-
-
Notifications
You must be signed in to change notification settings - Fork 152
/
csw3.py
2177 lines (1807 loc) · 102 KB
/
csw3.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
# -*- coding: utf-8 -*-
# =================================================================
#
# Authors: Tom Kralidis <tomkralidis@gmail.com>
#
# Copyright (c) 2016 Tom Kralidis
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# =================================================================
import os
import sys
import cgi
from time import time
from six.moves.urllib.parse import quote, unquote
from six import StringIO
from six.moves.configparser import SafeConfigParser
from pycsw.core.etree import etree
from pycsw.ogc.csw.cql import cql2fes1
from pycsw import oaipmh, opensearch, sru
from pycsw.plugins.profiles import profile as pprofile
import pycsw.plugins.outputschemas
from pycsw.core import config, log, metadata, util
from pycsw.core.formats.fmt_json import xml2dict
from pycsw.ogc.fes import fes2
import logging
LOGGER = logging.getLogger(__name__)
class Csw3(object):
''' CSW 3.x server '''
def __init__(self, server_csw):
''' Initialize CSW3 '''
self.parent = server_csw
self.version = '3.0.0'
def getcapabilities(self):
''' Handle GetCapabilities request '''
serviceidentification = True
serviceprovider = True
operationsmetadata = True
filtercaps = False
languages = False
# validate acceptformats
LOGGER.info('Validating ows20:AcceptFormats')
LOGGER.debug(self.parent.context.model['operations']['GetCapabilities']['parameters']['acceptFormats']['values'])
if 'acceptformats' in self.parent.kvp:
bfound = False
for fmt in self.parent.kvp['acceptformats'].split(','):
if fmt in self.parent.context.model['operations']['GetCapabilities']['parameters']['acceptFormats']['values']:
self.parent.mimetype = fmt
bfound = True
break
if not bfound:
return self.exceptionreport('InvalidParameterValue',
'acceptformats', 'Invalid acceptFormats parameter value: %s' %
self.parent.kvp['acceptformats'])
if 'sections' in self.parent.kvp and self.parent.kvp['sections'] != '':
serviceidentification = False
serviceprovider = False
operationsmetadata = False
for section in self.parent.kvp['sections'].split(','):
if section == 'ServiceIdentification':
serviceidentification = True
if section == 'ServiceProvider':
serviceprovider = True
if section == 'OperationsMetadata':
operationsmetadata = True
if section == 'All':
serviceidentification = True
serviceprovider = True
operationsmetadata = True
filtercaps = True
languages = True
else:
filtercaps = True
languages = True
# check extra parameters that may be def'd by profiles
if self.parent.profiles is not None:
for prof in self.parent.profiles['loaded'].keys():
result = \
self.parent.profiles['loaded'][prof].check_parameters(self.parent.kvp)
if result is not None:
return self.exceptionreport(result['code'],
result['locator'], result['text'])
# @updateSequence: get latest update to repository
try:
updatesequence = \
util.get_time_iso2unix(self.parent.repository.query_insert())
except:
updatesequence = None
node = etree.Element(util.nspath_eval('csw30:Capabilities',
self.parent.context.namespaces),
nsmap=self.parent.context.namespaces, version='3.0.0',
updateSequence=str(updatesequence))
if 'updatesequence' in self.parent.kvp:
if int(self.parent.kvp['updatesequence']) == updatesequence:
return node
elif int(self.parent.kvp['updatesequence']) > updatesequence:
return self.exceptionreport('InvalidUpdateSequence',
'updatesequence',
'outputsequence specified (%s) is higher than server\'s \
updatesequence (%s)' % (self.parent.kvp['updatesequence'],
updatesequence))
node.attrib[util.nspath_eval('xsi:schemaLocation',
self.parent.context.namespaces)] = '%s %s/cat/csw/3.0/cswGetCapabilities.xsd' % \
(self.parent.context.namespaces['csw30'],
self.parent.config.get('server', 'ogc_schemas_base'))
metadata_main = dict(self.parent.config.items('metadata:main'))
if serviceidentification:
LOGGER.info('Writing section ServiceIdentification')
serviceidentification = etree.SubElement(node, \
util.nspath_eval('ows20:ServiceIdentification',
self.parent.context.namespaces))
etree.SubElement(serviceidentification,
util.nspath_eval('ows20:Title', self.parent.context.namespaces)).text = \
metadata_main.get('identification_title', 'missing')
etree.SubElement(serviceidentification,
util.nspath_eval('ows20:Abstract', self.parent.context.namespaces)).text = \
metadata_main.get('identification_abstract', 'missing')
keywords = etree.SubElement(serviceidentification,
util.nspath_eval('ows20:Keywords', self.parent.context.namespaces))
for k in \
metadata_main.get('identification_keywords').split(','):
etree.SubElement(
keywords, util.nspath_eval('ows20:Keyword',
self.parent.context.namespaces)).text = k
etree.SubElement(keywords,
util.nspath_eval('ows20:Type', self.parent.context.namespaces),
codeSpace='ISOTC211/19115').text = \
metadata_main.get('identification_keywords_type', 'missing')
etree.SubElement(serviceidentification,
util.nspath_eval('ows20:ServiceType', self.parent.context.namespaces),
codeSpace='OGC').text = 'CSW'
for stv in self.parent.context.model['parameters']['version']['values']:
etree.SubElement(serviceidentification,
util.nspath_eval('ows20:ServiceTypeVersion',
self.parent.context.namespaces)).text = stv
if self.parent.profiles is not None:
for prof in self.parent.profiles['loaded'].keys():
prof_name = self.parent.profiles['loaded'][prof].name
prof_val = self.parent.profiles['loaded'][prof].namespaces[prof_name]
etree.SubElement(serviceidentification,
util.nspath_eval('ows20:Profile',
self.parent.context.namespaces)).text = prof_val
etree.SubElement(serviceidentification,
util.nspath_eval('ows20:Fees', self.parent.context.namespaces)).text = \
metadata_main.get('identification_fees', 'missing')
etree.SubElement(serviceidentification,
util.nspath_eval('ows20:AccessConstraints',
self.parent.context.namespaces)).text = \
metadata_main.get('identification_accessconstraints', 'missing')
if serviceprovider:
LOGGER.info('Writing section ServiceProvider')
serviceprovider = etree.SubElement(node,
util.nspath_eval('ows20:ServiceProvider', self.parent.context.namespaces))
etree.SubElement(serviceprovider,
util.nspath_eval('ows20:ProviderName', self.parent.context.namespaces)).text = \
metadata_main.get('provider_name', 'missing')
providersite = etree.SubElement(serviceprovider,
util.nspath_eval('ows20:ProviderSite', self.parent.context.namespaces))
providersite.attrib[util.nspath_eval('xlink:type',
self.parent.context.namespaces)] = 'simple'
providersite.attrib[util.nspath_eval('xlink:href',
self.parent.context.namespaces)] = \
metadata_main.get('provider_url', 'missing')
servicecontact = etree.SubElement(serviceprovider,
util.nspath_eval('ows20:ServiceContact', self.parent.context.namespaces))
etree.SubElement(servicecontact,
util.nspath_eval('ows20:IndividualName',
self.parent.context.namespaces)).text = \
metadata_main.get('contact_name', 'missing')
etree.SubElement(servicecontact,
util.nspath_eval('ows20:PositionName',
self.parent.context.namespaces)).text = \
metadata_main.get('contact_position', 'missing')
contactinfo = etree.SubElement(servicecontact,
util.nspath_eval('ows20:ContactInfo', self.parent.context.namespaces))
phone = etree.SubElement(contactinfo, util.nspath_eval('ows20:Phone',
self.parent.context.namespaces))
etree.SubElement(phone, util.nspath_eval('ows20:Voice',
self.parent.context.namespaces)).text = \
metadata_main.get('contact_phone', 'missing')
etree.SubElement(phone, util.nspath_eval('ows20:Facsimile',
self.parent.context.namespaces)).text = \
metadata_main.get('contact_fax', 'missing')
address = etree.SubElement(contactinfo,
util.nspath_eval('ows20:Address', self.parent.context.namespaces))
etree.SubElement(address,
util.nspath_eval('ows20:DeliveryPoint',
self.parent.context.namespaces)).text = \
metadata_main.get('contact_address', 'missing')
etree.SubElement(address, util.nspath_eval('ows20:City',
self.parent.context.namespaces)).text = \
metadata_main.get('contact_city', 'missing')
etree.SubElement(address,
util.nspath_eval('ows20:AdministrativeArea',
self.parent.context.namespaces)).text = \
metadata_main.get('contact_stateorprovince', 'missing')
etree.SubElement(address,
util.nspath_eval('ows20:PostalCode',
self.parent.context.namespaces)).text = \
metadata_main.get('contact_postalcode', 'missing')
etree.SubElement(address,
util.nspath_eval('ows20:Country', self.parent.context.namespaces)).text = \
metadata_main.get('contact_country', 'missing')
etree.SubElement(address,
util.nspath_eval('ows20:ElectronicMailAddress',
self.parent.context.namespaces)).text = \
metadata_main.get('contact_email', 'missing')
url = etree.SubElement(contactinfo,
util.nspath_eval('ows20:OnlineResource', self.parent.context.namespaces))
url.attrib[util.nspath_eval('xlink:type',
self.parent.context.namespaces)] = 'simple'
url.attrib[util.nspath_eval('xlink:href',
self.parent.context.namespaces)] = \
metadata_main.get('contact_url', 'missing')
etree.SubElement(contactinfo,
util.nspath_eval('ows20:HoursOfService',
self.parent.context.namespaces)).text = \
metadata_main.get('contact_hours', 'missing')
etree.SubElement(contactinfo,
util.nspath_eval('ows20:ContactInstructions',
self.parent.context.namespaces)).text = \
metadata_main.get('contact_instructions', 'missing')
etree.SubElement(servicecontact,
util.nspath_eval('ows20:Role', self.parent.context.namespaces),
codeSpace='ISOTC211/19115').text = \
metadata_main.get('contact_role', 'missing')
if operationsmetadata:
LOGGER.info('Writing section OperationsMetadata')
operationsmetadata = etree.SubElement(node,
util.nspath_eval('ows20:OperationsMetadata',
self.parent.context.namespaces))
for operation in self.parent.context.model['operations_order']:
oper = etree.SubElement(operationsmetadata,
util.nspath_eval('ows20:Operation', self.parent.context.namespaces),
name=operation)
dcp = etree.SubElement(oper, util.nspath_eval('ows20:DCP',
self.parent.context.namespaces))
http = etree.SubElement(dcp, util.nspath_eval('ows20:HTTP',
self.parent.context.namespaces))
if self.parent.context.model['operations'][operation]['methods']['get']:
get = etree.SubElement(http, util.nspath_eval('ows20:Get',
self.parent.context.namespaces))
get.attrib[util.nspath_eval('xlink:type',\
self.parent.context.namespaces)] = 'simple'
get.attrib[util.nspath_eval('xlink:href',\
self.parent.context.namespaces)] = self.parent.config.get('server', 'url')
if self.parent.context.model['operations'][operation]['methods']['post']:
post = etree.SubElement(http, util.nspath_eval('ows20:Post',
self.parent.context.namespaces))
post.attrib[util.nspath_eval('xlink:type',
self.parent.context.namespaces)] = 'simple'
post.attrib[util.nspath_eval('xlink:href',
self.parent.context.namespaces)] = \
self.parent.config.get('server', 'url')
for parameter in \
sorted(self.parent.context.model['operations'][operation]['parameters']):
param = etree.SubElement(oper,
util.nspath_eval('ows20:Parameter',
self.parent.context.namespaces), name=parameter)
param.append(self._write_allowed_values(self.parent.context.model['operations'][operation]['parameters'][parameter]['values']))
if operation == 'GetRecords': # advertise queryables, MaxRecordDefault
for qbl in sorted(self.parent.repository.queryables.keys()):
if qbl not in ['_all', 'SupportedDublinCoreQueryables']:
param = etree.SubElement(oper,
util.nspath_eval('ows20:Constraint',
self.parent.context.namespaces), name=qbl)
param.append(self._write_allowed_values(self.parent.repository.queryables[qbl]))
if self.parent.profiles is not None:
for con in sorted(self.parent.context.model[\
'operations']['GetRecords']['constraints'].keys()):
param = etree.SubElement(oper,
util.nspath_eval('ows20:Constraint',
self.parent.context.namespaces), name=con)
param.append(self._write_allowed_values(self.parent.context.model['operations']['GetRecords']['constraints'][con]['values']))
extra_constraints = {
'OpenSearchDescriptionDocument': ['%s?mode=opensearch&service=CSW&version=3.0.0&request=GetCapabilities' % self.parent.config.get('server', 'url')],
'MaxRecordDefault': self.parent.context.model['constraints']['MaxRecordDefault']['values'],
}
for key in sorted(extra_constraints.keys()):
param = etree.SubElement(oper,
util.nspath_eval('ows20:Constraint',
self.parent.context.namespaces), name=key)
param.append(self._write_allowed_values(extra_constraints[key]))
if 'FederatedCatalogues' in self.parent.context.model['constraints']:
param = etree.SubElement(oper,
util.nspath_eval('ows20:Constraint',
self.parent.context.namespaces), name='FederatedCatalogues')
param.append(self._write_allowed_values(self.parent.context.model['constraints']['FederatedCatalogues']['values']))
for parameter in sorted(self.parent.context.model['parameters'].keys()):
param = etree.SubElement(operationsmetadata,
util.nspath_eval('ows20:Parameter', self.parent.context.namespaces),
name=parameter)
param.append(self._write_allowed_values(self.parent.context.model['parameters'][parameter]['values']))
for qbl in sorted(self.parent.repository.queryables.keys()):
if qbl == 'SupportedDublinCoreQueryables':
param = etree.SubElement(operationsmetadata,
util.nspath_eval('ows20:Constraint',
self.parent.context.namespaces), name='CoreQueryables')
param.append(self._write_allowed_values(self.parent.repository.queryables[qbl]))
for constraint in sorted(self.parent.context.model['constraints'].keys()):
param = etree.SubElement(operationsmetadata,
util.nspath_eval('ows20:Constraint', self.parent.context.namespaces),
name=constraint)
param.append(self._write_allowed_values(self.parent.context.model['constraints'][constraint]['values']))
if self.parent.profiles is not None:
for prof in self.parent.profiles['loaded'].keys():
ecnode = \
self.parent.profiles['loaded'][prof].get_extendedcapabilities()
if ecnode is not None:
operationsmetadata.append(ecnode)
if languages:
LOGGER.info('Writing section ows:Languages')
langs = etree.SubElement(node,
util.nspath_eval('ows20:Languages', self.parent.context.namespaces))
etree.SubElement(langs,
util.nspath_eval('ows20:Language', self.parent.context.namespaces)).text = self.parent.language['639_code']
if not filtercaps:
return node
# always write out Filter_Capabilities
LOGGER.info('Writing section Filter_Capabilities')
fltcaps = etree.SubElement(node,
util.nspath_eval('fes20:Filter_Capabilities', self.parent.context.namespaces))
conformance = etree.SubElement(fltcaps,
util.nspath_eval('fes20:Conformance', self.parent.context.namespaces))
for value in fes2.MODEL['Conformance']['values']:
constraint = etree.SubElement(conformance,
util.nspath_eval('fes20:Constraint', self.parent.context.namespaces),
name=value)
etree.SubElement(constraint,
util.nspath_eval('ows11:NoValues', self.parent.context.namespaces))
etree.SubElement(constraint,
util.nspath_eval('ows11:DefaultValue', self.parent.context.namespaces)).text = 'TRUE'
idcaps = etree.SubElement(fltcaps,
util.nspath_eval('fes20:Id_Capabilities', self.parent.context.namespaces))
for idcap in fes2.MODEL['Ids']['values']:
etree.SubElement(idcaps, util.nspath_eval('fes20:ResourceIdentifier',
self.parent.context.namespaces), name=idcap)
scalarcaps = etree.SubElement(fltcaps,
util.nspath_eval('fes20:Scalar_Capabilities', self.parent.context.namespaces))
etree.SubElement(scalarcaps, util.nspath_eval('fes20:LogicalOperators',
self.parent.context.namespaces))
cmpops = etree.SubElement(scalarcaps,
util.nspath_eval('fes20:ComparisonOperators', self.parent.context.namespaces))
for cmpop in sorted(fes2.MODEL['ComparisonOperators'].keys()):
etree.SubElement(cmpops,
util.nspath_eval('fes20:ComparisonOperator',
self.parent.context.namespaces), name=fes2.MODEL['ComparisonOperators'][cmpop]['opname'])
spatialcaps = etree.SubElement(fltcaps,
util.nspath_eval('fes20:Spatial_Capabilities', self.parent.context.namespaces))
geomops = etree.SubElement(spatialcaps,
util.nspath_eval('fes20:GeometryOperands', self.parent.context.namespaces))
for geomtype in \
fes2.MODEL['GeometryOperands']['values']:
etree.SubElement(geomops,
util.nspath_eval('fes20:GeometryOperand',
self.parent.context.namespaces), name=geomtype)
spatialops = etree.SubElement(spatialcaps,
util.nspath_eval('fes20:SpatialOperators', self.parent.context.namespaces))
for spatial_comparison in \
fes2.MODEL['SpatialOperators']['values']:
etree.SubElement(spatialops,
util.nspath_eval('fes20:SpatialOperator', self.parent.context.namespaces),
name=spatial_comparison)
functions = etree.SubElement(fltcaps,
util.nspath_eval('fes20:Functions', self.parent.context.namespaces))
for fnop in sorted(fes2.MODEL['Functions'].keys()):
fn = etree.SubElement(functions,
util.nspath_eval('fes20:Function', self.parent.context.namespaces),
name=fnop)
etree.SubElement(fn, util.nspath_eval('fes20:Returns',
self.parent.context.namespaces)).text = \
fes2.MODEL['Functions'][fnop]['returns']
return node
def getdomain(self):
''' Handle GetDomain request '''
if ('parametername' not in self.parent.kvp and
'valuereference' not in self.parent.kvp):
return self.exceptionreport('MissingParameterValue',
'parametername', 'Missing value. \
One of valuereference or parametername must be specified')
node = etree.Element(util.nspath_eval('csw30:GetDomainResponse',
self.parent.context.namespaces), nsmap=self.parent.context.namespaces)
node.attrib[util.nspath_eval('xsi:schemaLocation',
self.parent.context.namespaces)] = '%s %s/cat/csw/3.0/cswGetDomain.xsd' % \
(self.parent.context.namespaces['csw30'],
self.parent.config.get('server', 'ogc_schemas_base'))
if 'parametername' in self.parent.kvp:
for pname in self.parent.kvp['parametername'].split(','):
LOGGER.info('Parsing parametername %s', pname)
domainvalue = etree.SubElement(node,
util.nspath_eval('csw30:DomainValues', self.parent.context.namespaces),
type='csw30:Record', resultType='available')
etree.SubElement(domainvalue,
util.nspath_eval('csw30:ParameterName',
self.parent.context.namespaces)).text = pname
try:
operation, parameter = pname.split('.')
except:
return node
if (operation in self.parent.context.model['operations'] and
parameter in self.parent.context.model['operations'][operation]['parameters']):
listofvalues = etree.SubElement(domainvalue,
util.nspath_eval('csw30:ListOfValues', self.parent.context.namespaces))
for val in \
sorted(self.parent.context.model['operations'][operation]\
['parameters'][parameter]['values']):
etree.SubElement(listofvalues,
util.nspath_eval('csw30:Value',
self.parent.context.namespaces)).text = val
if 'valuereference' in self.parent.kvp:
for pname in self.parent.kvp['valuereference'].split(','):
LOGGER.info('Parsing valuereference %s', pname)
if pname.find('/') == 0: # it's an XPath
pname2 = pname
else: # it's a core queryable, map to internal typename model
try:
pname2 = self.parent.repository.queryables['_all'][pname]['dbcol']
except:
pname2 = pname
# decipher typename
dvtype = None
if self.parent.profiles is not None:
for prof in self.parent.profiles['loaded'].keys():
for prefix in self.parent.profiles['loaded'][prof].prefixes:
if pname2.find(prefix) != -1:
dvtype = self.parent.profiles['loaded'][prof].typename
break
if not dvtype:
dvtype = 'csw30:Record'
domainvalue = etree.SubElement(node,
util.nspath_eval('csw30:DomainValues', self.parent.context.namespaces),
type=dvtype, resultType='available')
etree.SubElement(domainvalue,
util.nspath_eval('csw30:ValueReference',
self.parent.context.namespaces)).text = pname
try:
LOGGER.debug(
'Querying repository property %s, typename %s, \
domainquerytype %s',
pname2, dvtype, self.parent.domainquerytype)
results = self.parent.repository.query_domain(
pname2, dvtype, self.parent.domainquerytype, True)
LOGGER.debug('Results: %d', len(results))
if self.parent.domainquerytype == 'range':
rangeofvalues = etree.SubElement(domainvalue,
util.nspath_eval('csw30:RangeOfValues',
self.parent.context.namespaces))
etree.SubElement(rangeofvalues,
util.nspath_eval('csw30:MinValue',
self.parent.context.namespaces)).text = results[0][0]
etree.SubElement(rangeofvalues,
util.nspath_eval('csw30:MaxValue',
self.parent.context.namespaces)).text = results[0][1]
else:
listofvalues = etree.SubElement(domainvalue,
util.nspath_eval('csw30:ListOfValues',
self.parent.context.namespaces))
for result in results:
LOGGER.debug(str(result))
if (result is not None and
result[0] is not None): # drop null values
etree.SubElement(listofvalues,
util.nspath_eval('csw30:Value',
self.parent.context.namespaces),
count=str(result[1])).text = result[0]
except Exception as err:
# here we fail silently back to the client because
# CSW tells us to
LOGGER.exception('No results for propertyname')
return node
def getrecords(self):
''' Handle GetRecords request '''
timestamp = util.get_today_and_now()
if ('elementsetname' not in self.parent.kvp and
'elementname' not in self.parent.kvp):
if self.parent.requesttype == 'GET':
LOGGER.debug(self.parent.requesttype)
self.parent.kvp['elementsetname'] = 'summary'
else:
# mutually exclusive required
return self.exceptionreport('MissingParameterValue',
'elementsetname',
'Missing one of ElementSetName or ElementName parameter(s)')
if 'elementsetname' in self.parent.kvp and 'elementname' in self.parent.kvp and self.parent.kvp['elementname']:
# mutually exclusive required
return self.exceptionreport('NoApplicableCode',
'elementsetname',
'Only ONE of ElementSetName or ElementName parameter(s) is permitted')
if 'elementsetname' not in self.parent.kvp:
self.parent.kvp['elementsetname'] = 'summary'
if 'outputschema' not in self.parent.kvp:
self.parent.kvp['outputschema'] = self.parent.context.namespaces['csw30']
LOGGER.debug(self.parent.context.model['operations']['GetRecords']['parameters']['outputSchema']['values'])
if (self.parent.kvp['outputschema'] not in self.parent.context.model['operations']
['GetRecords']['parameters']['outputSchema']['values']):
return self.exceptionreport('InvalidParameterValue',
'outputschema', 'Invalid outputSchema parameter value: %s' %
self.parent.kvp['outputschema'])
if 'outputformat' not in self.parent.kvp:
self.parent.kvp['outputformat'] = 'application/xml'
if 'HTTP_ACCEPT' in self.parent.environ:
LOGGER.debug('Detected HTTP Accept header: %s', self.parent.environ['HTTP_ACCEPT'])
formats_match = False
if 'outputformat' in self.parent.kvp:
LOGGER.debug(self.parent.kvp['outputformat'])
for ofmt in self.parent.environ['HTTP_ACCEPT'].split(','):
LOGGER.info('Comparing %s and %s', ofmt, self.parent.kvp['outputformat'])
if ofmt.split('/')[0] in self.parent.kvp['outputformat']:
LOGGER.debug('FOUND OUTPUT MATCH')
formats_match = True
if not formats_match and self.parent.environ['HTTP_ACCEPT'] != '*/*':
return self.exceptionreport('InvalidParameterValue',
'outputformat', 'HTTP Accept header (%s) and outputformat (%s) must agree' %
(self.parent.environ['HTTP_ACCEPT'], self.parent.kvp['outputformat']))
else:
for ofmt in self.parent.environ['HTTP_ACCEPT'].split(','):
if ofmt in self.parent.context.model['operations']['GetRecords']['parameters']['outputFormat']['values']:
self.parent.kvp['outputformat'] = ofmt
break
if (self.parent.kvp['outputformat'] not in self.parent.context.model['operations']
['GetRecords']['parameters']['outputFormat']['values']):
return self.exceptionreport('InvalidParameterValue',
'outputformat', 'Invalid outputFormat parameter value: %s' %
self.parent.kvp['outputformat'])
if 'outputformat' in self.parent.kvp:
LOGGER.info('Setting content type')
self.parent.contenttype = self.parent.kvp['outputformat']
if self.parent.kvp['outputformat'] == 'application/atom+xml':
self.parent.kvp['outputschema'] = self.parent.context.namespaces['atom']
self.parent.mode = 'opensearch'
if (('elementname' not in self.parent.kvp or
len(self.parent.kvp['elementname']) == 0) and
self.parent.kvp['elementsetname'] not in
self.parent.context.model['operations']['GetRecords']['parameters']
['ElementSetName']['values']):
return self.exceptionreport('InvalidParameterValue',
'elementsetname', 'Invalid ElementSetName parameter value: %s' %
self.parent.kvp['elementsetname'])
if 'typenames' not in self.parent.kvp:
return self.exceptionreport('MissingParameterValue',
'typenames', 'Missing typenames parameter')
if ('typenames' in self.parent.kvp and
self.parent.requesttype == 'GET'): # passed via GET
#self.parent.kvp['typenames'] = self.parent.kvp['typenames'].split(',')
self.parent.kvp['typenames'] = ['csw:Record' if x=='Record' else x for x in self.parent.kvp['typenames'].split(',')]
if 'namespace' in self.parent.kvp:
LOGGER.info('resolving KVP namespace bindings')
LOGGER.debug(self.parent.kvp['typenames'])
self.parent.kvp['typenames'] = self.resolve_nsmap(self.parent.kvp['typenames'])
if 'elementname' in self.parent.kvp:
LOGGER.debug(self.parent.kvp['elementname'])
self.parent.kvp['elementname'] = self.resolve_nsmap(self.parent.kvp['elementname'].split(','))
if 'typenames' in self.parent.kvp:
for tname in self.parent.kvp['typenames']:
#if tname == 'Record':
# tname = 'csw:Record'
if (tname not in self.parent.context.model['operations']['GetRecords']
['parameters']['typeNames']['values']):
return self.exceptionreport('InvalidParameterValue',
'typenames', 'Invalid typeNames parameter value: %s' %
tname)
# check elementname's
if 'elementname' in self.parent.kvp:
for ename in self.parent.kvp['elementname']:
if ename not in self.parent.repository.queryables['_all']:
return self.exceptionreport('InvalidParameterValue',
'elementname', 'Invalid ElementName parameter value: %s' %
ename)
maxrecords_cfg = -1 # not set in config server.maxrecords
if self.parent.config.has_option('server', 'maxrecords'):
maxrecords_cfg = int(self.parent.config.get('server', 'maxrecords'))
if 'maxrecords' in self.parent.kvp and self.parent.kvp['maxrecords'] == 'unlimited':
LOGGER.debug('Detected maxrecords=unlimited')
self.parent.kvp.pop('maxrecords')
if 'maxrecords' not in self.parent.kvp: # not specified by client
if maxrecords_cfg > -1: # specified in config
self.parent.kvp['maxrecords'] = maxrecords_cfg
else: # spec default
self.parent.kvp['maxrecords'] = 10
else: # specified by client
if self.parent.kvp['maxrecords'] == '':
self.parent.kvp['maxrecords'] = 10
if maxrecords_cfg > -1: # set in config
if int(self.parent.kvp['maxrecords']) > maxrecords_cfg:
self.parent.kvp['maxrecords'] = maxrecords_cfg
if any(x in ['bbox', 'q', 'time'] for x in self.parent.kvp):
LOGGER.debug('OpenSearch Geo/Time parameters detected.')
self.parent.kvp['constraintlanguage'] = 'FILTER'
try:
tmp_filter = opensearch.kvp2filterxml(self.parent.kvp, self.parent.context)
except Exception as err:
return self.exceptionreport('InvalidParameterValue', 'bbox', str(err))
if tmp_filter is not "":
self.parent.kvp['constraint'] = tmp_filter
LOGGER.debug('OpenSearch Geo/Time parameters to Filter: %s.', self.parent.kvp['constraint'])
if self.parent.requesttype == 'GET':
if 'constraint' in self.parent.kvp:
# GET request
LOGGER.debug('csw:Constraint passed over HTTP GET.')
if 'constraintlanguage' not in self.parent.kvp:
return self.exceptionreport('MissingParameterValue',
'constraintlanguage',
'constraintlanguage required when constraint specified')
if (self.parent.kvp['constraintlanguage'] not in
self.parent.context.model['operations']['GetRecords']['parameters']
['CONSTRAINTLANGUAGE']['values']):
return self.exceptionreport('InvalidParameterValue',
'constraintlanguage', 'Invalid constraintlanguage: %s'
% self.parent.kvp['constraintlanguage'])
if self.parent.kvp['constraintlanguage'] == 'CQL_TEXT':
tmp = self.parent.kvp['constraint']
try:
LOGGER.info('Transforming CQL into fes1')
LOGGER.debug('CQL: %s', tmp)
self.parent.kvp['constraint'] = {}
self.parent.kvp['constraint']['type'] = 'filter'
cql = cql2fes1(tmp, self.parent.context.namespaces)
self.parent.kvp['constraint']['where'], self.parent.kvp['constraint']['values'] = fes1.parse(cql,
self.parent.repository.queryables['_all'], self.parent.repository.dbtype,
self.parent.context.namespaces, self.parent.orm, self.parent.language['text'], self.parent.repository.fts)
self.parent.kvp['constraint']['_dict'] = xml2dict(etree.tostring(cql), self.parent.context.namespaces)
except Exception as err:
LOGGER.exception('Invalid CQL query %s', tmp)
return self.exceptionreport('InvalidParameterValue',
'constraint', 'Invalid Filter syntax')
elif self.parent.kvp['constraintlanguage'] == 'FILTER':
# validate filter XML
try:
schema = os.path.join(self.parent.config.get('server', 'home'),
'core', 'schemas', 'ogc', 'filter', '1.1.0', 'filter.xsd')
LOGGER.info('Validating Filter %s.', self.parent.kvp['constraint'])
schema = etree.XMLSchema(file=schema)
parser = etree.XMLParser(schema=schema, resolve_entities=False)
doc = etree.fromstring(self.parent.kvp['constraint'], parser)
LOGGER.debug('Filter is valid XML.')
self.parent.kvp['constraint'] = {}
self.parent.kvp['constraint']['type'] = 'filter'
self.parent.kvp['constraint']['where'], self.parent.kvp['constraint']['values'] = \
fes2.parse(doc,
self.parent.repository.queryables['_all'],
self.parent.repository.dbtype,
self.parent.context.namespaces, self.parent.orm, self.parent.language['text'], self.parent.repository.fts)
self.parent.kvp['constraint']['_dict'] = xml2dict(etree.tostring(doc), self.parent.context.namespaces)
except Exception as err:
errortext = \
'Exception: document not valid.\nError: %s' % str(err)
LOGGER.exception(errortext)
return self.exceptionreport('InvalidParameterValue',
'bbox', 'Invalid Filter query: %s' % errortext)
else:
self.parent.kvp['constraint'] = {}
if 'sortby' not in self.parent.kvp:
self.parent.kvp['sortby'] = None
elif 'sortby' in self.parent.kvp and self.parent.requesttype == 'GET':
LOGGER.debug('Sorted query specified')
tmp = self.parent.kvp['sortby']
self.parent.kvp['sortby'] = {}
try:
name, order = tmp.rsplit(':', 1)
except:
return self.exceptionreport('InvalidParameterValue',
'sortby', 'Invalid SortBy value: must be in the format\
propertyname:A or propertyname:D')
try:
self.parent.kvp['sortby']['propertyname'] = \
self.parent.repository.queryables['_all'][name]['dbcol']
if name.find('BoundingBox') != -1 or name.find('Envelope') != -1:
# it's a spatial sort
self.parent.kvp['sortby']['spatial'] = True
except Exception as err:
return self.exceptionreport('InvalidParameterValue',
'sortby', 'Invalid SortBy propertyname: %s' % name)
if order not in ['A', 'D']:
return self.exceptionreport('InvalidParameterValue',
'sortby', 'Invalid SortBy value: sort order must be "A" or "D"')
if order == 'D':
self.parent.kvp['sortby']['order'] = 'DESC'
else:
self.parent.kvp['sortby']['order'] = 'ASC'
if 'startposition' not in self.parent.kvp:
self.parent.kvp['startposition'] = 1
if 'recordids' in self.parent.kvp and self.parent.kvp['recordids'] != '':
# query repository
LOGGER.info('Querying repository with RECORD ids: %s', self.parent.kvp['recordids'])
results = self.parent.repository.query_ids(self.parent.kvp['recordids'].split(','))
matched = str(len(results))
if len(results) == 0:
return self.exceptionreport('NotFound', 'recordids',
'No records found for \'%s\'' % self.parent.kvp['recordids'])
else:
# query repository
LOGGER.info('Querying repository with constraint: %s,\
sortby: %s, typenames: %s, maxrecords: %s, startposition: %s.',
self.parent.kvp['constraint'], self.parent.kvp['sortby'], self.parent.kvp['typenames'],
self.parent.kvp['maxrecords'], self.parent.kvp['startposition'])
try:
matched, results = self.parent.repository.query(
constraint=self.parent.kvp['constraint'],
sortby=self.parent.kvp['sortby'], typenames=self.parent.kvp['typenames'],
maxrecords=self.parent.kvp['maxrecords'],
startposition=int(self.parent.kvp['startposition'])-1)
except Exception as err:
LOGGER.exception('Invalid query syntax. Query: %s', self.parent.kvp['constraint'])
LOGGER.exception('Invalid query syntax. Result: %s', err)
return self.exceptionreport('InvalidParameterValue', 'constraint',
'Invalid query syntax')
if int(matched) == 0:
returned = nextrecord = '0'
elif int(self.parent.kvp['maxrecords']) == 0:
returned = nextrecord = '0'
elif int(matched) < int(self.parent.kvp['startposition']):
returned = nextrecord = '0'
elif int(matched) <= int(self.parent.kvp['startposition']) + int(self.parent.kvp['maxrecords']) - 1:
returned = str(int(matched) - int(self.parent.kvp['startposition']) + 1)
nextrecord = '0'
else:
returned = str(self.parent.kvp['maxrecords'])
nextrecord = str(int(self.parent.kvp['startposition']) + int(self.parent.kvp['maxrecords']))
LOGGER.debug('Results: matched: %s, returned: %s, next: %s',
matched, returned, nextrecord)
node = etree.Element(util.nspath_eval('csw30:GetRecordsResponse',
self.parent.context.namespaces),
nsmap=self.parent.context.namespaces, version='3.0.0')
node.attrib[util.nspath_eval('xsi:schemaLocation',
self.parent.context.namespaces)] = \
'%s %s/cat/csw/3.0/cswGetRecordsResponse.xsd' % \
(self.parent.context.namespaces['csw30'], self.parent.config.get('server', 'ogc_schemas_base'))
if 'requestid' in self.parent.kvp and self.parent.kvp['requestid'] is not None:
etree.SubElement(node, util.nspath_eval('csw:RequestId',
self.parent.context.namespaces)).text = self.parent.kvp['requestid']
etree.SubElement(node, util.nspath_eval('csw30:SearchStatus',
self.parent.context.namespaces), timestamp=timestamp)
#if 'where' not in self.parent.kvp['constraint'] and \
#self.parent.kvp['resulttype'] is None:
# returned = '0'
searchresults = etree.SubElement(node,
util.nspath_eval('csw30:SearchResults', self.parent.context.namespaces),
numberOfRecordsMatched=matched, numberOfRecordsReturned=returned,
nextRecord=nextrecord, recordSchema=self.parent.kvp['outputschema'],
expires=timestamp, status=get_resultset_status(matched, nextrecord))
if self.parent.kvp['elementsetname'] is not None:
searchresults.attrib['elementSet'] = self.parent.kvp['elementsetname']
#if 'where' not in self.parent.kvp['constraint'] \
#and self.parent.kvp['resulttype'] is None:
# LOGGER.debug('Empty result set returned')
# return node
if results is not None:
if len(results) < int(self.parent.kvp['maxrecords']):
max1 = len(results)
else:
max1 = int(self.parent.kvp['startposition']) + (int(self.parent.kvp['maxrecords'])-1)
LOGGER.info('Presenting records %s - %s',
self.parent.kvp['startposition'], max1)
for res in results:
try:
if (self.parent.kvp['outputschema'] ==
'http://www.opengis.net/cat/csw/3.0' and
('csw:Record' in self.parent.kvp['typenames'] or
'csw30:Record' in self.parent.kvp['typenames'])):
# serialize csw:Record inline
searchresults.append(self._write_record(
res, self.parent.repository.queryables['_all']))
elif (self.parent.kvp['outputschema'] ==
'http://www.opengis.net/cat/csw/3.0' and
'csw:Record' not in self.parent.kvp['typenames']):
# serialize into csw:Record model
for prof in self.parent.profiles['loaded']:
# find source typename
if self.parent.profiles['loaded'][prof].typename in \
self.parent.kvp['typenames']:
typename = self.parent.profiles['loaded'][prof].typename
break
util.transform_mappings(
self.parent.repository.queryables['_all'],
self.parent.context.model['typenames'][typename][
'mappings']['csw:Record']
)
searchresults.append(self._write_record(
res, self.parent.repository.queryables['_all']))
elif self.parent.kvp['outputschema'] in self.parent.outputschemas: # use outputschema serializer
searchresults.append(self.parent.outputschemas[self.parent.kvp['outputschema']].write_record(res, self.parent.kvp['elementsetname'], self.parent.context, self.parent.config.get('server', 'url')))
else: # use profile serializer
searchresults.append(
self.parent.profiles['loaded'][self.parent.kvp['outputschema']].\
write_record(res, self.parent.kvp['elementsetname'],
self.parent.kvp['outputschema'],
self.parent.repository.queryables['_all']))
except Exception as err:
self.parent.response = self.exceptionreport(
'NoApplicableCode', 'service',
'Record serialization failed: %s' % str(err))
return self.parent.response
if (self.parent.config.has_option('server', 'federatedcatalogues') and
'distributedsearch' in self.parent.kvp and
self.parent.kvp['distributedsearch'] and self.parent.kvp['hopcount'] > 0):
# do distributed search
LOGGER.debug('DistributedSearch specified (hopCount: %s)',
self.parent.kvp['hopcount'])
from owslib.csw import CatalogueServiceWeb
from owslib.ows import ExceptionReport
for fedcat in \
self.parent.config.get('server', 'federatedcatalogues').split(','):
LOGGER.info('Performing distributed search on federated \
catalogue: %s', fedcat)
try:
start_time = time()
remotecsw = CatalogueServiceWeb(fedcat, skip_caps=True)
remotecsw.getrecords2(xml=self.parent.request,
esn=self.parent.kvp['elementsetname'],
outputschema=self.parent.kvp['outputschema'])
fsr = etree.SubElement(searchresults, util.nspath_eval(
'csw30:FederatedSearchResult',
self.parent.context.namespaces),
catalogueURL=fedcat.request)
msg = 'Distributed search results from catalogue %s: %s.' % (fedcat, remotecsw.results)
LOGGER.debug(msg)
fsr.append(etree.Comment(msg))