-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcsw_update.py
1450 lines (1247 loc) · 60.6 KB
/
csw_update.py
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
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Python standard libs
import logging
import os
import sys
import json
from datetime import datetime
import argparse
import time
import pdb
# non standard dependencies
from owslib import csw
from owslib.etree import etree
from owslib import util
from owslib.namespaces import Namespaces
import unicodecsv as csv
from dateutil import parser
# config options - see config.py.sample for how to structure
from config import CSW_URL, USER, PASSWORD, DEBUG
# logging stuff
if DEBUG:
log_level = logging.DEBUG
else:
log_level = logging.INFO
log = logging.getLogger('owslib')
log.setLevel(log_level)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(log_level)
log_formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(log_formatter)
log.addHandler(ch)
class UpdateCSW(object):
def __init__(self, url, username, password, input_csv_path):
self.INNER_DELIMITER = "###"
self.GEMET_ANCHOR_BASE_URI = "https://geonet.lib.umn.edu:80/geonetwork/srv/eng/xml.keyword.get?thesaurus=external.theme.gemet-en&id="
self.csw = csw.CatalogueServiceWeb(
url, username=username, password=password)
self.records = {}
if not os.path.isabs(input_csv_path):
input_csv_path = os.path.abspath(
os.path.relpath(input_csv_path, os.getcwd()))
self.csvfile = open(input_csv_path, "rU")
self.reader = csv.DictReader(self.csvfile)
self.fieldnames = self.reader.fieldnames
self.namespaces = self.get_namespaces()
# these are the column names that will trigger a change
self.field_handlers = {"iso19139": {
"NEW_title": self.NEW_title,
"NEW_publisher": self.NEW_publisher,
"NEW_link_download": self.NEW_link_download,
"NEW_link_service_wms": self.NEW_link_service_wms,
"NEW_link_service_esri": self.NEW_link_service_esri,
"NEW_link_information": self.NEW_link_information,
"NEW_distribution_format": self.NEW_distribution_format,
"NEW_contact_organization": self.NEW_contact_organization,
"NEW_contact_individual": self.NEW_contact_individual,
"NEW_topic_categories": self.NEW_topic_categories,
"NEW_abstract": self.NEW_abstract,
"NEW_keywords_theme": self.NEW_keywords_theme,
"NEW_keywords_theme_gemet_name": self.NEW_keywords_theme_gemet_name,
"NEW_keywords_place": self.NEW_keywords_place,
"NEW_keywords_place_geonames": self.NEW_keywords_place_geonames,
"NEW_date_publication": self.NEW_date_publication,
"NEW_date_revision": self.NEW_date_revision,
"NEW_temporal_end": self.NEW_temporal_end,
"NEW_temporal_start": self.NEW_temporal_start,
"NEW_temporal_instant": self.NEW_temporal_instant,
"DELETE_link": self.DELETE_link,
"DELETE_link_no_protocol": self.DELETE_link_no_protocol
},
# currently unused
"dublin-core": {
u"NEW_title": self.NEW_title,
u"NEW_abstract": self.NEW_abstract
}
}
self.XPATHS = {"iso19139": {
"citation": "gmd:identificationInfo/gmd:MD_DataIdentification/gmd:citation/gmd:CI_Citation",
"publisher": "gmd:identificationInfo/gmd:MD_DataIdentification/gmd:citation/gmd:CI_Citation/gmd:citedResponsibleParty/gmd:CI_ResponsibleParty[gmd:role/gmd:CI_RoleCode[@codeListValue='publisher']]/gmd:organisationName/gco:CharacterString",
"title": "gmd:identificationInfo/gmd:MD_DataIdentification/gmd:citation/gmd:CI_Citation/gmd:title/gco:CharacterString",
"distribution_format": "gmd:distributionInfo/gmd:MD_Distribution/gmd:distributionFormat/gmd:MD_Format/gmd:name/gco:CharacterString",
"date_creation": "gmd:identificationInfo/gmd:MD_DataIdentification/gmd:citation/gmd:CI_Citation/gmd:date/gmd:CI_Date/gmd:dateType/gmd:CI_DateTypeCode[@codeListValue='creation']",
"date_publication": "gmd:identificationInfo/gmd:MD_DataIdentification/gmd:citation/gmd:CI_Citation/gmd:date/gmd:CI_Date/gmd:dateType/gmd:CI_DateTypeCode[@codeListValue='publication']",
"date_revision": "gmd:identificationInfo/gmd:MD_DataIdentification/gmd:citation/gmd:CI_Citation/gmd:date/gmd:CI_Date/gmd:dateType/gmd:CI_DateTypeCode[@codeListValue='revision']",
"contact_organization": "gmd:contact/gmd:CI_ResponsibleParty/gmd:organisationName/gco:CharacterString",
"contact_individual": "gmd:contact/gmd:CI_ResponsibleParty/gmd:individualName/gco:CharacterString",
"timestamp": "gmd:dateStamp",
"md_distribution": "gmd:distributionInfo/gmd:MD_Distribution",
"transferOptions": "gmd:distributionInfo/gmd:MD_Distribution/gmd:transferOptions",
"digital_trans_options": "gmd:distributionInfo/gmd:MD_Distribution/gmd:transferOptions/gmd:MD_DigitalTransferOptions",
"online_resources": "//gmd:transferOptions/gmd:MD_DigitalTransferOptions/gmd:onLine/gmd:CI_OnlineResource",
"online_resource_links": "//gmd:transferOptions/gmd:MD_DigitalTransferOptions/gmd:onLine/gmd:CI_OnlineResource/gmd:linkage/gmd:URL",
"link_no_protocol": "//gmd:transferOptions/gmd:MD_DigitalTransferOptions/gmd:onLine/gmd:CI_OnlineResource[not(gmd:protocol)]",
"distribution_link": "gmd:distributionInfo/gmd:MD_Distribution/gmd:transferOptions[{index}]/gmd:MD_DigitalTransferOptions[1]/gmd:onLine[1]/gmd:CI_OnlineResource[1]/gmd:linkage[1]/gmd:URL[1]",
"distributor_distribution_link": "gmd:distributionInfo/gmd:MD_Distribution/gmd:distributor[{distributor_index}]/gmd:MD_Distributor/gmd:distributorTransferOptions[{index}]/gmd:MD_DigitalTransferOptions/gmd:onLine/gmd:CI_OnlineResource/gmd:linkage/gmd:URL",
"keywords_theme": "gmd:identificationInfo/gmd:MD_DataIdentification/gmd:descriptiveKeywords/gmd:MD_Keywords/gmd:type/gmd:MD_KeywordTypeCode[@codeListValue='theme']/../../gmd:keyword/gco:CharacterString",
"keywords_theme_base": "gmd:identificationInfo/gmd:MD_DataIdentification/gmd:descriptiveKeywords/gmd:MD_Keywords/gmd:type/gmd:MD_KeywordTypeCode[@codeListValue='theme']",
"keywords_theme_gemet": "gmd:identificationInfo/gmd:MD_DataIdentification/gmd:descriptiveKeywords/gmd:MD_Keywords/gmd:thesaurusName/gmd:CI_Citation/gmd:title/gco:CharacterString[text()='GEMET']",
"keywords_place": "gmd:identificationInfo/gmd:MD_DataIdentification/gmd:descriptiveKeywords/gmd:MD_Keywords/gmd:type/gmd:MD_KeywordTypeCode[@codeListValue='place']/../../gmd:keyword/gco:CharacterString",
"keywords_place_base": "gmd:identificationInfo/gmd:MD_DataIdentification/gmd:descriptiveKeywords/gmd:MD_Keywords/gmd:type/gmd:MD_KeywordTypeCode[@codeListValue='place']",
"keywords_place_geonames": "gmd:identificationInfo/gmd:MD_DataIdentification/gmd:descriptiveKeywords/gmd:MD_Keywords/gmd:thesaurusName/gmd:CI_Citation/gmd:title/gco:CharacterString[text()='GeoNames']",
"descriptive_keywords": "gmd:identificationInfo/gmd:MD_DataIdentification/gmd:descriptiveKeywords",
"md_data_identification": "gmd:identificationInfo/gmd:MD_DataIdentification",
"topic_categories": "gmd:identificationInfo/gmd:MD_DataIdentification/gmd:topicCategory/gmd:MD_TopicCategoryCode",
"abstract": "gmd:identificationInfo/gmd:MD_DataIdentification/gmd:abstract/gco:CharacterString",
"purpose": "gmd:identificationInfo/gmd:MD_DataIdentification/gmd:purpose/gco:CharacterString",
"extent": "gmd:identificationInfo/gmd:MD_DataIdentification/gmd:extent",
"temporalextent": "gmd:identificationInfo/gmd:MD_DataIdentification/gmd:extent/gmd:EX_Extent/gmd:temporalElement",
"temporalextent_start": "gmd:EX_TemporalExtent/gmd:extent/gml:TimePeriod/gml:beginPosition",
"temporalextent_end": "gmd:EX_TemporalExtent/gmd:extent/gml:TimePeriod/gml:endPosition",
"temporalextent_instant": "gmd:EX_TemporalExtent/gmd:extent/gml:TimeInstant/gml:timePosition",
"ci_date_type": "gmd:identificationInfo/gmd:MD_DataIdentification/gmd:citation/gmd:CI_Citation/gmd:date/gmd:CI_Date[gmd:dateType/gmd:CI_DateTypeCode/@codeListValue='{datetype}']/gmd:date"
},
"dublin-core": {
"title": "dc:title"
}
}
self.protocol_map = {
"download": ["WWW:DOWNLOAD-1.0-ftp--download",
"download",
"WWW:DOWNLOAD-1.0-http--download",
"WWW:DOWNLOAD"],
"information": ["WWW:LINK",
"WWW:LINK-1.0-http--link"],
"esri_service": ["ESRI:ArcGIS"],
"wms_service": ["OGC:WMS"],
"wfs_service": ["OGC:WFS"],
"wcs_service": ["OGC:WCS"]
}
self.topic_categories = [
'intelligenceMilitary', 'environment',
'geoscientificinformation', 'elevation', 'utilitiesCommunications',
'structure', 'oceans', 'planningCadastre', 'inlandWaters',
'boundaries', 'society', 'biota', 'health', 'location',
'climatologyMeteorologyAtmosphere', 'transportation', 'farming',
'imageryBaseMapsEarthCover', 'economy']
@staticmethod
def get_namespaces():
"""
Returns specified namespaces using owslib Namespaces function.
"""
n = Namespaces()
ns = n.get_namespaces(
["gco", "gmd", "gml", "gml32", "gmx", "gts", "srv", "xlink", "dc"])
return ns
@staticmethod
def _filter_link_updates_or_deletions(field):
"""
Filter function used to identify link updates or deletions from the CSV
"""
if field.startswith("NEW_link") or field.startswith("DELETE_link"):
return True
def _get_links_from_record(self, uuid):
"""
Sets self.record_online_resources to a list of all\
CI_OnlineResource elements
"""
self.record_online_resources = self.record_etree.findall(
self.XPATHS[self.schema]["online_resources"], self.namespaces)
def _simple_element_update(self, uuid, new_value, xpath=None, element=None):
"""
Updates single element of record. Nothing fancy.
Elements like abstract and title.
Positional arguments:
uuid -- the unique id of the record to be updated
new_value -- the new value supplied from the csv
Keyword arguments (need one and only one):
xpath -- must follow straight from the root element
element -- match a name in self.XPATHS for the current schema
"""
if xpath:
path = xpath
elif element:
path = self.XPATHS[self.schema][element]
else:
log.error("_simple_element_update: No xpath or element provided")
return
tree = self.record_etree
original_path = path
elem = []
while len(elem) == 0:
elem = tree.xpath(path, namespaces=self.namespaces)
if len(elem) == 0:
log.debug(
"Did not find \n {p} \n trying next level up.".format(
p=path
)
)
path = "/".join(path.split("/")[:-1])
if len(elem) > 0 and path == original_path:
log.debug("Found the path: \n {p}".format(p=path))
if elem[0].text != new_value:
elem[0].text = new_value
self.tree_changed = True
else:
log.info("Value for \n {p} \n already set to: {v}".format(
p=path.split("/")[-2], v=new_value))
elif len(elem) > 0 and path != original_path:
elements_to_create = [
e for e in original_path.split("/") if e not in path]
self._create_elements(elem[0], elements_to_create)
log.debug(
"Recursing to _simple_element_update now that the \
element should be there.")
self._simple_element_update(uuid, new_value, xpath=original_path)
def _create_elements(self, start_element, list_of_element_names):
tree = self.record_etree
base_element = start_element
for elem_name in list_of_element_names:
elem_name_split = elem_name.split(":")
ns = "{" + self.namespaces[elem_name_split[0]] + "}"
base_element = etree.SubElement(
base_element,
"{ns}".format(ns=ns) + elem_name_split[1],
nsmap=self.namespaces
)
log.debug("Created {n}".format(n=elem_name))
self.tree_changed = True
def _check_for_links_to_update(self, link_type):
"""
Return a list of links that match a given type.
Positional argument:
link_type -- The type of link to look for. download, information,
esri_service, and wms_service are current values for link_type)
"""
self.protocols_list = self.protocol_map[link_type]
links_to_update = filter(
lambda resource,
ns=self.namespaces,
protocols=self.protocols_list: resource.findtext(
"gmd:protocol/gco:CharacterString",
namespaces=ns) in self.protocols_list,
self.record_online_resources
)
return links_to_update
def _add_protocol_to_resource(self, resource, link_type):
"""
Creates a protocol element and its text for a given online resource.
Positional arguments:
resource -- A CI_Online_Resource currently lacking a protocol.
link_type -- The type of link, which determines the protocol applied.
"""
protocol_element = etree.SubElement(
resource,
"{ns}protocol".format(
ns="{" + self.namespaces["gmd"] + "}"),
nsmap=self.namespaces
)
char_string = etree.SubElement(
protocol_element,
"{ns}CharacterString".format(
ns="{" + self.namespaces["gco"] + "}"),
nsmap=self.namespaces
)
char_string.text = self.protocol_map[link_type][0]
log.debug("Added protocol: {prot}".format(prot=char_string.text))
# log.debug(etree.tostring(self.record_etree))
return resource
def _update_links_no_protocol(self, new_link, link_type, resources_no_protocol):
"""
Matches inputted link to existing resources without
protocols and if successful, adds protocol.
Positional arguments:
new_link -- The link to search for
link_type -- The type of link, which us be used to create the protocol
resources_no_protocol -- A list of OnlineResource Elements lacking protocol SubElements
"""
for resource in resources_no_protocol:
if resource.find(
"gmd:linkage/gmd:URL",
namespaces=self.namespaces).text == new_link:
log.debug("updating resource with no protocol")
self._add_protocol_to_resource(resource, link_type)
# log.debug(etree.tostring(self.record_etree))
self.tree_changed = True
def _create_new_link(self, new_link, link_type):
"""
Create a new onLine element.
Assumes that gmd:MD_DigitalTransferOptions exists.
Positional arguments:
new_link -- The link to search for
link_type -- The type of link, which us be used to create the protocol
"""
transferOptions = self.record_etree.xpath(
self.XPATHS[self.schema]["transferOptions"],
namespaces=self.namespaces
)
new_link_layer_name = None
new_link_split = new_link.split(self.INNER_DELIMITER)
new_link = new_link_split[0]
if len(new_link_split) > 1:
new_link_layer_name = new_link_split[1]
if len(transferOptions) > 0:
digital_trans_options = self.record_etree.xpath(
self.XPATHS[self.schema]["digital_trans_options"],
namespaces=self.namespaces
)
if len(digital_trans_options) > 0:
# create the elements
online_element = etree.SubElement(
digital_trans_options[0],
"{ns}onLine".format(
ns="{" + self.namespaces["gmd"] + "}"),
nsmap=self.namespaces)
ci_onlineresource = etree.SubElement(
online_element,
"{ns}CI_OnlineResource".format(
ns="{" + self.namespaces["gmd"] + "}"),
nsmap=self.namespaces)
linkage = etree.SubElement(
ci_onlineresource,
"{ns}linkage".format(
ns="{" + self.namespaces["gmd"] + "}"),
nsmap=self.namespaces)
url = etree.SubElement(
linkage,
"{ns}URL".format(
ns="{" + self.namespaces["gmd"] + "}"),
nsmap=self.namespaces)
protocol = etree.SubElement(
ci_onlineresource,
"{ns}protocol".format(
ns="{" + self.namespaces["gmd"] + "}"),
nsmap=self.namespaces)
protocol_string = etree.SubElement(
protocol,
"{ns}CharacterString".format(
ns="{" + self.namespaces["gco"] + "}"),
nsmap=self.namespaces)
name = etree.SubElement(
ci_onlineresource,
"{ns}name".format(
ns="{" + self.namespaces["gmd"] + "}"),
nsmap=self.namespaces)
name_string = etree.SubElement(
ci_onlineresource,
"{ns}CharacterString".format(
ns="{" + self.namespaces["gco"] + "}"),
nsmap=self.namespaces)
# add the text
url.text = new_link
protocol_string.text = self.protocols_list[0]
if new_link_layer_name:
name_string.text = new_link_layer_name
self.tree_changed = True
log.debug("created new link: {link}".format(link=new_link))
# log.debug(etree.tostring(self.record_etree))
# log.debug(self.csw.response)
else:
md_distribution = self.record_etree.xpath(self.XPATHS[self.schema]["md_distribution"],
namespaces=self.namespaces)
if len(md_distribution) > 0:
transfer_options = self._create_transferOptions(
md_distribution[0])
self._create_md_digital_transfer_options(transfer_options)
# recurse and try to make link again now that the parents are
# in place
log.debug("trying to create link again")
self._create_new_link(new_link, link_type)
def _create_transferOptions(self, md_distribution):
return etree.SubElement(md_distribution,
"{ns}transferOptions".format(
ns="{" + self.namespaces["gmd"] + "}"),
nsmap=self.namespaces)
def _create_md_digital_transfer_options(self, transfer_options):
return etree.SubElement(transfer_options,
"{ns}MD_DigitalTransferOptions".format(
ns="{" + self.namespaces["gmd"] + "}"),
nsmap=self.namespaces)
def _current_link_url_elements(self):
return self.record_etree.xpath(
self.XPATHS[self.schema]["online_resource_links"],
namespaces=self.namespaces)
def _current_link_urls(self):
"""
Return a list of all URLs currently in the record.
"""
links = self._current_link_url_elements()
log.debug("Current link urls: " +
" | ".join([link.text for link in links]))
return [link.text for link in links]
def _get_resources_no_protocol(self):
return self.record_etree.xpath(
self.XPATHS[self.schema]["link_no_protocol"],
namespaces=self.namespaces)
def _update_links(self, uuid, new_link, link_type):
"""
Base function for updating links
"""
tree = self.record_etree
self._get_links_from_record(uuid)
record_links = self._current_link_urls()
new_link_layer_name = None
new_link_split = new_link.split(self.INNER_DELIMITER)
new_link = new_link_split[0]
if len(new_link_split) > 1:
new_link_layer_name = new_link_split[1]
#import pdb; pdb.set_trace()
links_to_update = self._check_for_links_to_update(link_type)
resources_no_protocol = self._get_resources_no_protocol()
if len(links_to_update) == 0 and resources_no_protocol is not None:
self._update_links_no_protocol(new_link,
link_type,
resources_no_protocol)
# log.debug(etree.tostring(self.record_etree))
for i in links_to_update:
elem = i.find("gmd:linkage/gmd:URL", namespaces=self.namespaces)
layer_name_elem = i.find(
"gmd:name/gco:CharacterString", namespaces=self.namespaces)
current_val = elem.text
current_protocol = i.find(
"gmd:protocol/gco:CharacterString", namespaces=self.namespaces)
log.debug("Current protocol: {p}".format(p=current_protocol.text))
log.debug("Current text: {t}".format(t=current_val))
if (current_protocol.text in self.protocols_list and
current_protocol.text != "WWW:DOWNLOAD"):
if "wms" in current_protocol.text.lower() and new_link_layer_name is not None and layer_name_elem is None:
name = etree.SubElement(i,
"{ns}name".format(
ns="{" + self.namespaces["gmd"] + "}"),
nsmap=self.namespaces)
name_text = etree.SubElement(name,
"{ns}CharacterString".format(
ns="{" + self.namespaces["gco"] + "}"),
nsmap=self.namespaces)
name_text.text = new_link_layer_name
self.tree_changed = True
if current_val and current_val == new_link:
# if so, we have nothing to do!
log.info(
"Value is already set to {link}. Skipping!".format(link=new_link))
continue
else:
log.debug("Updating link from {old} to {new}".format(old=current_val,
new=new_link))
elem.text = new_link
record_links.append(new_link)
record_links.remove(current_val)
self.tree_changed = True
xpath = self.record_etree.getpath(elem)
xpath = "/".join(xpath.split("/")[2:])
else:
log.debug("Updating protocol from {old} to {new}".format(old=current_protocol.text,
new=self.protocols_list[0]))
value = self.protocols_list[0]
current_protocol = value
self.tree_changed = True
xpath = self.record_etree.getpath(current_protocol)
xpath = "/".join(xpath.split("/")[2:])
# if the new url is nowhere to be found, create a new resource
if new_link not in record_links:
log.debug("Current links: " + ", ".join(self._current_link_urls()))
log.debug("Creating a new link")
self._create_new_link(new_link, link_type)
log.debug("Updated links: " + ", ".join(self._current_link_urls()))
def _make_new_multiple_element(self, element_name, value):
# TODO abstract beyond keywords using element_name
element = etree.Element("{ns}keyword".format(ns="{" + self.namespaces["gmd"] + "}"),
nsmap=self.namespaces)
child_element = etree.SubElement(element,
"{ns}CharacterString".format(ns="{" + self.namespaces["gco"] + "}"))
child_element.text = value
return element
def _multiple_element_update(self, uuid, new_vals_string, multiple_element_name):
"""
Keyword specific at the moment
"""
log.debug("NEW VALUE INPUT: " + new_vals_string)
new_vals_list = new_vals_string.split(self.INNER_DELIMITER)
if len(new_vals_list) == 1 and new_vals_list[0] == "":
return
tree = self.record_etree
tree_changed = False
base_desc_kw = tree.findall(self.XPATHS[self.schema][multiple_element_name + "_base"],
namespaces=self.namespaces)
if len(base_desc_kw) == 0:
# "descriptive_keywords" :"gmd:identificationInfo/gmd:MD_DataIdentification/gmd:descriptiveKeywords",
# "md_data_identification" :"gmd:identificationInfo/gmd:MD_DataIdentification",
new_desc_kw = self._parse_snippet(multiple_element_name + ".xml")
existing_desc_kw = tree.findall(self.XPATHS[self.schema]["descriptive_keywords"],
namespaces=self.namespaces)
if len(existing_desc_kw) > 0:
existing_desc_kw[-1].addnext(new_desc_kw)
self.tree_changed = True
else:
md_data_identification = tree.find(self.XPATHS[self.schema]["md_data_identification"],
namespaces=self.namespaces)
if md_data_identification is not None:
md_data_identification.append(new_desc_kw)
self.tree_changed = True
log.debug(
"Created descriptiveKeywords, now recursing to add keywords.")
self._multiple_element_update(
uuid, new_vals_string, multiple_element_name)
xpath = self.XPATHS[self.schema][multiple_element_name]
existing_vals = tree.findall(xpath, namespaces=self.namespaces)
if len(existing_vals) > 0:
md_keywords = existing_vals[0].getparent().getparent()
existing_vals_list = [i.text for i in existing_vals]
log.debug("EXISTING VALUES: " + "| ".join(existing_vals_list))
add_values = list(set(new_vals_list) - set(existing_vals_list))
delete_values = list(set(existing_vals_list) - set(new_vals_list))
log.debug("VALUES TO ADD: " + "| ".join(add_values))
log.debug("VALUES TO DELETE: " + "| ".join(delete_values))
else:
delete_values = []
add_values = new_vals_list
md_keywords = base_desc_kw[0].getparent().getparent()
log.debug("VALUES TO ADD: " + ", ".join(add_values))
for delete_value in delete_values:
# TODO abstract out keyword specifics
del_ele = tree.xpath(tree.getpath(
md_keywords) + "/gmd:keyword/gco:CharacterString[text()='{val}']".format(val=delete_value), namespaces=self.namespaces)
if len(del_ele) == 1:
log.debug("Deleted: {v}".format(v=delete_value))
p = del_ele[0].getparent()
p.remove(del_ele[0])
pp = p.getparent()
pp.remove(p)
tree_changed = True
for value in add_values:
# TODO handle specific things like this? maybe another dict of
# elements that have a controlled vocab?
# if value not in self.topic_categories:
# log.warn("Invalid topic category not added: " + value)
# continue
new_element = self._make_new_multiple_element(
multiple_element_name, value)
md_keywords.append(new_element)
tree_changed = True
if tree_changed:
self.tree_changed = True
def _make_new_topic_element(self, cat_text):
p = etree.Element("{gmd}topicCategory".format(
gmd="{" + self.namespaces["gmd"] + "}"), nsmap=self.namespaces)
c = etree.SubElement(p, "{gmd}MD_TopicCategoryCode".format(
gmd="{" + self.namespaces["gmd"] + "}"))
c.text = cat_text
return p
def NEW_abstract(self, uuid, new_abstract):
"""
Updates abstract of record
"""
if new_abstract != "" and new_abstract != "SKIP":
update = self._simple_element_update(
uuid, new_abstract, element="abstract")
log.info("updated abstract")
def NEW_publisher(self, uuid, new_publisher):
"""
Updates publisher of record
"""
if new_publisher != "" and new_publisher != "SKIP":
update = self._simple_element_update(
uuid, new_publisher, element="publisher")
log.info("updated publisher")
def NEW_distribution_format(self, uuid, new_format):
"""
Updates abstract of record
"""
if new_format != "" and new_format != "SKIP":
update = self._simple_element_update(
uuid, new_format, element="distribution_format")
log.info("updated distribution format")
def NEW_title(self, uuid, new_title):
"""
Updates title of record
"""
if new_title != "" and new_title != "SKIP":
update = self._simple_element_update(
uuid, new_title, element="title")
log.info("updated title")
def NEW_link_download(self, uuid, new_link):
if new_link != "" and new_link != "SKIP":
update = self._update_links(uuid, new_link, "download")
log.info("updated download link")
def NEW_link_service_esri(self, uuid, new_link):
if new_link != "" and new_link != "SKIP":
update = self._update_links(uuid, new_link, "esri_service")
log.info("updated esri_service link")
def NEW_link_service_wms(self, uuid, new_link):
if new_link != "" and new_link != "SKIP":
update = self._update_links(uuid, new_link, "wms_service")
log.info("updated wms_service link")
def NEW_link_information(self, uuid, new_link):
if new_link != "" and new_link != "SKIP":
update = self._update_links(uuid, new_link, "information")
log.info("updated info link")
def _delete_link_elementset(self, link):
onLine = link.getparent().getparent().getparent()
p = onLine.getparent()
p.remove(onLine)
self.tree_changed = True
def DELETE_link_no_protocol(self, uuid, link_to_delete):
if link_to_delete != "":
links = self._get_resources_no_protocol()
for link in links:
if link.findtext("gmd:linkage/gmd:URL", namespaces=self.namespaces) == link_to_delete:
self._delete_link_elementset(link)
log.info("deleted link with no protocol: {link}".format(
link=link_to_delete))
def DELETE_link(self, uuid, link_to_delete):
if link_to_delete != "":
links = self._current_link_url_elements()
for link in links:
if link.text == link_to_delete:
self._delete_link_elementset(link)
log.info("deleted link: {link}".format(
link=link_to_delete))
def NEW_topic_categories(self, uuid, new_topic_categories):
"""
This is heinous. I'm sorry.
"""
cat_list = new_topic_categories.split(self.INNER_DELIMITER)
log.debug("NEW TOPIC INPUT: " + new_topic_categories)
if len(cat_list) == 1 and cat_list[0] == "":
return
tree = self.record_etree
tree_changed = False
xpath = self.XPATHS[self.schema]["topic_categories"]
existing_cats = tree.findall(xpath, namespaces=self.namespaces)
existing_cats_text = [
i.text for i in existing_cats if i.text is not None]
log.debug("existing_cats_text: {e}".format(e=existing_cats_text))
new_cats = list(set(cat_list) - set(existing_cats_text))
delete_cats = list(set(existing_cats_text) - set(cat_list))
log.debug("NEW CATEGORIES: " + ", ".join(new_cats))
log.debug("CATEGORIES TO DELETE: " + ", ".join(delete_cats))
for cat_text in new_cats:
if cat_text not in self.topic_categories:
log.warn("Invalid topic category not added: " + cat_text)
continue
new_cat_element = self._make_new_topic_element(cat_text)
elem = None
if len(existing_cats) > 0:
elem = existing_cats[-1].getparent()
else:
md_di = tree.find(self.XPATHS[self.schema][
"md_data_identification"], namespaces=self.namespaces)
potential_siblings = [
"gmd:characterSet", "gmd:language",
"gmd:spatialResolution", "gmd:spatialResolutionType",
"gmd:aggregationInfo", "gmd:resourceConstraints",
"gmd:resourceSpecificUsage", "gmd:descriptiveKeywords",
"gmd:resourceFormat", "gmd:graphicOverview",
"gmd:resourceMaintenance", "gmd:pointOfContact",
"gmd:status", "gmd:credit", "gmd:purpose", "gmd:abstract"]
for i in potential_siblings:
log.debug("Looking for: {e}".format(e=i))
elem = md_di.find(i, namespaces=self.namespaces)
if elem is not None:
log.debug("Found: {e}".format(e=i))
break
elem.addnext(new_cat_element)
self.tree_changed = True
for delete_cat in delete_cats:
del_ele = tree.xpath("//gmd:MD_TopicCategoryCode[text()='{cat}']".format(
cat=delete_cat), namespaces=self.namespaces)
if len(del_ele) == 1:
p = del_ele[0].getparent()
p.remove(del_ele[0])
pp = p.getparent()
pp.remove(p)
self.tree_changed = True
def NEW_keywords_place(self, uuid, new_keywords):
update = self._multiple_element_update(
uuid, new_keywords, "keywords_place")
log.info("updated place keywords")
def NEW_keywords_theme(self, uuid, new_keywords):
update = self._multiple_element_update(
uuid, new_keywords, "keywords_theme")
log.info("updated theme keywords")
def _make_new_descriptive_keywords(self, tree):
if len(dk) > 0:
print("returning dk")
e = etree.Element(
"{ns}descriptiveKeywords".format(
ns="{" + self.namespaces["gmd"] + "}"),
nsmap=self.namespaces)
dk[-1].addnext()
return dk[-1].getnext()
else:
md_di = tree.find(self.XPATHS[self.schema][
"md_data_identification"], namespaces=self.namespaces)
if md_di is not None:
print("making new dk")
return etree.SubElement(md_di, "{ns}descriptiveKeywords".format(ns="{" + self.namespaces["gmd"] + "}"), nsmap=self.namespaces)
def _make_new_keyword_thesaurus_elements(self, thesaurus_name):
tree = self.record_etree
dk = tree.findall(
self.XPATHS[self.schema]["descriptive_keywords"],
namespaces=self.namespaces
)
thesaurus = self._parse_snippet(
"thesaurus_{n}.xml".format(n=thesaurus_name)
)
elem = None
if len(dk) > 0:
elem = dk[-1]
else:
md_di = tree.find(
self.XPATHS[self.schema]["md_data_identification"],
namespaces=self.namespaces
)
# ATM I can't think of a better way to make sure a fresh desc kw
# elem gets placed in the correct spot.
potential_siblings = [
"gmd:resourceFormat", "gmd:graphicOverview",
"gmd:resourceMaintenance", "gmd:pointOfContact", "gmd:status",
"gmd:credit", "gmd:purpose", "gmd:abstract"]
for i in potential_siblings:
log.debug("Looking for: {e}".format(e=i))
elem = md_di.find(i, namespaces=self.namespaces)
if elem is not None:
log.debug("Found: {e}".format(e=i))
break
elem.addnext(thesaurus)
return elem.getnext().find(
"gmd:MD_Keywords",
namespaces=self.namespaces
)
def _make_new_keyword_anchor(self, value, uri, parent_node):
element = etree.Element(
"{ns}keyword".format(ns="{" + self.namespaces["gmd"] + "}"),
nsmap=self.namespaces
)
child_element = etree.SubElement(
element,
"{ns}Anchor".format(ns="{" + self.namespaces["gmx"] + "}")
)
child_element.set(
"{" + self.namespaces["xlink"] + "}href",
self.GEMET_ANCHOR_BASE_URI + uri
)
child_element.text = value
parent_node.insert(0, element)
def _make_new_keyword_text(self, value, parent_node):
element = etree.Element(
"{ns}keyword".format(ns="{" + self.namespaces["gmd"] + "}"),
nsmap=self.namespaces
)
child_element = etree.SubElement(
element,
"{ns}CharacterString".format(ns="{" + self.namespaces["gco"] + "}"))
child_element.text = value
parent_node.insert(0, element)
def _keywords_thesaurus_update(
self,
uuid,
new_vals_string,
ids=None,
kw_type=None,
thesaurus=None):
"""
This is heinous. I'm sorry.
"""
log.info("KEYWORD TYPE: {t}".format(t=kw_type))
log.info("THESAURUS: {t}".format(t=thesaurus))
log.info("NEW VALUE INPUT: " + new_vals_string)
new_vals_list = new_vals_string.split(self.INNER_DELIMITER)
if ids:
new_ids_list = ids.split(self.INNER_DELIMITER)
if len(new_ids_list) == 1 and new_ids_list[0] == "":
return
if len(new_vals_list) == 1 and new_vals_list[0] == "":
return
tree = self.record_etree
thesaurus_xpath = self.XPATHS[self.schema][
"keywords_{kw_type}_{thesaurus}".format(
kw_type=kw_type,
thesaurus=thesaurus)]
existing_thesaurus = tree.xpath(
thesaurus_xpath,
namespaces=self.namespaces
)
if len(existing_thesaurus) == 0:
md_kw = self._make_new_keyword_thesaurus_elements(thesaurus)
if ids:
for index, value in enumerate(new_vals_list):
self._make_new_keyword_anchor(
value, new_ids_list[index], md_kw)
self.tree_changed = True
else:
for value in new_vals_list:
self._make_new_keyword_text(value, md_kw)
self.tree_changed = True
else:
existing_vals = existing_thesaurus[0].getparent().getparent().getparent(
).getparent().findall("gmd:keyword/*", namespaces=self.namespaces)
existing_vals_parent = existing_vals[0].getparent().getparent()
existing_vals_list = [i.text for i in existing_vals]
log.info("EXISTING VALUES: " + ", ".join(existing_vals_list))
add_values = list(set(new_vals_list) - set(existing_vals_list))
delete_values = list(set(existing_vals_list) - set(new_vals_list))
# TODO can't handle going between anchor/text, but i don't
# care!!!!! hahahahha
if ids:
# Are these even necessary? Not doing anything with em anyway
existing_ids = [i.get("{{ns}}href".format(
ns="{" + self.namespaces["xlink"] + "}")) for i in existing_vals]
add_ids = list(set(new_ids_list) - set(existing_ids))
delete_ids = list(set(existing_ids) - set(new_ids_list))
log.info("VALUES TO ADD: " + ", ".join(add_values))
log.info("VALUES TO DELETE: " + ", ".join(delete_values))
for delete_value in delete_values:
# TODO abstract out keyword specifics
del_ele = tree.xpath("//gmd:keyword/*[text()='{val}']".format(
val=delete_value), namespaces=self.namespaces)
if len(del_ele) == 1:
p = del_ele[0].getparent()
p.remove(del_ele[0])
pp = p.getparent()
pp.remove(p)
self.tree_changed = True
for value in add_values:
if ids:
self._make_new_keyword_anchor(
value,
add_ids[index],
existing_vals_parent
)
else:
self._make_new_keyword_text(value, existing_vals_parent)
self.tree_changed = True
def _keywords_theme_gemet_update(
self,
uuid,
new_vals_string,
new_ids_string):
"""
This is heinous. I'm sorry.
"""
log.info("NEW VALUE INPUT: " + new_vals_string)
new_vals_list = new_vals_string.split(self.INNER_DELIMITER)
new_ids_list = new_ids_string.split(self.INNER_DELIMITER)
if len(new_vals_list) == 1 and new_vals_list[0] == "" or \
len(new_ids_list) == 1 and new_ids_list[0] == "":
return
tree = self.record_etree
thesaurus_xpath = self.XPATHS[self.schema]["keywords_theme_gemet"]
existing_thesaurus = tree.xpath(
thesaurus_xpath,
namespaces=self.namespaces
)
if len(existing_thesaurus) == 0:
md_kw = self._make_new_keyword_thesaurus_elements()
self.tree_changed = True
for index, value in enumerate(new_vals_list):
self._make_new_keyword_anchor(
value,