forked from cite-architecture/citemicroservices
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathciteMicros-1.1.2.go
1524 lines (1460 loc) · 59.1 KB
/
citeMicros-1.1.2.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 main
//***Import Block: imports necessary libraries***
import (
"encoding/csv"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strings"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/jcelliott/lumber"
)
var clog = lumber.NewConsoleLogger(lumber.INFO)
//***Type Defenition Block: defines necessary data structures***
//Stores CTSURN information. Used in splitCTS, isCTSURN and functions in the Endpoint Handling Block.
type CTSURN struct {
Stem string
Reference string
}
//Stores Node information. Used in NodeResponse.
type Node struct {
URN []string `json:"urn"`
Text []string `json:"text,omitempty"`
Previous []string `json:"previous"`
Next []string `json:"next"`
Index int `json:"sequence"`
}
//Stores version information which are added to CITEResponse for further processing. Used in ReturnCiteVersion
type Versions struct {
Texts string `json:"texts"`
Textcatalog string `json:"textatalog,omitempty"`
Citedata string `json:"citedata,omitempty"`
Citecatalog string `json:"citecatalog,omitempty"`
Citerelations string `json:"citerelations,omitempty"`
Citeextensions string `json:"citeextensions,omitempty"`
DSE string `json:"dse,omitempty"`
ORCA string `json:"orca,omitempty"`
}
//Stores cite version information and a versions variable which are parsed to JSON format and displayed. Used in ReturnCiteVersion
type CITEResponse struct {
Status string `json:"status"`
Service string `json:"service"`
Versions Versions `json:"versions"`
}
//Stores text version information which are parsed to JSON format and displayed. Used in ReturnTextsVersion
type VersionResponse struct {
Status string `json:"status"`
Service string `json:"service"`
Version string `json:"version"`
}
//Stores node response results which are later parsed to JSON format and displayed. Used throughout the Endpoint Handling Block.
type NodeResponse struct {
requestURN []string `json:"requestURN"`
Status string `json:"status"`
Service string `json:"service"`
Message string `json:"message,omitempty"`
URN []string `json:"urns,omitempty"`
Nodes []Node `json:""`
}
//Stores URN response results, which are passed to ReturnWorkURNS for further processing, parsing to JSON format and displaying. Used in ParseURNS.
type URNResponse struct {
requestURN []string `json:"requestURN"`
Status string `json:"status"`
Service string `json:"service"`
Message string `json:"message,omitempty"`
URN []string `json:"urns"`
}
//Stores catalog response results, which are parsed to JSON format and displayed. Used in ReturnCatalog.
type CatalogResponse struct {
Status string `json:"status"`
Service string `json:"service"`
Message string `json:"message,omitempty"`
URN []string `json:"urns"`
}
//Stores work information for transfer to other functions. Used in ParseWork and the Endpoint Handling Block.
type Work struct {
WorkURN string
URN []string
Text []string
Index []int
}
//Holds multiple Works. Not in use yet.
type Collection struct {
Works []Work
}
//Stores CEX catalog entry information. Format of CEX catalog seems not to be fixed yet...
type CatalogEntry struct {
URN string
CitationScheme string
GroupName string
WorkTitle string
VersionLabel string
ExemplarLabel string
Online string
Lang string
}
//Stores catalog entries. Used in ParseCatalog to transfer results to ReturnCatalog.
type Catalog struct {
CatalogEntries []CatalogEntry
}
//Stores a sourcetext. Used by parsing functions and in Endpoint Handling Block.
type CTSParams struct {
Sourcetext string
}
//Stores server configuration. Used in all functions that need access to server parameters and the source.
type ServerConfig struct {
Host string `json:"host"`
Port string `json:"port"`
Source string `json:"cex_source"`
TestSource string `json:"test_cex_source"`
}
//***Helpfunction Block: These functions perform tasks that are necessary in multiple functions in the Endpoint Handling Block***
//Splits CTS string s into its Stem and Reference. Returns CTSURN.
func splitCTS(s string) CTSURN {
var result CTSURN //initialize result as CTSURN
result = CTSURN{Stem: strings.Join(strings.Split(s, ":")[0:4], ":"), Reference: strings.Split(s, ":")[4]} //first four parts go into the stem, last (fourth) part goes into reference
return result //returns as CTSURN
}
//Loads and parses JSON file defined by string s. Returns ServerConfig.
func LoadConfiguration(file string) ServerConfig {
var config ServerConfig //initialize config as ServerConfig
configFile, err := os.Open(file) //attempt to open file
defer configFile.Close() //push closing on call list
if err != nil { //error handling
fmt.Println(err.Error())
}
jsonParser := json.NewDecoder(configFile) //initialize jsonParser with configFile
jsonParser.Decode(&config) //parse configFile to config
return config //return ServerConfig config
}
//Returns boolf for wether string slice s contains string e.
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
//Returns bool for wether string s resembles a URN-range. Called in ReturnReff and ReturnPassage.
func isRange(s string) bool {
switch {
case len(strings.Split(s, ":")) < 5: //Test wether URN has reference..
return false //..else its not a range.
case strings.Contains(strings.Split(s, ":")[4], "-"): //The Reference must contain a hyphen ('-') indicating a range of URNs.
return true //Than it should be a range.
default: //In any other case..
return false //...its not a CTS URN range.
}
}
//Returns bool for whether length and structure of string s indicate it is a valid CTS URN. Called in Endpoint Handling Block.
func isCTSURN(s string) bool {
clog.Info("Testing wether \"" + s + "\" is a valid CTS URN")
test := strings.Split(s, ":") //initializes string array by splitting string into functional parts.
switch {
case len(test) < 4: //URN has to have at least 4 parts
clog.Warn("Not a valid CTS URN: not enough fields. (Should be 4 or 5)")
return false
case len(test) > 5: //URN may not have more thatn 5 parts.
clog.Warn("Not a valid CTS URN: too many fields. (Should be 4 or 5)")
return false
case test[0] != "urn": //First field of URN must be "urn"
clog.Warn("Not a valid CTS URN: first field must be urn")
return false
case test[1] != "cts": //Second field of URN must be "cts"
clog.Warn("Not a valid CTS URN: second field must be cts")
return false
default:
clog.Info("CTS URN is valid")
return true
}
}
//Returns bool for wether bool e is contained in bool slice s.
func boolcontains(s []bool, e bool) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
//Returns bool for wether string e is contained in string slice s on level 1 of the URN.
func level1contains(s []string, e string) bool {
var match []bool //initialize bool array match
for i := range s { //go through string array. if regex matches string plus one level
match2, _ := regexp.MatchString((e + "([:|.]*[0-9|a-z]+)$"), s[i])
match = append(match, match2)
}
return boolcontains(match, true)
}
//Returns bool for wether string e is contained in string slice s on level 2 of the URN.
func level2contains(s []string, e string) bool {
var match []bool
for i := range s {
match2, _ := regexp.MatchString((e + "([:|.]*[0-9|a-z]+).([0-9|a-z]+)$"), s[i])
match = append(match, match2)
}
return boolcontains(match, true)
}
//Returns bool for wether string e is contained in string slice s on level 3 of the URN.
func level3contains(s []string, e string) bool {
var match []bool
for i := range s {
match2, _ := regexp.MatchString((e + "([:|.]*[0-9|a-z]+).([0-9|a-z]+).([0-9|a-z]+)$"), s[i])
match = append(match, match2)
}
return boolcontains(match, true)
}
//Returns bool for wether string e is contained in string slice s on level 4 of the URN.
func level4contains(s []string, e string) bool {
var match []bool
for i := range s {
match2, _ := regexp.MatchString((e + "([:|.]*[0-9|a-z]+).([0-9|a-z]+).([0-9|a-z]+).([0-9|a-z]+)$"), s[i])
match = append(match, match2)
}
return boolcontains(match, true)
}
//Removes dublicate URNs from elements. Returns a slice of all unique elements.
func removeDuplicatesUnordered(elements []string) []string {
encountered := map[string]bool{} //initalize bool map with string keys
// Create a map of all unique elements.
for v := range elements {
encountered[elements[v]] = true //all elements are set to true
}
// Place all keys from the map into a slice.
result := []string{}
for key, _ := range encountered {
result = append(result, key) //append every key to the slice
}
return result
}
//***Main Block***
//Initializes mux server, loads configuration from config file, sets the serverIP, maps endpoints to respective funtions. Initialises the headers.
func main() {
clog.Info("Starting up local server.")
confvar := LoadConfiguration("./config.json")
serverIP := confvar.Port
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/cite", ReturnCiteVersion)
router.HandleFunc("/texts", ReturnWorkURNS)
router.HandleFunc("/texts/version", ReturnTextsVersion)
router.HandleFunc("/catalog", ReturnCatalog)
router.HandleFunc("/texts/first/{URN}", ReturnFirst)
router.HandleFunc("/texts/last/{URN}", ReturnLast)
router.HandleFunc("/texts/previous/{URN}", ReturnPrev)
router.HandleFunc("/texts/next/{URN}", ReturnNext)
router.HandleFunc("/texts/urns/{URN}", ReturnReff)
router.HandleFunc("/catalog/{URN}", ReturnCatalog)
router.HandleFunc("/texts/{URN}", ReturnPassage)
router.HandleFunc("/{CEX}/texts/", ReturnWorkURNS)
router.HandleFunc("/{CEX}/catalog/", ReturnCatalog)
router.HandleFunc("/{CEX}/texts/first/{URN}", ReturnFirst)
router.HandleFunc("/{CEX}/texts/last/{URN}", ReturnLast)
router.HandleFunc("/{CEX}/texts/previous/{URN}", ReturnPrev)
router.HandleFunc("/{CEX}/texts/next/{URN}", ReturnNext)
router.HandleFunc("/{CEX}/texts/urns/{URN}", ReturnReff)
router.HandleFunc("/{CEX}/catalog/{URN}", ReturnCatalog)
router.HandleFunc("/{CEX}/texts/{URN}", ReturnPassage)
router.HandleFunc("/", ReturnCiteVersion)
headersOk := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type"})
originsOk := handlers.AllowedOrigins([]string{os.Getenv("ORIGIN_ALLOWED")})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
clog.Info("Server is running")
clog.Info("Listening at" + serverIP + "...")
log.Fatal(http.ListenAndServe(serverIP, handlers.CORS(originsOk, headersOk, methodsOk)(router)))
}
//Fetches data from the url. Returns byte slice. Error handling implemented.
func getContent(url string) ([]byte, error) {
resp, err := http.Get(url) //get response from server
if err != nil {
return nil, fmt.Errorf("GET error: %v", err) //return in case of GET error
}
defer resp.Body.Close() //return in case of http status error
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Status error: %v", resp.StatusCode)
}
data, err := ioutil.ReadAll(resp.Body) //read response into byte slice
if err != nil { //return in case of read error
return nil, fmt.Errorf("Read body: %v", err)
}
return data, nil
}
//ReturnWorkURNS returns the URNs as found in the #!ctsdata block of the CEX file
func ReturnWorkURNS(w http.ResponseWriter, r *http.Request) {
clog.Info("Called function: ReturWorkURNS")
confvar := LoadConfiguration("config.json")
vars := mux.Vars(r)
requestCEX := ""
requestCEX = vars["CEX"]
var sourcetext string
switch {
case requestCEX != "":
sourcetext = confvar.Source + requestCEX + ".cex"
clog.Info("CEX-file provided in URL: " + requestCEX + ". Using " + sourcetext + ".")
default:
sourcetext = confvar.TestSource
clog.Info("No CEX-file provided in URL. Using " + confvar.TestSource + " from congfig instead.")
}
result := ParseURNS(CTSParams{Sourcetext: sourcetext})
for i := range result.URN {
result.URN[i] = strings.Join(strings.Split(result.URN[i], ":")[0:4], ":")
result.URN[i] = result.URN[i] + ":"
}
result.URN = removeDuplicatesUnordered(result.URN)
result.Service = "/texts"
result.requestURN = []string{}
resultJSON, _ := json.Marshal(result)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
fmt.Fprintln(w, string(resultJSON))
clog.Info("ReturWorkURNS executed succesfully")
}
func ParseURNS(p CTSParams) URNResponse { //suggestion: change name to ParseURNSFromCTSdata
clog.Info("Parsing URNS from #!ctsdata")
input_file := p.Sourcetext
data, err := getContent(input_file)
if err != nil {
return URNResponse{Status: "Exception", Message: "Couldn't open connection."}
}
str := string(data)
// Remove comments
str = strings.Split(str, "#!ctsdata")[1]
str = strings.Split(str, "#!")[0]
re := regexp.MustCompile("(?m)[\r\n]*^//.*$")
str = re.ReplaceAllString(str, "")
reader := csv.NewReader(strings.NewReader(str))
reader.Comma = '#'
reader.LazyQuotes = true
reader.FieldsPerRecord = 2
var response URNResponse
for {
line, error := reader.Read()
if error == io.EOF {
break
} else if error != nil {
log.Fatal(error)
}
response.URN = append(response.URN, line[0])
}
response.Status = "Success"
clog.Info("URNS parsed succesfully")
return response
}
//ParseWork extracts the relevant data out of the Sourcetext.
func ParseWork(p CTSParams) Work {
clog.Info("Parsing work")
input_file := p.Sourcetext //get information out of Sourcetext (string?)
data, err := getContent(input_file) //get data out of input_file
if err != nil {
log.Fatal(err) //log error
return Work{} //return empty work if saving in data failed
}
str := string(data) //save data in str
str = strings.Split(str, "#!ctsdata")[1] //split data at #!ctsdata and take the second part
str = strings.Split(str, "#!")[0] // split at #! and take the first part in case there is any other funtional part after #!ctsdata
re := regexp.MustCompile("(?m)[\r\n]*^//.*$") //initialize regex to remove all newlines and carriage returns
str = re.ReplaceAllString(str, "") //remove unnecessary characters
reader := csv.NewReader(strings.NewReader(str)) //initialize csv reader with str
reader.Comma = '#' //set # as seperator; sits between URN and respective text
reader.LazyQuotes = true
reader.FieldsPerRecord = 2 //specifies that each read line will have two fields
var response Work //initialize return value (Work)
for {
line, error := reader.Read() //read every line with prepared reader ([]string)
if error == io.EOF { //leave for loop it EOF is reached
break
} else if error != nil {
log.Fatal(error) //log error
}
response.URN = append(response.URN, line[0]) //add first field of []line to URNs
response.Text = append(response.Text, line[1]) //add seconf field of []line to Texts
}
clog.Info("Work parsed succesfully")
return response
}
func ParseCatalog(p CTSParams) Catalog {
clog.Info("Parsing catalog")
input_file := p.Sourcetext //get information out of Sourcetext (string?)
data, err := getContent(input_file) //get data out of input_file
if err != nil {
clog.Error("Parsing Catalog failed. Returning empty catalog")
log.Fatal(err)
return Catalog{} //return empty Catalog if loading data failed
}
str := string(data) //save data in str
//ToDo: add regex that tests for #!ctscatalog re :=regexp.MatchString("#!ctscatalog", str)
str = strings.Split(str, "#!ctscatalog")[1] //split data at #!ctscatalog and take the second part
str = strings.Split(str, "#!")[0] // split at #! and take the first part in case there is any other funtional part
re := regexp.MustCompile("(?m)[\r\n]*^//.*$") //initialize regex to remove all newlines and carriage returns
str = re.ReplaceAllString(str, "") //remove unnecessary characters
// log.Println("String: " + str)
reader := csv.NewReader(strings.NewReader(str)) //initialize csv reader with str
reader.Comma = '#' //set # as seperator; sits between URN and respective text
reader.LazyQuotes = true //check that
reader.FieldsPerRecord = 0 //specifies that each read line will have as many fields as first line
var response Catalog //initialize return value (Catalog)
for {
line, error := reader.Read() //read every line with prepared reader ([]string)
if error == io.EOF { //leave for loop it EOF is reached
break
} else if error != nil {
log.Fatal(error) //log error
}
var entry CatalogEntry //initialize entry variable to add to Catalog
entry.URN = line[0] //add fields of []line to respective fields of entry
entry.CitationScheme = line[1]
entry.GroupName = line[2]
entry.WorkTitle = line[3]
entry.VersionLabel = line[4]
entry.ExemplarLabel = line[5]
entry.Online = line[6]
if reader.FieldsPerRecord == 8 { //This solution will not suffice...
entry.Lang = line[7]
}
if isCTSURN(entry.URN) {
response.CatalogEntries = append(response.CatalogEntries, entry)
}
}
clog.Info("Catalog parsed succesfully")
return response
}
//Endpoint Handling Block: contains the handle functions that are executed according to the request.
func ReturnCiteVersion(w http.ResponseWriter, r *http.Request) {
clog.Info("Called function: ReturnCiteVersion")
var result CITEResponse
result = CITEResponse{Status: "Success",
Service: "/cite",
Versions: Versions{Texts: "1.1.0", Textcatalog: ""}}
resultJSON, _ := json.Marshal(result)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
clog.Info("ReturnCiteVersion executed succesfully")
fmt.Fprintln(w, string(resultJSON))
}
func ReturnTextsVersion(w http.ResponseWriter, r *http.Request) {
clog.Info("Called function: ReturnTextsVersion")
var result VersionResponse
result = VersionResponse{
Status: "Success",
Service: "/texts/version",
Version: "1.1.0"}
resultJSON, _ := json.Marshal(result)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
clog.Info("ReturnTextsVersion executed succesfully")
fmt.Fprintln(w, string(resultJSON))
}
func ReturnFirst(w http.ResponseWriter, r *http.Request) {
clog.Info("Called function: ReturnFirst")
confvar := LoadConfiguration("config.json")
vars := mux.Vars(r)
requestCEX := ""
requestCEX = vars["CEX"]
var sourcetext string
switch {
case requestCEX != "":
sourcetext = confvar.Source + requestCEX + ".cex"
clog.Info("CEX-file provided in URL: " + requestCEX + ". Using " + sourcetext + ".")
default:
sourcetext = confvar.TestSource
clog.Info("No CEX-file provided in URL. Using " + confvar.TestSource + " from config instead.")
}
requestURN := vars["URN"]
//log.Println("Requested URN: " + requestURN)
if isCTSURN(requestURN) != true {
message := requestURN + " is not valid CTS."
result := NodeResponse{requestURN: []string{requestURN}, Status: "Exception", Message: message}
result.Service = "/texts/first"
resultJSON, _ := json.Marshal(result)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
fmt.Fprintln(w, string(resultJSON))
clog.Info("ReturnLast executed succesfully")
return
}
workResult := ParseWork(CTSParams{Sourcetext: sourcetext})
works := append([]string(nil), workResult.URN...)
for i := range workResult.URN {
works[i] = strings.Join(strings.Split(workResult.URN[i], ":")[0:4], ":")
}
works = removeDuplicatesUnordered(works)
workindex := 0
for i := range works {
if strings.Contains(requestURN, works[i]) {
teststring := works[i] + ":"
switch {
case requestURN == works[i]:
workindex = i + 1
case strings.Contains(requestURN, teststring):
workindex = i + 1
}
}
}
var result NodeResponse
switch {
case workindex == 0:
message := "No results for " + requestURN
clog.Error("Requested URN not in works. Returning exception message")
result = NodeResponse{requestURN: []string{requestURN}, Status: "Exception", Message: message}
default:
var RequestedWork Work
RequestedWork.WorkURN = works[workindex-1]
runindex := 0
for i := range workResult.URN {
if strings.Join(strings.Split(workResult.URN[i], ":")[0:4], ":") == RequestedWork.WorkURN {
RequestedWork.URN = append(RequestedWork.URN, workResult.URN[i])
RequestedWork.Text = append(RequestedWork.Text, workResult.Text[i])
runindex++
RequestedWork.Index = append(RequestedWork.Index, runindex)
}
}
result = NodeResponse{requestURN: []string{requestURN},
Status: "Success",
Nodes: []Node{Node{URN: []string{RequestedWork.URN[0]},
Text: []string{RequestedWork.Text[0]},
Next: []string{RequestedWork.URN[1]},
Index: RequestedWork.Index[0]}}}
}
result.Service = "/texts/first"
resultJSON, _ := json.Marshal(result)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
clog.Info("ReturnFirst executed succesfully")
fmt.Fprintln(w, string(resultJSON))
}
func ReturnLast(w http.ResponseWriter, r *http.Request) {
clog.Info("Called function: ReturnLast")
confvar := LoadConfiguration("config.json")
vars := mux.Vars(r)
requestCEX := ""
requestCEX = vars["CEX"]
var sourcetext string
switch {
case requestCEX != "":
sourcetext = confvar.Source + requestCEX + ".cex"
clog.Info("CEX-file provided in URL: " + requestCEX + ". Using " + sourcetext + ".")
default:
sourcetext = confvar.TestSource
clog.Info("No CEX-file provided in URL. Using " + confvar.TestSource + " from config instead.")
}
requestURN := vars["URN"]
if isCTSURN(requestURN) != true {
message := requestURN + " is not valid CTS."
result := NodeResponse{requestURN: []string{requestURN}, Status: "Exception", Message: message}
result.Service = "/texts/last"
resultJSON, _ := json.Marshal(result)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
fmt.Fprintln(w, string(resultJSON))
clog.Info("ReturnLast executed succesfully")
return
}
workResult := ParseWork(CTSParams{Sourcetext: sourcetext})
works := append([]string(nil), workResult.URN...)
for i := range workResult.URN {
works[i] = strings.Join(strings.Split(workResult.URN[i], ":")[0:4], ":")
}
works = removeDuplicatesUnordered(works)
workindex := 0
for i := range works {
if strings.Contains(requestURN, works[i]) {
teststring := works[i] + ":"
switch {
case requestURN == works[i]:
workindex = i + 1
case strings.Contains(requestURN, teststring):
workindex = i + 1
}
}
}
var result NodeResponse
switch {
case workindex == 0:
message := "No results for " + requestURN
result = NodeResponse{requestURN: []string{requestURN}, Status: "Exception", Message: message}
default:
var RequestedWork Work
RequestedWork.WorkURN = works[workindex-1]
runindex := 0
for i := range workResult.URN {
if strings.Join(strings.Split(workResult.URN[i], ":")[0:4], ":") == RequestedWork.WorkURN {
RequestedWork.URN = append(RequestedWork.URN, workResult.URN[i])
RequestedWork.Text = append(RequestedWork.Text, workResult.Text[i])
runindex++
RequestedWork.Index = append(RequestedWork.Index, runindex)
}
}
result = NodeResponse{requestURN: []string{requestURN},
Status: "Success",
Nodes: []Node{Node{URN: []string{RequestedWork.URN[len(RequestedWork.URN)-1]},
Text: []string{RequestedWork.Text[len(RequestedWork.URN)-1]},
Previous: []string{RequestedWork.URN[len(RequestedWork.URN)-2]},
Index: RequestedWork.Index[len(RequestedWork.URN)-1]}}}
}
result.Service = "/texts/last"
resultJSON, _ := json.Marshal(result)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
fmt.Fprintln(w, string(resultJSON))
}
func ReturnPrev(w http.ResponseWriter, r *http.Request) {
clog.Info("Called function: ReturnPrev")
confvar := LoadConfiguration("config.json")
vars := mux.Vars(r)
requestCEX := ""
requestCEX = vars["CEX"]
var sourcetext string
switch {
case requestCEX != "":
sourcetext = confvar.Source + requestCEX + ".cex"
clog.Info("CEX-file provided in URL: " + requestCEX + ". Using " + sourcetext + ".")
default:
sourcetext = confvar.TestSource
clog.Info("No CEX-file provided in URL. Using " + confvar.TestSource + " from config instead.")
}
requestURN := vars["URN"]
if isCTSURN(requestURN) != true {
message := requestURN + " is not valid CTS."
result := NodeResponse{requestURN: []string{requestURN}, Status: "Exception", Message: message}
result.Service = "/texts/previous"
resultJSON, _ := json.Marshal(result)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
fmt.Fprintln(w, string(resultJSON))
clog.Info("ReturnReff executed succesfully")
return
}
workResult := ParseWork(CTSParams{Sourcetext: sourcetext})
works := append([]string(nil), workResult.URN...)
for i := range workResult.URN {
works[i] = strings.Join(strings.Split(workResult.URN[i], ":")[0:4], ":")
}
works = removeDuplicatesUnordered(works)
workindex := 0
for i := range works {
if strings.Contains(requestURN, works[i]) {
teststring := works[i] + ":"
switch {
case requestURN == works[i]:
workindex = i + 1
case strings.Contains(requestURN, teststring):
workindex = i + 1
}
}
}
var result NodeResponse
switch {
case workindex == 0:
message := "No results for " + requestURN
result = NodeResponse{requestURN: []string{requestURN}, Status: "Exception", Message: message}
default:
var RequestedWork Work
RequestedWork.WorkURN = works[workindex-1]
runindex := 0
for i := range workResult.URN {
if strings.Join(strings.Split(workResult.URN[i], ":")[0:4], ":") == RequestedWork.WorkURN {
RequestedWork.URN = append(RequestedWork.URN, workResult.URN[i])
RequestedWork.Text = append(RequestedWork.Text, workResult.Text[i])
runindex++
RequestedWork.Index = append(RequestedWork.Index, runindex)
}
}
var requestedIndex int
for i := range RequestedWork.URN {
if RequestedWork.URN[i] == requestURN {
requestedIndex = i
}
}
switch {
case contains(RequestedWork.URN, requestURN):
switch {
case requestedIndex == 0:
result = NodeResponse{requestURN: []string{requestURN}, Status: "Success", Nodes: []Node{}}
case requestedIndex-1 == 0:
result = NodeResponse{requestURN: []string{requestURN},
Status: "Success",
Nodes: []Node{Node{URN: []string{RequestedWork.URN[requestedIndex-1]},
Text: []string{RequestedWork.Text[requestedIndex-1]},
Next: []string{RequestedWork.URN[requestedIndex]},
Index: RequestedWork.Index[requestedIndex-1]}}}
default:
result = NodeResponse{requestURN: []string{requestURN},
Status: "Success",
Nodes: []Node{Node{URN: []string{RequestedWork.URN[requestedIndex-1]},
Text: []string{RequestedWork.Text[requestedIndex-1]},
Next: []string{RequestedWork.URN[requestedIndex]},
Previous: []string{RequestedWork.URN[requestedIndex-2]},
Index: RequestedWork.Index[requestedIndex-1]}}}
}
default:
message := "Could not find node to " + requestURN + " in source."
result = NodeResponse{requestURN: []string{requestURN}, Status: "Exception", Message: message}
}
}
result.Service = "/texts/previous"
resultJSON, _ := json.Marshal(result)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
fmt.Fprintln(w, string(resultJSON))
clog.Info("ReturnPrev executed succesfully")
}
func ReturnNext(w http.ResponseWriter, r *http.Request) {
clog.Info("Called function: ReturnNext")
confvar := LoadConfiguration("config.json")
vars := mux.Vars(r)
requestCEX := ""
requestCEX = vars["CEX"]
var sourcetext string
switch {
case requestCEX != "":
sourcetext = confvar.Source + requestCEX + ".cex"
clog.Info("CEX-file provided in URL: " + requestCEX + ". Using " + sourcetext + ".")
default:
sourcetext = confvar.TestSource
clog.Info("No CEX-file provided in URL. Using " + confvar.TestSource + " from config instead.")
}
requestURN := vars["URN"]
if isCTSURN(requestURN) != true {
message := requestURN + " is not valid CTS."
result := NodeResponse{requestURN: []string{requestURN}, Status: "Exception", Message: message}
result.Service = "/texts/next"
resultJSON, _ := json.Marshal(result)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
fmt.Fprintln(w, string(resultJSON))
clog.Info("ReturnReff executed succesfully")
return
}
workResult := ParseWork(CTSParams{Sourcetext: sourcetext})
works := append([]string(nil), workResult.URN...)
for i := range workResult.URN {
works[i] = strings.Join(strings.Split(workResult.URN[i], ":")[0:4], ":")
}
works = removeDuplicatesUnordered(works)
workindex := 0
for i := range works {
if strings.Contains(requestURN, works[i]) {
teststring := works[i] + ":"
switch {
case requestURN == works[i]:
workindex = i + 1
case strings.Contains(requestURN, teststring):
workindex = i + 1
}
}
}
var result NodeResponse
switch {
case workindex == 0:
message := "No results for " + requestURN
result = NodeResponse{requestURN: []string{requestURN}, Status: "Exception", Message: message}
default:
var RequestedWork Work
RequestedWork.WorkURN = works[workindex-1]
runindex := 0
for i := range workResult.URN {
if strings.Join(strings.Split(workResult.URN[i], ":")[0:4], ":") == RequestedWork.WorkURN {
RequestedWork.URN = append(RequestedWork.URN, workResult.URN[i])
RequestedWork.Text = append(RequestedWork.Text, workResult.Text[i])
runindex++
RequestedWork.Index = append(RequestedWork.Index, runindex)
}
}
var requestedIndex int
for i := range RequestedWork.URN {
if RequestedWork.URN[i] == requestURN {
requestedIndex = i
}
}
switch {
case contains(RequestedWork.URN, requestURN):
switch {
case requestedIndex == len(RequestedWork.URN)-1:
result = NodeResponse{requestURN: []string{requestURN}, Status: "Success", Nodes: []Node{}}
case requestedIndex+1 == len(RequestedWork.URN)-1:
result = NodeResponse{requestURN: []string{requestURN},
Status: "Success",
Nodes: []Node{Node{URN: []string{RequestedWork.URN[requestedIndex+1]},
Text: []string{RequestedWork.Text[requestedIndex+1]},
Previous: []string{RequestedWork.URN[requestedIndex]},
Index: RequestedWork.Index[requestedIndex+1]}}}
default:
result = NodeResponse{requestURN: []string{requestURN},
Status: "Success",
Nodes: []Node{Node{URN: []string{RequestedWork.URN[requestedIndex+1]},
Text: []string{RequestedWork.Text[requestedIndex+1]},
Next: []string{RequestedWork.URN[requestedIndex+2]},
Previous: []string{RequestedWork.URN[requestedIndex]},
Index: RequestedWork.Index[requestedIndex+1]}}}
}
default:
message := "Could not find node to " + requestURN + " in source."
result = NodeResponse{requestURN: []string{requestURN}, Status: "Exception", Message: message}
}
}
result.Service = "/texts/next"
resultJSON, _ := json.Marshal(result)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
clog.Info("ReturnNext executed succesfully")
fmt.Fprintln(w, string(resultJSON))
}
func ReturnReff(w http.ResponseWriter, r *http.Request) {
clog.Info("Called function: ReturnReff")
confvar := LoadConfiguration("config.json") //load configuration from json file (ServerConfig)
vars := mux.Vars(r) //load vars from mux config to get CEX and URN information )[]string ?)
requestCEX := "" //initalize CEX variable (string)
requestCEX = vars["CEX"] //save CEX name in CEX variable
var sourcetext string //initialize sourcetext variable; will hold CEX data
switch { //switch to determine wether a CEX file was specified
case requestCEX != "":
sourcetext = confvar.Source + requestCEX + ".cex" //build URL to CEX file if CEX file was specified
clog.Info("CEX-file provided in URL: " + requestCEX + ". Using " + sourcetext + ".")
default:
sourcetext = confvar.TestSource //use TestSource as URL to CEX-file as found in config.json
clog.Info("No CEX-file provided in URL. Using " + confvar.TestSource + " from config instead.")
}
requestURN := vars["URN"] //safe requested URN
if isCTSURN(requestURN) != true { //test if given URN is valid (bool)
message := requestURN + " is not valid CTS." //build message part of NodeResponse
result := NodeResponse{requestURN: []string{requestURN}, Status: "Exception", Message: message} //building result (NodeResponse)
result.Service = "/texts/urns" // adding Service part to result (NodeResponse)
resultJSON, _ := json.Marshal(result) //parsing result to JSON format (_ would contain err)
w.Header().Set("Content-Type", "application/json; charset=utf-8") //set output format
fmt.Fprintln(w, string(resultJSON)) //output
clog.Info("ReturnReff executed succesfully")
return
}
workResult := ParseWork(CTSParams{Sourcetext: sourcetext}) //parse the work
works := append([]string(nil), workResult.URN...) // append URNs from workResult to works
for i := range workResult.URN {
works[i] = strings.Join(strings.Split(workResult.URN[i], ":")[0:4], ":") //crop URNs in []work to first four parts of URN
}
works = removeDuplicatesUnordered(works) //remove dublicate URNS
workindex := 0 //initialize variable to save index of works to work with
for i := range works {
if strings.Contains(requestURN, works[i]) {
teststring := works[i] + ":" //add colon which was lost during joins
switch {
case requestURN == works[i]:
workindex = i + 1
case strings.Contains(requestURN, teststring): //should have matched before already, shouldn't it?
workindex = i + 1
}
}
}
var result URNResponse //initialize result (URNResponse)
switch {
case workindex == 0: //if requested URN is not among URNs in works prepare and display message accordingly
message := "No results for " + requestURN
result = URNResponse{requestURN: []string{requestURN}, Status: "Exception", Message: message}
result.Service = "/texts/urns"
resultJSON, _ := json.Marshal(result)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
fmt.Fprintln(w, string(resultJSON))
default: // if requested URN is among URNs in work
var RequestedWork Work
RequestedWork.WorkURN = works[workindex-1]
runindex := 0
for i := range workResult.URN {
if strings.Join(strings.Split(workResult.URN[i], ":")[0:4], ":") == RequestedWork.WorkURN {
RequestedWork.URN = append(RequestedWork.URN, workResult.URN[i])
RequestedWork.Text = append(RequestedWork.Text, workResult.Text[i])
runindex++
RequestedWork.Index = append(RequestedWork.Index, runindex)
}
}
switch {
case isRange(requestURN): //if range is requested,
ctsurn := splitCTS(requestURN) //split URN into its stem and reference
ctsrange := strings.Split(ctsurn.Reference, "-") //split reference along the hyphen
startURN := ctsurn.Stem + ":" + ctsrange[0] //define startURN as the first field
endURN := ctsurn.Stem + ":" + ctsrange[1] //definde endURN as the second field
var startindex, endindex int
switch { //find startindex in RequestedWork.URN
case contains(RequestedWork.URN, startURN): //if the startURN is in the URNs of RequestedWork use its index as startindex
for i := range RequestedWork.URN {
if RequestedWork.URN[i] == startURN {
startindex = i
}
}
case level1contains(RequestedWork.URN, startURN):
var match []bool
for i := range RequestedWork.URN {
match2, _ := regexp.MatchString((startURN + "([:|.]*[0-9|a-z]+)$"), RequestedWork.URN[i])
match = append(match, match2)
}
for i := range match {
if match[i] == true {
startindex = i
break
}
}
case level2contains(RequestedWork.URN, startURN):
var match []bool
for i := range RequestedWork.URN {
match2, _ := regexp.MatchString((startURN + "([:|.]*[0-9|a-z]+).([0-9|a-z]+)$"), RequestedWork.URN[i])
match = append(match, match2)
}
for i := range match {
if match[i] == true {
startindex = i
break
}
}
case level3contains(RequestedWork.URN, startURN):
var match []bool
for i := range RequestedWork.URN {
match2, _ := regexp.MatchString((startURN + "([:|.]*[0-9|a-z]+).([0-9|a-z]+).([0-9|a-z]+)$"), RequestedWork.URN[i])
match = append(match, match2)
}
for i := range match {
if match[i] == true {
startindex = i
break
}
}
case level4contains(RequestedWork.URN, startURN):
var match []bool
for i := range RequestedWork.URN {
match2, _ := regexp.MatchString((startURN + "([:|.]*[0-9|a-z]+).([0-9|a-z]+).([0-9|a-z]+).([0-9|a-z]+)$"), RequestedWork.URN[i])
match = append(match, match2)
}
for i := range match {
if match[i] == true {
startindex = i
break
}
}
default:
startindex = 0
}
switch { //find endindex in RequestedWork.URN
case contains(RequestedWork.URN, endURN):
for i := range RequestedWork.URN {
if RequestedWork.URN[i] == endURN {
endindex = i
}
}
case level1contains(RequestedWork.URN, endURN):
var match []bool
for i := range RequestedWork.URN {
match2, _ := regexp.MatchString((endURN + "([:|.]*[0-9|a-z]+)$"), RequestedWork.URN[i])
match = append(match, match2)
}
for i := len(match) - 1; i >= 0; i-- {
if match[i] == true {
endindex = i
break