-
Notifications
You must be signed in to change notification settings - Fork 5
/
ISOAbstractObject.R
1710 lines (1612 loc) · 69.2 KB
/
ISOAbstractObject.R
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
#' ISOAbstractObject
#'
#' @docType class
#' @importFrom utils packageDescription
#' @importFrom R6 R6Class
#' @importFrom methods is
#' @importFrom methods as
#' @importFrom utils read.csv
#' @import XML
#' @import httr
#' @import readr
#' @import jsonlite
#' @import keyring
#' @import crayon
#' @export
#' @keywords ISO metadata element
#' @return Object of \code{\link{R6Class}} for modelling an ISO Metadata Element
#' @format \code{\link{R6Class}} object.
#'
#' @section Static Methods:
#' \describe{
#' \item{\code{getISOStandardByPrefix(prefix)}}{
#' Inherit the ISO (and/or OGC) standard reference for a given standard prefix (e.g. GMD).
#' The object returned is a \code{data.frame} containing the specification reference
#' and title.
#' }
#' \item{\code{getISOStandard(clazz)}}{
#' Inherit the ISO (and/or OGC) standard reference for a given \pkg{geometa} class.
#' The object returned is a \code{data.frame} containing the specification reference
#' and title.
#' }
#' \item{\code{getISOClasses(extended, pretty)}}{
#' Get the list of classes supported by \pkg{geometa}. By default, \code{extended} is
#' set to \code{FALSE} (restrained to \pkg{geometa} environment). If \code{TRUE}, this
#' allows to list eventual classes loaded in your global environment and that extend
#' \pkg{geometa} classes. The argument \code{pretty} gives a the list of classes and
#' associated ISO/OGC standard information as \code{data.frame}.
#' }
#' \item{\code{getISOClassByNode(node)}}{
#' Inherit the ISO class matching an XML document or node
#' }
#' \item{\code{compare(metadataElement1, metadataElement2)}}{
#' Compares two metadata elements objects. Returns TRUE if they are equal,
#' FALSE otherwise. The comparison of object is done by comparing the XML
#' representation of the objects (since no R6 object comparison method seems
#' to exist)
#' }
#' }
#'
#' @note Abstract ISO Metadata class used internally by geometa
#'
#' @author Emmanuel Blondel <emmanuel.blondel1@@gmail.com>
#'
ISOAbstractObject <- R6Class("ISOAbstractObject",
inherit = geometaLogger,
cloneable = FALSE,
private = list(
xmlElement = "AbstractObject",
xmlNamespacePrefix = "GCO",
encoding = options("encoding"),
document = FALSE,
system_fields = c("wrap", "value_as_field", "valueDescription",
"element", "namespace", "defaults", "attrs", "printAttrs", "parentAttrs",
"codelistId", "measureType", "isNull", "anyElement"),
xmlComments = function(isoCompliant = NA, inspireReport = NULL){
comments <- list()
geometa <- packageDescription("geometa")
title <- paste0("ISO 19139 XML generated by geometa R package - Version ", geometa$Version)
isISOCompliant <- ifelse(is.na(isoCompliant),"NOT TESTED", ifelse(isoCompliant, "YES", "NO"))
ISOCompliance <- paste0("ISO 19139 XML compliance: ", isISOCompliant)
isINSPIRECompliant <- ifelse(is.null(inspireReport), "NOT TESTED", ifelse(inspireReport$Status=="PASSED", "YES", "NO"))
INSPIRECompliance <- paste0("INSPIRE compliance: ", isINSPIRECompliant)
createdOn <- paste0("Metadata Creation date/time: ", format(Sys.time(), "%Y-%m-%dT%H:%M:%S"))
geometaAuthor <- gsub(">","",gsub("<","",unlist(strsplit(as.character(eval(parse(text=geometa$Authors)))," \\["))[1]))
author <- paste0("\tContact: ", geometaAuthor)
infoPage <- paste0("\tURL: ", geometa$URL)
bugReport <- paste0("\tBugReports: ", geometa$BugReports)
idx <- 1
comments[[idx]] <- createdOn; idx <- idx+1
comments[[idx]] <- title; idx <- idx+1
comments[[idx]] <- ISOCompliance; idx <- idx+1
if(!is.null(inspireReport)){
comments[[idx]] <- INSPIRECompliance; idx <- idx+1
for(inspireAttr in names(inspireReport)){
if(!(inspireAttr %in% c("raw", "status"))){
comments[[idx]] <- sprintf("INSPIRE %s : %s", inspireAttr, inspireReport[[inspireAttr]])
idx <- idx+1
}
}
}
comments[[idx]] <- paste("geometa R package information:", author, infoPage, bugReport, sep="\n")
return(comments)
},
toComplexTypes = function(value){
newvalue <- value
#datetime types
if(regexpr(pattern = "^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})", value)>0){
if(endsWith(value, "Z")){
newvalue <- as.POSIXct(strptime(value, "%Y-%m-%dT%H:%M:%S"), tz = "UTC")
}else{
if(regexpr(pattern = "[[:space:]]", value)){
splits <- unlist(strsplit(value, " "))
value <- splits[1]
#TODO find a way to fetch "tzone" attribute -not solved for now
newvalue <- as.POSIXct(strptime(value, "%Y-%m-%dT%H:%M:%S"), tz = "")
}else{
newvalue <- as.POSIXct(strptime(value, "%Y-%m-%dT%H:%M:%S"), tz = "")
}
}
}else if(regexpr(pattern = "^(\\d{4})-(\\d{2})-(\\d{2})$", value)>0){
newvalue <- as.Date(as.POSIXct(strptime(value, "%Y-%m-%d"), tz = "UTC"))
}
return(newvalue)
},
fromComplexTypes = function(value){
#datetime types
if(suppressWarnings(all(class(value)==c("POSIXct","POSIXt")))){
tz <- attr(value, "tzone")
if(length(tz)>1){
if(tz %in% c("UTC","GMT")){
value <- format(value,"%Y-%m-%dT%H:%M:%S")
value <- paste0(value,"Z")
}else{
utc_offset <- format(value, "%z")
utc_offset <- paste0(substr(utc_offset,1,3),":",substr(utc_offset,4,5))
value <- paste0(format(value,"%Y-%m-%dT%H:%M:%S"), utc_offset)
}
}else{
value <- format(value,"%Y-%m-%dT%H:%M:%S")
}
}else if(class(value)[1] == "Date"){
value <- format(value,"%Y-%m-%d")
}
return(value)
},
xmlNodeToCharacter = function (x, ..., indent = "", tagSeparator = "\n")
{
out <- ""
if (length(xmlAttrs(x))) {
tmp <- paste(names(xmlAttrs(x)), paste("\"", XML:::insertEntities(xmlAttrs(x)),
"\"", sep = ""), sep = "=", collapse = " ")
} else{
tmp <- ""
}
if (length(x$namespaceDefinitions) > 0) {
k = as(x$namespaceDefinitions, "character")
ns = paste("xmlns", ifelse(nchar(names(k)), ":", ""),
names(k), "=", ddQuote(k), sep = "", collapse = " ")
} else{
ns <- ""
}
subIndent <- paste(indent, " ", sep = "")
if (is.logical(indent) && !indent) {
indent <- ""
subIndent <- FALSE
}
if (length(xmlChildren(x)) == 0) {
out <- paste(out,indent, paste("<", xmlName(x, TRUE), ifelse(tmp !=
"", " ", ""), tmp, ifelse(ns != "", " ", ""), ns,
"/>", tagSeparator, sep = ""), sep = "")
} else if (length(xmlChildren(x)) == 1 && inherits(xmlChildren(x)[[1]], "XMLTextNode")) {
out <- paste(out,indent, paste("<", xmlName(x, TRUE), ifelse(tmp !=
"", " ", ""), tmp, ifelse(ns != "", " ", ""), ns,
">", sep = ""), sep = "")
kid = xmlChildren(x)[[1]]
if (inherits(kid, "EntitiesEscaped"))
txt = xmlValue(kid)
else txt = XML:::insertEntities(xmlValue(kid))
out <- paste(out,txt, sep = "")
out <- paste(out,paste("</", xmlName(x, TRUE), ">", tagSeparator,
sep = ""), sep = "")
} else {
out <- paste(out,indent, paste("<", xmlName(x, TRUE), ifelse(tmp !=
"", " ", ""), tmp, ifelse(ns != "", " ", ""), ns,
">", tagSeparator, sep = ""), sep = "")
for (i in xmlChildren(x)){
out_child <- NULL
if(is(i,"XMLNode")){
if(is(i,"XMLCommentNode")){
out_child <- paste0(capture.output(i),collapse="")
}else{
out_child <- private$xmlNodeToCharacter(i)
}
}else{
out_child <- paste(as(i,"character"),tagSeparator,sep="")
}
if(!is.null(out_child)) out <- paste(out, out_child, sep="")
}
out<-paste(out,indent, paste("</", xmlName(x, TRUE), ">", tagSeparator,
sep = ""), sep = "")
}
return(out)
}
),
public = list(
#fields
#---------------------------------------------------------------------------
#'@field wrap wrap
wrap = TRUE,
#'@field element element
element = NA,
#'@field namespace namespace
namespace = NA,
#'@field defaults defaults
defaults = list(),
#'@field attrs attributes
attrs = list(),
#'@field printAttrs attributes to print
printAttrs = list(),
#'@field parentAttrs parent attributes
parentAttrs = NULL,
#'@field value value
value = NULL,
#'@field value_as_field value as field?
value_as_field = FALSE,
#'@field isNull is null?
isNull = FALSE,
#'@field anyElement any element?
anyElement = FALSE,
#'@description Initializes object
#'@param xml object of class \link{XMLInternalNode-class}
#'@param element element name
#'@param namespace namespace
#'@param attrs attrs
#'@param defaults defaults
#'@param wrap wrap?
#'@param value_as_field value as field?
initialize = function(xml = NULL, element = NULL, namespace = NULL,
attrs = list(), defaults = list(),
wrap = TRUE, value_as_field = FALSE){
if(!is.null(element)){ private$xmlElement <- element }
if(!is.null(namespace)){ private$xmlNamespacePrefix <- toupper(namespace)}
self$element = private$xmlElement
self$namespace = getISOMetadataNamespace(private$xmlNamespacePrefix)
self$attrs = attrs
self$defaults = defaults
self$wrap = wrap
self$value_as_field = value_as_field
if(!is.null(xml)){
self$decode(xml)
}
},
#Main methods
#---------------------------------------------------------------------------
#'@description Provides a custom print output (as tree) of the current class
#'@param ... args
#'@param depth class nesting depth
#'@param add_codelist_description Add codelist description. Default is \code{TRUE}
print = function(..., depth = 1, add_codelist_description = TRUE){
#list of fields to encode as XML
fields <- rev(names(self))
#fields
fields <- fields[!sapply(fields, function(x){
(class(self[[x]])[1] %in% c("environment", "function")) ||
(x %in% private$system_fields)
})]
if(!inherits(self, "GMLElement") && !inherits(self, "SWEElement")) cat(crayon::white(paste0("<", crayon::underline(self$getClassName()), ">")))
if(is(self, "ISOCodeListValue")){
clVal <- self$printAttrs$codeListValue
clDes <- self$codelistId$entries[self$codelistId$entries$value == clVal,"description"]
if(length(clDes)==0){
clDes <- self$valueDescription
}
cat(paste0(": ", clVal, if(add_codelist_description) crayon::cyan(paste0(" {",clDes,"}")) else ""))
}
for(field in fields){
fieldObj <- self[[field]]
#default values management
if(is.null(fieldObj) || (is.list(fieldObj) & length(fieldObj)==0)){
if(field %in% names(self$defaults)){
fieldObj <- self$defaults[[field]]
}
}
print_attrs <- function(obj){
paste(
sapply(names(obj$attrs), function(attrName){
paste0( crayon::magenta(attrName,"=",sep=""), crayon::green(obj$attrs[[attrName]]))
}
),
collapse=",")
}
#user values management
shift <- "...."
if(!is.null(fieldObj)){
if(is(fieldObj, "ISOAbstractObject")){
attrs_str <- ""
if(length(fieldObj$attrs)>0){
attrs <- print_attrs(fieldObj)
attrs_str <- paste0(" [",attrs,"] ")
}
cat(paste0("\n", paste(rep(shift, depth), collapse=""),"|-- ", crayon::italic(field), " ", attrs_str))
fieldObj$print(depth = depth+1, add_codelist_description = add_codelist_description)
}else if(is(fieldObj, "ISOAttributes")){
attrs <- print_attrs(fieldObj)
cat(paste0("\n",paste(rep(shift, depth), collapse=""),"|-- ", crayon::italic(field), " [",attrs,"]"))
}else if(is(fieldObj, "list")){
for(item in fieldObj){
if(is(item, "ISOAbstractObject")){
attrs_str <- ""
if(length(item$attrs)>0){
attrs <- print_attrs(item)
attrs_str <- paste0(" [",attrs,"] ")
}
cat(paste0("\n", paste(rep(shift, depth), collapse=""),"|-- ", crayon::italic(field), " ", attrs_str))
item$print(depth = depth+1, add_codelist_description = add_codelist_description)
if(is(item, "ISOCodeListValue")){
clVal <- item$printAttrs$codeListValue
clDes <- item$codelistId$entries[item$codelistId$entries$value == clVal,"description"]
cat(paste0(": ", clVal, if(add_codelist_description) crayon::cyan(paste0(" {",clDes,"}")) else ""))
}
}else if(is(item, "ISOAttributes")){
attrs <- print_attrs(item)
cat(paste0("\n",paste(rep(shift, depth), collapse=""),"|-- ", crayon::italic(field), " [",attrs,"]"))
}else if(is(item, "matrix")){
m <- paste(apply(item, 1L, function(x){
x <- lapply(x, function(el){
if(is.na(suppressWarnings(as.numeric(el))) & !all(sapply(item,class)=="character")){
el <- paste0("\"",el,"\"")
}else{
if(!is.na(suppressWarnings(as.numeric(el)))){
el <- as.numeric(el)
}
}
return(el)
})
return(paste(x, collapse = " "))
}), collapse = " ")
cat(paste0("\n",paste(rep(shift, depth), collapse=""),"|-- ", crayon::italic(field), ": ", crayon::bgWhite(m)))
}else{
cat(paste0("\n", paste(rep(shift, depth), collapse=""),"|-- ", crayon::italic(field), ": ", crayon::bgWhite(item)))
}
}
}else if (is(fieldObj,"matrix")){
m <- paste(apply(fieldObj, 1L, function(x){
x <- lapply(x, function(el){
if(is.na(suppressWarnings(as.numeric(el)))& !all(sapply(fieldObj,class)=="character")){
el <- paste0("\"",el,"\"")
}else{
if(!is.na(suppressWarnings(as.numeric(el)))){
el <- as.numeric(el)
}
}
return(el)
})
return(paste(x, collapse = " "))
}), collapse = " ")
cat(paste0("\n",paste(rep(shift, depth), collapse=""),"|-- ", crayon::italic(field), ": ", crayon::bgWhite(m)))
}else{
fieldObjP <- fieldObj
if(is(fieldObjP,"Date")|is(fieldObjP, "POSIXt")){
fieldObjP <- private$fromComplexTypes(fieldObjP)
}
cat(paste0("\n",paste(rep(shift, depth), collapse=""),"|-- ", crayon::italic(field), ": ", crayon::bgWhite(fieldObjP)))
}
}
}
invisible(self)
},
#'@description Decodes object from XML
#'@param xml object of class \link{XMLInternalNode-class}
decode = function(xml){
#remove comments if any (in case of document)
if(is(xml, "XMLInternalDocument")){
children <- xmlChildren(xml, encoding = private$encoding, addFinalizer = FALSE)
xml <- children[names(children) != "comment"][[1]]
}
xml_children <- xmlChildren(xml, encoding = private$encoding, addFinalizer = FALSE)
for(child in xml_children){
fieldName <- xmlName(child)
childElement <- child
nsPrefix <- ""
fNames <- unlist(strsplit(fieldName, ":"))
if(length(fNames)>1){
fieldName <- fNames[2]
}
if(!is(self, "ISOElementSequence")) {
if(!(fieldName %in% names(self)) & fieldName != "text" & !self$anyElement) next
}
wrap_fields <- FALSE
fieldClass <- NULL
parentAttrs <- NULL
if(!is(child, "XMLInternalTextNode")){
fieldClass <- ISOAbstractObject$getISOClassByNode(child)
nsPrefix <- names(xmlNamespace(child))
if(is.null(nsPrefix)){
#try to grab from ns prefix
childName <- xmlName(child, full = TRUE)
preftag <- unlist(strsplit(as(childName, "character"),":"))[1]
if(preftag!=childName) nsPrefix <- substring(preftag, 2, nchar(preftag))
}
if(is.null(fieldClass)){
parentAttrs <- as.list(xmlAttrs(child, TRUE, FALSE))
if(length(parentAttrs)>0) parentAttrs <- parentAttrs[names(parentAttrs) != "xsi:type"]
if(length(parentAttrs)==0) parentAttrs <- NULL
children <- xmlChildren(child, encoding = private$encoding, addFinalizer = FALSE)
if(length(children)>0){
if(length(children)==1){
childroot <- children[[1]]
if(!is(childroot, "XMLInternalTextNode")){
child <- childroot
fieldClass <- ISOAbstractObject$getISOClassByNode(childroot)
}
}else{
#more than one child, consider it as sequence
fieldClass <- ISOElementSequence
}
}else{
#if xlink:href attr available attempt to
#href <- xmlGetAttr(child, "xlink:href")
#if(!is.null(href)){
# self$INFO(sprintf("Fetching child element from xlink:href attribute '%s'", href))
# childXML <- try(XML::xmlParse(href))
# if(!is(childXML,"try-error")){
# child <- XML::xmlRoot(childXML)
# fieldClass <- ISOAbstractObject$getISOClassByNode(child)
# }
#}
}
if(!is.null(fieldClass)) wrap_fields <- TRUE
}
}
#coercing
fieldValue <- xmlValue(child, recursive = FALSE)
if(length(fieldValue)>0){
fieldValue <- private$toComplexTypes(fieldValue)
}
if(!is.null(fieldClass)){
if(regexpr("^ISOBase.+", fieldClass$classname)>0){
fieldValue <- switch(fieldClass$classname,
"ISOBaseBoolean" = as.logical(fieldValue),
"ISOBaseInteger" = as.integer(fieldValue),
"ISOBaseReal" = as.numeric(fieldValue),
"ISOBaseDecimal" = {
fieldValue <- as.numeric(fieldValue)
class(fieldValue) <- "decimal"
fieldValue
},
fieldValue
)
if(length(fieldValue)==0) fieldValue = NA
}else{
fieldValue <- fieldClass$new(xml = child)
fieldValue$parentAttrs <- parentAttrs
attrs <- as.list(xmlAttrs(child, TRUE, FALSE))
if(length(attrs)>0) attrs <- attrs[attrs != "gmd:PT_FreeText_PropertyType"]
fieldValue$attrs <- attrs
}
if(is(self[[fieldName]], "list")){
self[[fieldName]] <- c(self[[fieldName]], fieldValue)
}else{
if(is(self, "ISOElementSequence")){
if(!wrap_fields){
#means no wrapping of ElementSequence fields
self[["_internal_"]] <- c(self[["_internal_"]], fieldValue)
}else{
self[[fieldName]] <- fieldValue
}
}else{
self[[fieldName]] <- fieldValue
}
}
}else{
if(is.null(nsPrefix)) nsPrefix <- ""
if(startsWith(nsPrefix,"gml") |inherits(self, "GMLAbstractObject")){
if(is(self[[fieldName]], "matrix") &
(inherits(self,"GMLAbstractRing")|
inherits(self,"GMLAbstractGeometricPrimitive")|
inherits(self,"GMLEnvelope")|
inherits(self,"GMLGridEnvelope")|
inherits(self,"GMLGeneralGridAxis"))){
value <- xmlValue(child)
if(value=="") value <- NA
if(!is.na(value)){
value_split <- unlist(strsplit(value," "))
coercable <- !suppressWarnings(is.na(as.numeric(value_split)))
values <- lapply(1:length(value_split), function(i){
out <- value_split[i]
if(coercable[i]) out <- as.numeric(out)
return(out)
})
if(all(!is.na(values)) & length(values)>1){
values <- lapply(values, function(x){if(is.character(x)){x <- gsub("\"","",x)};x})
if(is(self,"GMLEnvelope")){
m.values <- t(matrix(values))
}else{
dimension <- xmlGetAttr(xml, "srsDimension")
if(!is.null(dimension)) dimension <- as.integer(dimension)
if(is.null(dimension)){
dimension <- 1
if(inherits(self,"GMLAbstractGeometricPrimitive")){
if(is(self, "GMLPoint")){
dimension <- length(values)
}else{
self$WARN("No 'srsDimension' on geometry object. Impossible to decode coordinates!")
}
}
}
m.values <- matrix(values, length(values)/dimension, dimension, byrow = TRUE)
}
if(is(self[[fieldName]], "list")){
self[[fieldName]] <- c(self[[fieldName]], m.values)
}else{
self[[fieldName]] <- m.values
}
}
}else{
#xmlNamespacePrefix <- "GML"
xmlNamespacePrefix <- self$getClass()$private_fields$xmlNamespacePrefix
if(startsWith(nsPrefix,"gml")) xmlNamespacePrefix <- toupper(nsPrefix)
if(is.null(xmlNamespacePrefix)) xmlNamespacePrefix <- "GML"
gmlElem <- GMLElement$new(element = fieldName, xmlNamespacePrefix = xmlNamespacePrefix)
gmlElem$decode(xml = childElement)
if(is(self[[fieldName]], "list")){
self[[fieldName]] <- c(self[[fieldName]], gmlElem)
}else{
self[[fieldName]] <- gmlElem
}
}
}else{
#xmlNamespacePrefix <- "GML"
#if(startsWith(nsPrefix,"gml")) xmlNamespacePrefix <- toupper(nsPrefix)
xmlNamespacePrefix <- self$getClass()$private_fields$xmlNamespacePrefix
if(startsWith(nsPrefix,"gml")) xmlNamespacePrefix <- toupper(nsPrefix)
if(is.null(xmlNamespacePrefix)) xmlNamespacePrefix <- "GML"
gmlElem <- GMLElement$new(element = fieldName, xmlNamespacePrefix = xmlNamespacePrefix)
gmlElem$decode(xml = childElement)
if(is(self[[fieldName]], "list")){
self[[fieldName]] <- c(self[[fieldName]], gmlElem)
}else{
self[[fieldName]] <- gmlElem
}
}
}else if(inherits(self, "SWEAbstractObject")){
#TODO see how to improve encoding/decoding for GML/SWE objects
xmlNamespacePrefix <- self$getClass()$private_fields$xmlNamespacePrefix
if(startsWith(nsPrefix,"swe")) xmlNamespacePrefix <- toupper(nsPrefix)
if(is.null(xmlNamespacePrefix)) xmlNamespacePrefix <- "SWE"
sweElem <- SWEElement$new(element = fieldName, xmlNamespacePrefix = xmlNamespacePrefix)
sweElem$decode(xml = childElement)
if(is(self[[fieldName]], "list")){
self[[fieldName]] <- c(self[[fieldName]], sweElem)
}else{
self[[fieldName]] <- sweElem
}
}else{
value <- xmlValue(child)
isList <- is.list(self$getClass()$public_fields[[fieldName]])
if(value==""){
value <- ifelse(isList, list(), NA)
attrs <- xmlAttrs(child)
if(!is.null(attrs)){
attrNs <- attr(attrs,"namespaces")
if(!is.null(attrNs)){
attr(attrs,"namespaces") <- NULL
names(attrs) <- paste(attrNs, names(attrs), sep=":")
#control mal-formed attributes (starting with :)
names(attrs) <- lapply(names(attrs), function(x){
out <- x
if(startsWith(x,":")) out <- substr(x, 2, nchar(x))
return(out)
})
}
if(length(attrs)==1 && names(attrs)== "gco:nilReason"){
#if only gco:nilReason attribute we resolve value as NA
value <- NA
}else{
#if others attributes we keep them
value <- ISOAttributes$new(attrs[names(attrs)!="gco:nilReason"])
}
}
}
if(fieldName == "text") fieldName <- "value"
self[[fieldName]] <- if(is.list(self[[fieldName]])) c(self[[fieldName]], value) else value
}
}
}
#inherit attributes if any
xmlattrs <- NULL
if(!self$isDocument()) xmlattrs <- xmlAttrs(xml, TRUE, FALSE)
if(is(self, "ISOFeatureCatalogue")){
xmlattrs <- xmlAttrs(xml, TRUE, FALSE)
if("uuid" %in% names(xmlattrs)){
xmlattrs <- xmlattrs[names(xmlattrs)=="uuid"]
}
}
attrs <- as.list(xmlattrs)
if(length(attrs)>0) attrs <- attrs[attrs != "gmd:PT_FreeText_PropertyType"]
self$attrs <- attrs
if("gco:nilReason" %in% names(xmlattrs)) self$isNull <- TRUE
},
#'@description Encodes object as XML.
#'
#' By default, namespace definition will be added to XML root (\code{addNS = TRUE}), and validation
#' of object will be performed (\code{validate = TRUE}) prior to its XML encoding. The argument
#' \code{strict} allows to stop the encoding in case object is not valid, with a default value set to \code{FALSE}.
#'
#' The argument \code{setSerialID} is used by \pkg{geometa} to generate automatically serial IDs associated to
#' XML elements, in particular for GML, default value is \code{TRUE} (recommended value).
#'
#' The argument \code{resetSerialID} is used by \pkg{geometa} for reseting mandatory IDs
#' associated to XML elements, such as GML objects, default value is \code{TRUE}
#' (recommended value).
#'
#' Setting \code{inspire} to TRUE (default FALSE), the metadata will be checked with
#' the INSPIRE metadata validator (online web-service provided by INSPIRE). To check
#' metadata with the INSPIRE metadata validator, setting an INSPIRE metadata validator
#' is now required, and should be specified with the \code{inspireValidator}. See
#' \code{\link{INSPIREMetadataValidator}} for more details
#'
#'@param addNS add namespace? Default is \code{TRUE}
#'@param validate validate XML output against schemas?
#'@param strict strict validation? Default is \code{FALSE}.
#'@param inspire perform INSPIRE validation? Default is \code{FALSE}
#'@param inspireValidator an object of class \link{INSPIREMetadataValidator} to perform INSPIRE metadata validation
#'@param resetSerialID reset Serial ID? Default is \code{TRUE}
#'@param setSerialID set serial ID? Default is \code{TRUE}
#'@param encoding encoding. Default is \code{UTF-8}
encode = function(addNS = TRUE, validate = TRUE, strict = FALSE, inspire = FALSE, inspireValidator = NULL,
resetSerialID = TRUE, setSerialID = TRUE,
encoding = "UTF-8"){
#management of GML ids
if(resetSerialID) .geometa.gml$serialId <- 1L
if(setSerialID){
if(inherits(self, "GMLAbstractGML")){
if(is.null(self$attrs[["gml:id"]])){
serialId <- paste0("ID",.geometa.gml$serialId)
self$setId(serialId,TRUE)
.geometa.gml$serialId <- .geometa.gml$serialId+1
}
}
}
#list of fields to encode as XML
fields <- rev(names(self))
#root XML
rootXML <- NULL
rootXMLAttrs <- list()
if("attrs" %in% fields){
rootXMLAttrs <- self[["attrs"]]
rootXMLAttrs <- rootXMLAttrs[!is.na(rootXMLAttrs)]
}
freeTextAttr <- list("xsi:type" = "gmd:PT_FreeText_PropertyType")
#fields
fields <- fields[!sapply(fields, function(x){
(class(self[[x]])[1] %in% c("environment", "function")) ||
(x %in% private$system_fields)
})]
if(self$isDocument()){
rootNamespaces <- sapply(getISOMetadataNamespaces(), function(x){x$getDefinition()})
rootXML <- xmlOutputDOM(
tag = self$element,
nameSpace = self$namespace$id,
nsURI = rootNamespaces
)
}else{
wrapperAttrs <- self$attrs
if(self$isNull){
wrapperAttrs <- self$attrs
if(length(wrapperAttrs)>1) wrapperAttrs <- wrapperAttrs[names(wrapperAttrs)!="gco:nilReason"]
}
if(addNS){
nsdefs <- self$getNamespaceDefinition(recursive = TRUE)
if(!("xsi" %in% names(nsdefs))) nsdefs <- c(nsdefs, ISOMetadataNamespace$XSI$getDefinition())
if(!("xlink" %in% names(nsdefs))) nsdefs <- c(nsdefs, ISOMetadataNamespace$XLINK$getDefinition())
nsdefs <- nsdefs[order(names(nsdefs))]
rootXML <- xmlOutputDOM(
tag = self$element,
nameSpace = self$namespace$id,
nsURI = nsdefs,
attrs = wrapperAttrs
)
}else{
rootXML <- xmlOutputDOM(
tag = self$element,
nameSpace = self$namespace$id,
attrs = wrapperAttrs
)
}
}
if(!self$isNull) for(field in fields){
fieldObj <- self[[field]]
#default values management
if(is.null(fieldObj) || (is.list(fieldObj) & length(fieldObj)==0)){
if(field %in% names(self$defaults)){
fieldObj <- self$defaults[[field]]
}
}
#user values management
ns <- self$namespace$getDefinition()
if(field != "value"){
klass <- self$isFieldInheritedFrom(field)
if(!is.null(klass)){
ns <- ISOMetadataNamespace[[klass$private_fields$xmlNamespacePrefix]]$getDefinition()
}
}
namespaceId <- names(ns)
if(!is.null(fieldObj)){
if(is(fieldObj, "ISOAbstractObject")){
fieldObjXml <- fieldObj$encode(addNS = FALSE, validate = FALSE,
resetSerialID = FALSE, setSerialID = setSerialID)
if(is(fieldObj, "ISOElementSequence")){
fieldObjXml.children <- xmlChildren(fieldObjXml, addFinalizer = FALSE)
hasLocales <- FALSE
if(!is.null(fieldObj[["_internal_"]])){
if(any(sapply(fieldObj[["_internal_"]],function(x){class(x)[1]})=="ISOFreeText")){
hasLocales <- TRUE
}
}
if(self$wrap){
wrapperAttrs <- self$parentAttrs
if(hasLocales) wrapperAttrs <- c(wrapperAttrs, freeTextAttr)
wrapperNode <- xmlOutputDOM(
tag = field,
nameSpace = namespaceId,
attrs = wrapperAttrs
)
for(child in fieldObjXml.children){
wrapperNode$addNode(child)
}
rootXML$addNode(wrapperNode$value())
}else{
if(hasLocales && !("xsi:type" %in% names(rootXMLAttrs))) rootXMLAttrs <- c(rootXMLAttrs, freeTextAttr)
for(child in fieldObjXml.children){
rootXML$addNode(child)
}
}
#fieldObjNames <- names(fieldObj)
#fieldObjNames <- fieldObjNames[sapply(fieldObjNames, function(name){
# return(which(fieldObjNames == name) < which(fieldObjNames == ".__enclos_env__"))
#})]
}else{
if(fieldObj$wrap){
wrapperAttrs <- fieldObj$parentAttrs
if(fieldObj$isNull){
wrapperAttrs <- fieldObj$attrs
if(length(wrapperAttrs)>1) wrapperAttrs <- wrapperAttrs[names(wrapperAttrs)!="gco:nilReason"]
}
wrapperNode <- xmlOutputDOM(
tag = field,
nameSpace = namespaceId,
attrs = wrapperAttrs
)
if(!fieldObj$isNull) wrapperNode$addNode(fieldObjXml)
rootXML$addNode(wrapperNode$value())
}else{
rootXML$addNode(fieldObjXml)
}
}
}else if(is(fieldObj, "list")){
for(item in fieldObj){
nodeValue <- NULL
if(length(item)==0) item <- NA
if(is(item, "ISOAttributes")){
emptyNodeAttrs <- item$attrs
emptyNode <- xmlOutputDOM(tag = field,nameSpace = namespaceId, attrs = emptyNodeAttrs)
rootXML$addNode(emptyNode$value())
}else if(suppressWarnings(all(is.na(item)))){
emptyNodeAttrs <- c("gco:nilReason" = "missing")
emptyNode <- xmlOutputDOM(tag = field,nameSpace = namespaceId, attrs = emptyNodeAttrs)
rootXML$addNode(emptyNode$value())
}else if(is(item, "matrix")){
matrix_NA <- all(is.na(item))
if(matrix_NA){
emptyNode <- xmlOutputDOM(tag = field,nameSpace = namespaceId)
rootXML$addNode(emptyNode$value())
}else{
mts <- paste(apply(item, 1L, function(x){
x <- lapply(x, function(el){
if(!is.na(suppressWarnings(as.numeric(el)))){
el <- as.numeric(el)
}
return(el)
})
x <- lapply(x, function(el){
if(is.na(suppressWarnings(as.numeric(el))) & !all(sapply(x,class)=="character")){
el <- paste0("\"",el,"\"")
}
return(el)
})
return(paste(x, collapse = " "))
}), collapse = " ")
txtNode <- xmlTextNode(mts)
if(field == "value"){
rootXML$addNode(txtNode)
}else{
wrapperNode <- xmlOutputDOM(tag = field, nameSpace = namespaceId)
wrapperNode$addNode(txtNode)
rootXML$addNode(wrapperNode$value())
}
}
}else{
if(is(item, "ISOAbstractObject")){
nodeValue <- item
}else{
nodeValue <- self$wrapBaseElement(field, item)
}
nodeValueXml <- nodeValue$encode(addNS = FALSE, validate = FALSE,
resetSerialID = FALSE, setSerialID = setSerialID)
if(is(item, "ISOElementSequence")){
nodeValueXml.children <- xmlChildren(nodeValueXml, addFinalizer = FALSE)
hasLocales <- FALSE
if(!is.null(item[["_internal_"]])){
if(any(sapply(item[["_internal_"]],function(x){class(x)[1]})=="ISOFreeText")){
hasLocales <- TRUE
}
}
if(nodeValue$wrap){
wrapperAttrs <- nodeValue$parentAttrs
if(nodeValue$isNull){
wrapperAttrs <- nodeValue$attrs
if(length(wrapperAttrs)>1) wrapperAttrs <- wrapperAttrs[names(wrapperAttrs)!="gco:nilReason"]
}
wrapperAttrs <- c(wrapperAttrs,freeTextAttr)
wrapperNode <- xmlOutputDOM(tag = field,nameSpace = namespaceId, attrs = wrapperAttrs)
if(!nodeValue$isNull){
for(child in nodeValueXml.children){
wrapperNode$addNode(child)
}
}
rootXML$addNode(wrapperNode$value())
}else{
if(hasLocales && !("xsi:type" %in% names(rootXMLAttrs))) rootXMLAttrs <- c(rootXMLAttrs, freeTextAttr)
for(child in nodeValueXml.children){
rootXML$addNode(child)
}
}
}else{
if(nodeValue$wrap && field != "_internal_"){
wrapperAttrs <- nodeValue$parentAttrs
if(nodeValue$isNull){
wrapperAttrs <- nodeValue$attrs
if(length(wrapperAttrs)>1) wrapperAttrs <- wrapperAttrs[names(wrapperAttrs)!="gco:nilReason"]
}
wrapperNode <- xmlOutputDOM(
tag = field,
nameSpace = namespaceId,
attrs = wrapperAttrs
)
if(!nodeValue$isNull) wrapperNode$addNode(nodeValueXml)
rootXML$addNode(wrapperNode$value())
}else{
rootXML$addNode(nodeValueXml)
}
}
}
}
}else if(is(fieldObj, "matrix")){
matrix_NA <- all(is.na(fieldObj))
if(matrix_NA){
emptyNode <- xmlOutputDOM(tag = field,nameSpace = namespaceId)
rootXML$addNode(emptyNode$value())
}else{
mts <- paste(apply(fieldObj, 1L, function(x){
x <- lapply(x, function(el){
if(!is.na(suppressWarnings(as.numeric(el)))){
el <- as.numeric(el)
}
return(el)
})
x <- lapply(x, function(el){
if(is.na(suppressWarnings(as.numeric(el))) & !all(sapply(x,class)=="character")){
el <- paste0("\"",el,"\"")
}
return(el)
})
return(paste(x, collapse = " "))
}), collapse = " ")
txtNode <- xmlTextNode(mts)
if(field == "value"){
if(field == "value" && self$value_as_field){
wrapperNode <- xmlOutputDOM(
tag = field,
nameSpace = namespaceId
)
wrapperNode$addNode(txtNode)
rootXML$addNode(wrapperNode$value())
}else{
rootXML$addNode(txtNode)
}
}else{
wrapperNode <- xmlOutputDOM(tag = field, nameSpace = namespaceId)
wrapperNode$addNode(txtNode)
rootXML$addNode(wrapperNode$value())
}
}
}else{
if(length(fieldObj)==0) fieldObj <- NA
if(is(fieldObj, "ISOAttributes")){
emptyNodeAttrs <- fieldObj$attrs
emptyNode <- xmlOutputDOM(tag = field,nameSpace = namespaceId, attrs = emptyNodeAttrs)
rootXML$addNode(emptyNode$value())
}else if(is.na(fieldObj)){
emptyNodeAttrs <- c("gco:nilReason" = "missing")
emptyNode <- xmlOutputDOM(tag = field,nameSpace = namespaceId, attrs = emptyNodeAttrs)
rootXML$addNode(emptyNode$value())
}else{
if((field == "value"|| field == "_internal_")){
if(is.logical(fieldObj)) fieldObj <- tolower(as.character(is.logical(fieldObj)))
fieldObj <- private$fromComplexTypes(fieldObj)
if(field == "value" && self$value_as_field){
wrapperNode <- xmlOutputDOM(
tag = field,
nameSpace = namespaceId
)
wrapperNode$addNode(xmlTextNode(fieldObj))
rootXML$addNode(wrapperNode$value())
}else{
rootXML$addNode(xmlTextNode(fieldObj))
}
}else{
dataObj <- self$wrapBaseElement(field, fieldObj)
if(!is.null(dataObj)){
if(dataObj$wrap){
#general case of gco wrapper element
wrapperNode <- xmlOutputDOM(
tag = field,
nameSpace = namespaceId
)
wrapperNode$addNode(dataObj$encode(addNS = FALSE, validate = FALSE,
resetSerialID = FALSE, setSerialID = setSerialID))
rootXML$addNode(wrapperNode$value())
}else{
rootXML$addNode(dataObj$encode(addNS = FALSE, validate = FALSE,
resetSerialID = FALSE, setSerialID = setSerialID))
}
}
}
}
}
}
}
#toXML (required for validation)
out <- rootXML$value()
out <- private$xmlNodeToCharacter(out)
if(Encoding(out)!="UTF-8") out <- iconv(out, to = "UTF-8")
out <- xmlParse(out, encoding = Encoding(out), error = function (msg, ...) {})
out <- as(out, "XMLInternalNode") #to XMLInternalNode
if(length(rootXMLAttrs)>0){
suppressWarnings(xmlAttrs(out) <- rootXMLAttrs)
}
#validation vs. ISO 19139 XML schemas + eventually INSPIRE
compliant <- NA
if(validate){
compliant <- self$validate(xml = out, strict = strict, inspire = inspire, inspireValidator = inspireValidator)
}
if(self$isDocument()){
if(!inspire){
header_comments <- private$xmlComments(compliant)
}else{
if(is.list(compliant)){
header_comments <- private$xmlComments(compliant$ISO, compliant$INSPIRE)
}else{
header_comments <- private$xmlComments(compliant)
}
}
#process XML comments
for(comment in header_comments){