source: TI07-MOLES/trunk/PythonCode/returnMoles/returnMolesExist.py @ 1560

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI07-MOLES/trunk/PythonCode/returnMoles/returnMolesExist.py@1560
Revision 1560, 88.7 KB checked in by ko23, 13 years ago (diff)

Fix XMLSpy's malign influence +

Line 
1#!/usr/bin/env python
2
3import urllib2, base64, urllib, urlparse, httplib, xmlrpclib, types, sys, getopt
4
5
6class   InstanceObject(object):
7    def __init__(self, **kw):
8        self.dict={}
9        self.dict.update(kw)
10       
11    def __getattr__(self,arg):
12        return self.dict[arg]
13
14class    eXist_Connector(object):
15    """Access class for eXist"""
16    def __init__(self,constants=None):
17        #make sure that we have these constants in scope for command line playfulness
18        if constants is None:constants=eXistConstants
19        authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm()
20        authinfo.add_password(None,
21                                  constants.host,
22                                  constants.userid,
23                                  constants.password)
24        authHandler = urllib2.HTTPBasicAuthHandler(authinfo)
25        opener = urllib2.build_opener(authHandler)
26        s = constants.userid+':'+constants.password
27        z = base64.encodestring(s)[:-1] # strip trailing 12
28        opener.addheaders.append(('Authorization', 'Basic %s' % z))
29        self.http_headers = {'Authorization':'Basic %s' % z}
30        self.opener = opener
31        # also create an xmlrpc Server object
32       
33        xmlrpc_uri = '%s%s:%s@%s:%d%s' % ( 
34                                            'http://',
35                                            constants.userid,
36                                            constants.password,
37                                            constants.host,
38                                            constants.port,
39                                            constants.xmlrpc_base_path
40                                        )
41        self.xmlrpc = xmlrpclib.Server(xmlrpc_uri)
42       
43    def execute(self, collection, application=None, subpath=None):
44        """Execute an xquery stored in eXist, return result as string"""
45        path = self.generate_db_path(collection=collection, application=application, 
46                            subpath=subpath)
47        params = {}
48        r = self.xmlrpc.execute(path, params)
49        try:
50            res = self.xmlrpc.retrieve(r['id'], 0, {})
51        finally:
52            self.xmlrpc.releaseQueryResult(r['id'])
53        return res.data
54
55    def executeQuery(self, xquery, params={}):
56        """Execute an xquery string, return result as string"""
57        xquery=xmlrpclib.Binary(xquery) #bnl
58        id = self.xmlrpc.executeQuery(xquery, params)
59        try:
60            res = self.xmlrpc.retrieve(id, 0, {})
61            print res.data,'bb'
62        finally:
63            self.xmlrpc.releaseQueryResult(id)
64        return res.data
65
66    def open(self, url):
67        """Open url and return url handler"""
68        return self.opener.open(url)
69
70    def http_request(self, url, method="GET", body=None, extra_headers=None, 
71                                                            extra_args=None):
72        """Open an HTTPConnection to server, splits url into parts
73           and adds headers as appropriate
74           extra_args can be a dictionary
75        """
76        parts = urlparse.urlparse(url)
77        scheme, location, path, parameters, query, fragment = parts
78        if scheme == 'https':
79            http = httplib.HTTPSConnection(location)
80        else:
81            http = httplib.HTTPConnection(location)
82        if extra_args:
83            extra_args = urllib.urlencode(extra_args)
84            if not query:
85                query = extra_args
86            else:
87                query = "%s&%s" % (query, extra_args)
88        if query and not body:
89            body = query
90        if not extra_headers:
91            extra_headers = {}
92        extra_headers.update(self.http_headers)
93        http.request(method, path, body, extra_headers )
94        return http.getresponse()
95
96def convTuple(t):
97        return {t[0]:t[1]}
98
99def printUsage():
100        print "\n\nThe mandatory command line options for this script are:"
101        print "\t--repositoryID"
102        print "\t--localID"
103        print "\t--format\n\t\tSupported values are:"
104        print "\t\t\tDC\t\t- Dublin Core"
105        print "\t\t\tDIF\t\t- GCMD DIF v9.4"
106        print "\t\t\tNDG-B0\t\t- Raw MOLES"
107        print "\t\t\tNDG-B1\t\t- StubB from MOLES"
108        print "\t\t\tISO19115\t- Base ISO19139"
109        print "\nOptional parameters are:"
110        print  "\t--user\t\teXist user ID; defaults to 'guest'"
111        print  "\t--userpw\t\teXist user ID password; defaults to 'guest'"
112        print  "\t--repository\t\pointer to eXist installation; defaults to 'localhost'"
113        print  "\t--port\t\pointer to eXist installation port number; defaults to '8080'"
114        print "\nAs an example:"
115        print '\tpython returnMoles.py --repositoryID=badc.nerc.ac.uk --localID=dataent20 -format=DC --repository=badc.nerc.ac.uk --port=8088 --userpw=secret' 
116        print '\nPlease note that spaces in parameter values may cause malfunction' 
117        print 'Non-zero return codes:'
118        print '\t10 - zero records returned (ID not found)'
119        print '\t11 - more than one record returned: check database and db records'
120        sys.exit(1)
121
122def XQueryDC(repositoryID, localID):
123    xquery = "declare namespace dc='http://purl.org/dc/elements/1.1/';"
124    xquery = xquery + " declare namespace oai_dc='http://www.openarchives.org/OAI/2.0/oai_dc';"
125    xquery = xquery + " declare variable $gcmd_science_valids as xs:string {'http://gcmd.gsfc.nasa.gov/Resources/valids/gcmd_parameters.html'};"
126    xquery = xquery + " declare variable $gcmd_project_valids as xs:string {'http://gcmd.gsfc.nasa.gov/Resources/valids/projects.html'};"
127    xquery = xquery + " declare variable $cf_standard_names as xs:string {'http://www.cgd.ucar.edu/cms/eaton/cf-metadata/standard_name.html'};"
128    xquery = xquery + " declare variable $iso_topic_list as xs:string {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_TopicCategoryCode'};"
129    xquery = xquery + " for $DE in collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[dgDataEntity!='' and dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier="
130    xquery = xquery + "'" + repositoryID + "'"
131    xquery = xquery + " and dgMetadataID/localIdentifier="
132    xquery = xquery + "'" + localID + "'"
133    xquery = xquery + " ]"
134    xquery = xquery + " return "
135    xquery = xquery + " <oai_dc:dc xmlns:oai_dc='http://www.openarchives.org/OAI/2.0/oai_dc/' xmlns:dc='http://purl.org/dc/elements/1.1/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd'>"
136    xquery = xquery + " {"
137    xquery = xquery + " element dc:title {string($DE/name)},"
138    xquery = xquery + " element dc:type {'Dataset'},"
139    xquery = xquery + " element dc:identifier {concat($DE/dgMetadataID/repositoryIdentifier, ':DC:', $DE/dgMetadataID/localIdentifier)},"
140    xquery = xquery + " element dc:description {string($DE/dgMetadataDescription/abstract/abstractText)},"
141    xquery = xquery + " element dc:date"
142    xquery = xquery + "  {"
143    xquery = xquery + "  if (exists($DE/(dgMetadataProvenance | DataProvenance)/RecordUpdate/UpdateDate)) then "
144    xquery = xquery + "  for $updatedate in $DE/(dgMetadataProvenance | DataProvenance)/RecordUpdate/UpdateDate"
145    xquery = xquery + "   order by xs:date($updatedate) descending"
146    xquery = xquery + "   return xs:date($updatedate[1])"
147    xquery = xquery + "  else "
148    xquery = xquery + "  string($DE/(dgMetadataProvenance | DataProvenance)/RecordCreation/CreatedDate) "
149    xquery = xquery + "  },"
150    xquery = xquery + " for $StructuredKeyword in distinct-values($DE/dgStructuredKeyword [dgValidTermID/ParentListID=$cf_standard_names or dgValidTermID/ParentListID=$gcmd_science_valids or dgValidTermID/ParentListID=$gcmd_project_valids or dgValidTermID/ParentListID=$iso_topic_list ]//dgValidTerm ) "
151    xquery = xquery + " order by $StructuredKeyword"
152    xquery = xquery + " return "
153    xquery = xquery + " element dc:subject {string($StructuredKeyword)},"
154    xquery = xquery + " for $StructuredKeyword1 in distinct-values($DE/dgDataEntity/dgDataSummary/dgParameterSummary/dgStdParameterMeasured[dgValidTermID/ParentListID=$cf_standard_names or dgValidTermID/ParentListID=$gcmd_science_valids or dgValidTermID/ParentListID=$gcmd_project_valids]//dgValidTerm) "
155    xquery = xquery + " order by $StructuredKeyword1"
156    xquery = xquery + " return "
157    xquery = xquery + " element dc:subject {string($StructuredKeyword1)},"
158    xquery = xquery + " for $DataCreatorRole in $DE/dgDataEntity/dgDataRoles/dgDataCreator/dgRoleHolder "
159    xquery = xquery + "  order by $DataCreatorRole/startDate empty least, $DataCreatorRole/endDate empty least"
160    xquery = xquery + "    return "
161    xquery = xquery + "  for $DataCreatorRoleHolder in collection('/db/ndg_B_metadata')/(dgOrganisation | dgPerson)[((not(exists($DataCreatorRole/endDate)) or empty($DataCreatorRole/endDate)) and dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier=$DataCreatorRole/*/repositoryIdentifier and dgMetadataID/localIdentifier=$DataCreatorRole/*/localIdentifier)]"
162    xquery = xquery + "  return "
163    xquery = xquery + "   element dc:creator {"
164    xquery = xquery + "  if (string(local-name($DataCreatorRoleHolder))='dgOrganisation') then"
165    xquery = xquery + " (string($DataCreatorRoleHolder/name))"
166    xquery = xquery + "  else if (string(local-name($DataCreatorRoleHolder))='dgPerson') then"
167    xquery = xquery + " (string(concat(string($DataCreatorRoleHolder/name/initials), ' ', string($DataCreatorRoleHolder/name/familyName))))"
168    xquery = xquery + "  else ('empty content')"
169    xquery = xquery + " },"
170    xquery = xquery + "   for $DataCuratorRole in $DE/dgDataEntity/dgDataRoles/dgDataCurator/dgRoleHolder[not(exists(endDate)) or endDate='']"
171    xquery = xquery + "   return "
172    xquery = xquery + "    for $DataCuratorRoleHolder in collection('/db/ndg_B_metadata')/dgMetadata/*[(dgMetadataID/schemeIdentifier='NDG-B0'"
173    xquery = xquery + "     and dgMetadataID/repositoryIdentifier=$DataCuratorRole/*/repositoryIdentifier"
174    xquery = xquery + "     and dgMetadataID/localIdentifier=$DataCuratorRole/*/localIdentifier)]"
175    xquery = xquery + "    return "
176    xquery = xquery + "     element dc:publisher {"
177    xquery = xquery + "  if (string(local-name($DataCuratorRoleHolder))='dgOrganisation') then"
178    xquery = xquery + " (string($DataCuratorRoleHolder/name))"
179    xquery = xquery + "  else if (string(local-name($DataCuratorRoleHolder))='dgPerson') then"
180    xquery = xquery + " (string(concat(string($DataCuratorRoleHolder/name/initials), ' ', string($DataCuratorRoleHolder/name/familyName))))"
181    xquery = xquery + "  else ('empty content')"
182    xquery = xquery + "  }"
183    xquery = xquery + "  }"
184    xquery = xquery + " </oai_dc:dc>"
185    return xquery
186
187def XQueryDIF(repositoryID, localID):
188    xquery = "for $DE in collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[exists('dgDataEntity') and dgMetadataID/schemeIdentifier='NDG-B0'"
189    xquery = xquery + " and dgMetadataID/repositoryIdentifier='" + repositoryID + "'"
190    xquery = xquery + " and dgMetadataID/localIdentifier='" + localID + "']"
191    xquery = xquery + " return"
192    xquery = xquery + " <DIF xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns='http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/' xsi:schemaLocation='http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/ http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/dif_v9.4.xsd'>"
193    xquery = xquery + " {"
194    xquery = xquery + " element Entry_ID {concat($DE/dgMetadataID/repositoryIdentifier, ':DIF:', $DE/dgMetadataID/localIdentifier)},"
195    xquery = xquery + " element Entry_Title {string($DE/name)},"
196    xquery = xquery + " element Data_Set_Citation"
197    xquery = xquery + " {"
198    xquery = xquery + " for $DataCreatorRole in $DE/dgDataEntity/dgDataRoles/dgDataCreator/dgRoleHolder[not(exists(endDate)) or endDate=''][1]"
199    xquery = xquery + " return "
200    xquery = xquery + " for $DataCreatorRoleHolder in collection('/db/ndg_B_metadata')/dgMetadata/*[(dgMetadataID/schemeIdentifier='NDG-B0'"
201    xquery = xquery + " and dgMetadataID/repositoryIdentifier=$DataCreatorRole/*/repositoryIdentifier"
202    xquery = xquery + " and dgMetadataID/localIdentifier=$DataCreatorRole/*/localIdentifier)]"
203    xquery = xquery + " return "
204    xquery = xquery + " element Data_Creator "
205    xquery = xquery + " {"
206    xquery = xquery + " if (exists($DataCreatorRoleHolder/name/initials)) then "
207    xquery = xquery + " (string(concat(string($DataCreatorRoleHolder/name/initials), ' ', string($DataCreatorRoleHolder/name/familyName))))"
208    xquery = xquery + " else "
209    xquery = xquery + " (string($DataCreatorRoleHolder/abbreviation))"
210    xquery = xquery + " },"
211    xquery = xquery + " element Dataset_Title {string($DE/name)}"
212    xquery = xquery + " },"
213    xquery = xquery + " for $StructuredKeyword in ($DE//(dgStructuredKeyword | dgStdParameterMeasured)[dgValidTermID/ParentListID='http://gcmd.gsfc.nasa.gov/Resources/valids/gcmd_parameters.html' and ListLevel = 0])"
214    xquery = xquery + " return if (exists($StructuredKeyword/*/dgValidTerm)) then ("
215    xquery = xquery + " element Parameters"
216    xquery = xquery + " {"
217    xquery = xquery + " element Category {string($StructuredKeyword/*/dgValidTerm)},"
218    xquery = xquery + " if (exists($StructuredKeyword//dgValidSubterm) "
219    xquery = xquery + " and $StructuredKeyword//dgValidSubterm != '' "
220    xquery = xquery + " and $StructuredKeyword//dgValidSubterm != ' ') then ("
221    xquery = xquery + " for $Subterm in $StructuredKeyword//dgValidSubterm[exists(dgValidTerm)]"
222    xquery = xquery + " where exists($Subterm/dgValidSubterm)"
223    xquery = xquery + " order by $Subterm/ListLevel"
224    xquery = xquery + " return "
225    xquery = xquery + " if ($Subterm/ListLevel=1) then (element Topic {string($Subterm/dgValidSubterm/dgValidTerm)}) "
226    xquery = xquery + " else ("
227    xquery = xquery + " if ($Subterm/ListLevel=2) then (element Term {string($Subterm/dgValidSubterm/dgValidTerm)}) "
228    xquery = xquery + " else ("
229    xquery = xquery + " if ($Subterm/ListLevel=3) then (element Variable {string($Subterm/dgValidSubterm/dgValidTerm)}) "
230    xquery = xquery + " else ("
231    xquery = xquery + " if ($Subterm/ListLevel=4) then (element Detailed_Variable {string($Subterm/dgValidSubterm/dgValidTerm)}) "
232    xquery = xquery + " else (element GCMD_Science_Valid {string($Subterm/dgValidSubterm/dgValidTerm)}))))"
233    xquery = xquery + " )"
234    xquery = xquery + " else()"
235    xquery = xquery + " }"
236    xquery = xquery + " )"
237    xquery = xquery + " else(),"
238    xquery = xquery + " for $ISOTopicCategory in ($DE/dgStructuredKeyword[dgValidTermID/ParentListID='http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_TopicCategoryCode'])"
239    xquery = xquery + " return "
240    xquery = xquery + " element ISO_Topic_Category {string($ISOTopicCategory/dgValidTerm)},"
241    xquery = xquery + " for $Keyword in distinct-values($DE//dgStructuredKeyword["
242    xquery = xquery + " dgValidTermID/ParentListID!='http://gcmd.gsfc.nasa.gov/Resources/valids/gcmd_parameters.html' "
243    xquery = xquery + " and "
244    xquery = xquery + " dgValidTermID/ParentListID!='http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_TopicCategoryCode' "
245    xquery = xquery + " ]/dgValidTerm)"
246    xquery = xquery + " return element Keyword {string($Keyword)}, "
247    xquery = xquery + " for $DepDPT in ($DE/dgDataEntity/RelatedDeployment/DataProductionToolID) "
248    xquery = xquery + " return "
249    xquery = xquery + " element Sensor_Name"
250    xquery = xquery + " {"
251    xquery = xquery + " for $DepDPTAbbrev in distinct-values((collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[dgMetadataID[schemeIdentifier='NDG-B0' and repositoryIdentifier=$DepDPT/repositoryIdentifier and localIdentifier=$DepDPT/localIdentifier]]/abbreviation))"
252    xquery = xquery + " return element Short_Name {data($DepDPTAbbrev)},"
253    xquery = xquery + " for $DepDPTName in distinct-values((collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[dgMetadataID[schemeIdentifier='NDG-B0' and repositoryIdentifier=$DepDPT/repositoryIdentifier and localIdentifier=$DepDPT/localIdentifier]]/name))"
254    xquery = xquery + " return element Long_Name {data($DepDPTName)}"
255    xquery = xquery + " },"
256    xquery = xquery + " for $DepObsStn in ($DE/dgDataEntity/RelatedDeployment/ObservationStationID)"
257    xquery = xquery + " return "
258    xquery = xquery + " element Source_Name"
259    xquery = xquery + " {"
260    xquery = xquery + " for $DepObsStnAbbrev in distinct-values((collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[dgMetadataID[schemeIdentifier='NDG-B0' and repositoryIdentifier=$DepObsStn/repositoryIdentifier and localIdentifier=$DepObsStn/localIdentifier]]/abbreviation))"
261    xquery = xquery + " return element Short_Name {data($DepObsStnAbbrev)},"
262    xquery = xquery + " for $DepObsStnName in distinct-values((collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[dgMetadataID[schemeIdentifier='NDG-B0' and repositoryIdentifier=$DepObsStn/repositoryIdentifier and localIdentifier=$DepObsStn/localIdentifier]]/name))"
263    xquery = xquery + " return element Long_Name {data($DepObsStnName)}"
264    xquery = xquery + " },"
265    xquery = xquery + " for $TemporalRange in ($DE/dgDataEntity/dgDataSummary/dgDataCoverage/(dgTemporalCoverage | dgSpatioTemporalcoverage/dgSpatioTemporalRange/dgSpatialCoverage)/dgDateRange)"
266    xquery = xquery + " return "
267    xquery = xquery + " element Temporal_Coverage"
268    xquery = xquery + " {"
269    xquery = xquery + " element Start_Date {data($TemporalRange/DateRangeStart)},"
270    xquery = xquery + " element End_Date {data($TemporalRange/DateRangeEnd)}"
271    xquery = xquery + " },"
272    xquery = xquery + " for $TemporalTerm in ($DE/dgDataEntity/dgDataSummary/dgDataCoverage/(dgTemporalCoverage | dgSpatioTemporalcoverage/dgSpatioTemporalRange/dgSpatialCoverage)/dgArea/dgValidTerm)"
273    xquery = xquery + " return element Paleo_Temporal_Coverage "
274    xquery = xquery + " {"
275    xquery = xquery + " element Chronostratigraphic_Unit {data($TemporalTerm)}"
276    xquery = xquery + " }, "
277    xquery = xquery + " for $Data_Set_Progress in ($DE/dgDataEntity/dgDataSummary/dgDataStatus/dgDatasetClosure)"
278    xquery = xquery + " return element Data_Set_Progress {$Data_Set_Progress},"
279    xquery = xquery + " for $BoundingBox in ($DE/dgDataEntity/dgDataSummary/dgDataCoverage/(dgSpatialCoverage | dgSpatioTemporalcoverage/dgSpatioTemporalRange/dgSpatialCoverage)/BoundingBox)"
280    xquery = xquery + " return "
281    xquery = xquery + " element Spatial_Coverage"
282    xquery = xquery + " {"
283    xquery = xquery + " element Southernmost_Latitude {data($BoundingBox/LimitSouth)},"
284    xquery = xquery + " element Northernmost_Latitude {data($BoundingBox/LimitNorth)},"
285    xquery = xquery + " element Westernmost_Longitude {data($BoundingBox/LimitWest)},"
286    xquery = xquery + " element Easternmost_Longitude {data($BoundingBox/LimitEast)}"
287    xquery = xquery + " },"
288    xquery = xquery + " for $Location in ($DE/dgDataEntity/dgDataSummary/dgDataCoverage/(dgSpatialCoverage | dgSpatioTemporalcoverage/dgSpatioTemporalRange/dgSpatialCoverage)/dgArea[dgValidTermID/ParentListID='http://gcmd.gsfc.nasa.gov/Resources/valids/gcmd_locations.html'])"
289    xquery = xquery + " return element Location {$Location}, "
290    xquery = xquery + " for $DepAct in ($DE/dgDataEntity/RelatedDeployment/ActivityID)"
291    xquery = xquery + " return "
292    xquery = xquery + " element Project"
293    xquery = xquery + " {"
294    xquery = xquery + " for $DepActAbbrev in distinct-values((collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[dgMetadataID[schemeIdentifier='NDG-B0' and repositoryIdentifier=$DepAct/repositoryIdentifier and localIdentifier=$DepAct/localIdentifier]]/abbreviation))"
295    xquery = xquery + " return "
296    xquery = xquery + " element Short_Name {data($DepActAbbrev)},"
297    xquery = xquery + " for $DepActName in distinct-values((collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[dgMetadataID[schemeIdentifier='NDG-B0' and repositoryIdentifier=$DepAct/repositoryIdentifier and localIdentifier=$DepAct/localIdentifier]]/name))"
298    xquery = xquery + " return "
299    xquery = xquery + " element Long_Name {data($DepActName)}"
300    xquery = xquery + " },"
301    xquery = xquery + " if (exists($DE/dgDataEntity/dgDataGranule/accessControlPolicy)) then ("
302    xquery = xquery + " for $DG in $DE/dgDataEntity/dgDataGranule"
303    xquery = xquery + " return "
304    xquery = xquery + " element Access_Constraints "
305    xquery = xquery + " {"
306    xquery = xquery + " if (exists($DG/dgGranuleSummary/dgGranuleName)) then "
307    xquery = xquery + " concat('For data granule ', $DG/dgGranuleSummary/dgGranuleName, ': ')"
308    xquery = xquery + " else (),"
309    xquery = xquery + " if (exists($DG/accessControlPolicy/accessControlPolicyURL)) then"
310    xquery = xquery + " concat('See access control policy at ', escape-uri($DG/accessControlPolicy/accessControlPolicyURL, true()))"
311    xquery = xquery + " else if (exists($DG/accessControlPolicy/accessControlPolicyText)) then"
312    xquery = xquery + " ("
313    xquery = xquery + " data($DG/accessControlPolicy/accessControlPolicyText)"
314    xquery = xquery + " )"
315    xquery = xquery + " else ("
316    xquery = xquery + " for $securityCondition in $DG/accessControlPolicy/dgSecurityCondition"
317    xquery = xquery + " return"
318    xquery = xquery + " if (exists($securityCondition/conditionExplanationText)) then"
319    xquery = xquery + " concat('Effect: ', data($securityCondition/effect), ' - ', data($securityCondition/conditionExplanationText))"
320    xquery = xquery + " else ("
321    xquery = xquery + " concat('Effect: ', data($securityCondition/effect), 'needs ', data($securityCondition/attauthRole), ' from ', data($securityCondition/dgAttributeAuthority))"
322    xquery = xquery + " )"
323    xquery = xquery + " )"
324    xquery = xquery + " }"
325    xquery = xquery + " )"
326    xquery = xquery + " else (),"
327    xquery = xquery + " for $DataCuratorRole in $DE/dgDataEntity/dgDataRoles/dgDataCurator/dgRoleHolder[not(exists(endDate)) or endDate='']"
328    xquery = xquery + " return "
329    xquery = xquery + " for $DataCuratorRoleHolder in collection('/db/ndg_B_metadata')/dgMetadata/*[(dgMetadataID/schemeIdentifier='NDG-B0'"
330    xquery = xquery + " and dgMetadataID/repositoryIdentifier=$DataCuratorRole/*/repositoryIdentifier"
331    xquery = xquery + " and dgMetadataID/localIdentifier=$DataCuratorRole/*/localIdentifier)]"
332    xquery = xquery + " return "
333    xquery = xquery + " element Data_Center"
334    xquery = xquery + " {"
335    xquery = xquery + " element Data_Center_Name"
336    xquery = xquery + " {"
337    xquery = xquery + " element Short_Name "
338    xquery = xquery + " {"
339    xquery = xquery + " if (exists($DataCuratorRoleHolder/name/initials)) then ("
340    xquery = xquery + " string(concat(string($DataCuratorRoleHolder/name/initials), ' ', string($DataCuratorRoleHolder/name/familyName)))"
341    xquery = xquery + " )"
342    xquery = xquery + " else "
343    xquery = xquery + " (string($DataCuratorRoleHolder/abbreviation))"
344    xquery = xquery + " },"
345    xquery = xquery + " element Long_Name "
346    xquery = xquery + " {"
347    xquery = xquery + " if (exists($DataCuratorRoleHolder/name/initials)) then "
348    xquery = xquery + " (string(concat(string($DataCuratorRoleHolder/name/initials), ' ', string($DataCuratorRoleHolder/name/familyName))))"
349    xquery = xquery + " else (string($DataCuratorRoleHolder/name))"
350    xquery = xquery + " }"
351    xquery = xquery + " },"
352    xquery = xquery + " if (exists($DataCuratorRoleHolder/contactDetails/URI)) then "
353    xquery = xquery + " ("
354    xquery = xquery + " element Data_Center_URL "
355    xquery = xquery + " {data($DataCuratorRoleHolder/contactDetails/URI)}"
356    xquery = xquery + " )"
357    xquery = xquery + " else (),"
358    xquery = xquery + " for $DGID in $DE/dgDataEntity/dgDataGranule/dataModelID"
359    xquery = xquery + " return "
360    xquery = xquery + " element Data_Set_ID "
361    xquery = xquery + " {"
362    xquery = xquery + " concat($DGID/repositoryIdentifier, ':', $DGID/schemeIdentifier, ':', $DGID/localIdentifier)"
363    xquery = xquery + " },"
364    xquery = xquery + " element Personnel"
365    xquery = xquery + " {"
366    xquery = xquery + " element Role {'Data Center Contact'},"
367    xquery = xquery + " if (exists($DataCuratorRoleHolder/name/knownAs)) then "
368    xquery = xquery + " (element First_Name {string($DataCuratorRoleHolder/name/knownAs)})"
369    xquery = xquery + " else if (exists($DataCuratorRoleHolder/name/initials)) then "
370    xquery = xquery + " (element First_Name {string($DataCuratorRoleHolder/name/initials)})"
371    xquery = xquery + " else (),"
372    xquery = xquery + " element Last_Name "
373    xquery = xquery + " {"
374    xquery = xquery + " if (exists($DataCuratorRoleHolder/name/familyName)) then "
375    xquery = xquery + " (string($DataCuratorRoleHolder/name/familyName))"
376    xquery = xquery + " else (string($DataCuratorRoleHolder/name))"
377    xquery = xquery + " },"
378    xquery = xquery + " if (exists($DataCuratorRole/contactDetails/eMail)) then "
379    xquery = xquery + " (element Email {string($DataCuratorRole/contactDetails/eMail)})"
380    xquery = xquery + " else "
381    xquery = xquery + " (if (exists($DataCuratorRoleHolder/contactDetails/eMail)) then "
382    xquery = xquery + " (element Email {string($DataCuratorRoleHolder/contactDetails/eMail)})"
383    xquery = xquery + " else ()"
384    xquery = xquery + " ),"
385    xquery = xquery + " if (exists($DataCuratorRole/contactDetails/telephone)) then "
386    xquery = xquery + " (element Phone {string($DataCuratorRole/contactDetails/telephone)})"
387    xquery = xquery + " else "
388    xquery = xquery + " (if (exists($DataCuratorRoleHolder/contactDetails/telephone)) then "
389    xquery = xquery + " (element Phone {string($DataCuratorRoleHolder/contactDetails/telephone)})"
390    xquery = xquery + " else ()"
391    xquery = xquery + " ),"
392    xquery = xquery + " if (exists($DataCuratorRole/contactDetails/fax)) then "
393    xquery = xquery + " (element Fax {string($DataCuratorRole/contactDetails/fax)})"
394    xquery = xquery + " else "
395    xquery = xquery + " (if (exists($DataCuratorRoleHolder/contactDetails/fax)) then "
396    xquery = xquery + " (element Fax {string($DataCuratorRoleHolder/contactDetails/fax)})"
397    xquery = xquery + " else ()"
398    xquery = xquery + " ),"
399    xquery = xquery + " if (exists($DataCuratorRole/contactDetails/address)) then "
400    xquery = xquery + " (element Contact_Address {"
401    xquery = xquery + " for $addressline in $DataCuratorRole/contactDetails/address/addressline"
402    xquery = xquery + " return element address {$addressline},"
403    xquery = xquery + " if (exists($DataCuratorRole/contactDetails/address/city)) then "
404    xquery = xquery + " (element City {string($DataCuratorRole/contactDetails/address/city)})"
405    xquery = xquery + " else (),"
406    xquery = xquery + " if (exists($DataCuratorRole/contactDetails/address/postcode)) then "
407    xquery = xquery + " (element Postal_Code {string($DataCuratorRole/contactDetails/address/postcode)})"
408    xquery = xquery + " else (),"
409    xquery = xquery + " if (exists($DataCuratorRole/contactDetails/address/country)) then "
410    xquery = xquery + " (element Country {string($DataCuratorRole/contactDetails/address/country)})"
411    xquery = xquery + " else ()"
412    xquery = xquery + " }"
413    xquery = xquery + " )"
414    xquery = xquery + " else if (exists($DataCuratorRoleHolder/contactDetails/address)) then "
415    xquery = xquery + " (element Contact_Address "
416    xquery = xquery + " {"
417    xquery = xquery + " for $addressline in $DataCuratorRole/contactDetails/address/addressline"
418    xquery = xquery + " return element address {$addressline},"
419    xquery = xquery + " if (exists($DataCuratorRole/contactDetails/address/city)) then "
420    xquery = xquery + " (element City {string($DataCuratorRoleHolder/contactDetails/address/city)})"
421    xquery = xquery + " else (),"
422    xquery = xquery + " if (exists($DataCuratorRoleHolder/contactDetails/address/postcode)) then "
423    xquery = xquery + " (element Postal_Code {string($DataCuratorRole/contactDetails/postcode)})"
424    xquery = xquery + " else (),"
425    xquery = xquery + " if (exists($DataCuratorRoleHolder/contactDetails/address/country)) then "
426    xquery = xquery + " (element Country {string($DataCuratorRoleHolder/contactDetails/address/country)})"
427    xquery = xquery + " else ()"
428    xquery = xquery + " }"
429    xquery = xquery + " )"
430    xquery = xquery + " else ()"
431    xquery = xquery + " }"
432    xquery = xquery + " },"
433    xquery = xquery + " element Summary {string($DE/dgMetadataDescription/abstract/abstractText)},"
434    xquery = xquery + " element Related_URL "
435    xquery = xquery + " {"
436    xquery = xquery + " element URL_Content_Type {'NDG_B_SERVICE'},"
437    xquery = xquery + " element URL {data($DE/dgMetadataID/repositoryIdentifier)},"
438    xquery = xquery + " element Description {'The NDG service for browsing metadata.'}"
439    xquery = xquery + " },"
440    xquery = xquery + " for $DG in $DE/dgDataEntity/dgDataGranule"
441    xquery = xquery + " return "
442    xquery = xquery + " if ($DG/dataModelID/schemeIdentifier='NDG-A0') then "
443    xquery = xquery + " ("
444    xquery = xquery + " element Related_URL "
445    xquery = xquery + " {"
446    xquery = xquery + " element URL_Content_Type {'NDG_A_SERVICE'},"
447    xquery = xquery + " element URL {escape-uri('http://dmgdev1.esc.rl.ac.uk/cgi-bin/ndgDataAccess?datasetSource=dmgdev1.esc.rl.ac.uk&amp;datasetID=', true())},"
448    xquery = xquery + " element Description {'The NDG service delivering data via NDG A metadata.'}"
449    xquery = xquery + " },"
450    xquery = xquery + " element Related_URL "
451    xquery = xquery + " {"
452    xquery = xquery + " element URL_Content_Type {'GET DATA > CSML'},"
453    xquery = xquery + " element URL {escape-uri('http://dmgdev1.esc.rl.ac.uk/cgi-bin/ndgDataAccess?datasetSource=dmgdev1.esc.rl.ac.uk&amp;datasetID=', true())},"
454    xquery = xquery + " element Description {'The NDG service delivering data via NDG A metadata. Additional tag to be more in line with latest version of GCMD valids'}"
455    xquery = xquery + " }"
456    xquery = xquery + " )"
457    xquery = xquery + " else if ($DG/dataModelID/schemeIdentifier='CDML-0') then "
458    xquery = xquery + " ("
459    xquery = xquery + " element Related_URL "
460    xquery = xquery + " {"
461    xquery = xquery + " element URL_Content_Type {'NDG_A_SERVICE'},"
462    xquery = xquery + " element URL {escape-uri('http://cdat.badc.nerc.ac.uk/cgi-bin/dxui.py?datasetURI_1=/', true())},"
463    xquery = xquery + " element Description {'The NDG service delivering data via Data extractor. Additional tag to be more in line with latest version of GCMD valids'}"
464    xquery = xquery + " },"
465    xquery = xquery + " element Related_URL "
466    xquery = xquery + " {"
467    xquery = xquery + " element URL_Content_Type {'GET DATA > DX'},"
468    xquery = xquery + " element URL {escape-uri('http://cdat.badc.nerc.ac.uk/cgi-bin/dxui.py?datasetURI_1=/', true())},"
469    xquery = xquery + " element Description {'The NDG service delivering data via Data extractor. Additional tag to be more in line with latest version of GCMD valids'}"
470    xquery = xquery + " }"
471    xquery = xquery + " )"
472    xquery = xquery + " else if ($DG/dataModelID/schemeIdentifier='URI') then "
473    xquery = xquery + " ("
474    xquery = xquery + " element Related_URL"
475    xquery = xquery + " {"
476    xquery = xquery + " element URL {data($DG/instance/URI)},"
477    xquery = xquery + " if (exists($DG/instance/instanceComment)) then "
478    xquery = xquery + " ("
479    xquery = xquery + " element Description {data($DG/instance/instanceComment)} "
480    xquery = xquery + " )"
481    xquery = xquery + " else "
482    xquery = xquery + " ("
483    xquery = xquery + " element Description {'URL to aid in delivering data. Note that this may point directly to the data or, more likely, point to the web site of the curators.'}"
484    xquery = xquery + " )"
485    xquery = xquery + " }"
486    xquery = xquery + " )"
487    xquery = xquery + " else (),"
488    xquery = xquery + " for $RelURL_Desc in ($DE/dgMetadataDescription/descriptionSection/descriptionOnlineReference) "
489    xquery = xquery + " return"
490    xquery = xquery + " element Related_URL"
491    xquery = xquery + " {"
492    xquery = xquery + " element URL {data($RelURL_Desc)},"
493    xquery = xquery + " element Description {concat(data($RelURL_Desc/name), ' - ', data($RelURL_Desc/notes))} "
494    xquery = xquery + " },"
495    xquery = xquery + " "
496    xquery = xquery + " element Metadata_Name {'[CEOS IDN DIF]'},"
497    xquery = xquery + " element Metadata_Version {'9.4'},"
498    xquery = xquery + " if (exists($DE/dgMetadataProvenance/RecordCreation)) then "
499    xquery = xquery + " ("
500    xquery = xquery + " element DIF_Creation_Date {data($DE/dgMetadataProvenance/RecordCreation/CreatedDate)}"
501    xquery = xquery + " )"
502    xquery = xquery + " else (),"
503    xquery = xquery + " for $MDUpdt in $DE/dgMetadataProvenance/RecordUpdate"
504    xquery = xquery + " return "
505    xquery = xquery + " element DIF_Revision_History {concat(data($MDUpdt/UpdateDate), ' - ', data($MDUpdt/UpdateSummary), ' - ', data($MDUpdt/UpdatedBy))}"
506    xquery = xquery + " ,"
507    xquery = xquery + " if (exists($DE/dgMetadataProvenance/RecordReview)) then "
508    xquery = xquery + " ("
509    xquery = xquery + " element Future_DIF_Review_Date {data($DE/dgMetadataProvenance/RecordReview/ReviewDate)}"
510    xquery = xquery + " )"
511    xquery = xquery + " else ()"
512    xquery = xquery + " }"
513    xquery = xquery + " </DIF>"
514    return xquery
515
516
517def XQueryISO19115(repositoryID, localID):
518    xquery = "for $DE in collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[dgDataEntity!='' and dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier="
519    xquery = xquery + "'" + repositoryID + "'"
520    xquery = xquery + " and dgMetadataID/localIdentifier="
521    xquery = xquery + "'" + localID + "'"
522    xquery = xquery + " ]"
523    xquery = xquery + " return "
524    xquery = xquery + "<MD_Metadata "
525    xquery = xquery + "  xmlns='http://www.isotc211.org/2005/gmd'"
526    xquery = xquery + "  xmlns:gco='http://www.isotc211.org/2005/gco'"
527    xquery = xquery + "  xmlns:gmd='http://www.isotc211.org/2005/gmd' "
528    xquery = xquery + "  xmlns:gml='http://www.opengis.net/gml'"
529    xquery = xquery + "  xmlns:xlink='http://www.w3.org/1999/xlink' "
530    xquery = xquery + "  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
531    xquery = xquery + "  xsi:schemaLocation='http://www.isotc211.org/2005/gmd http://www.isotc211.org/2005/gmd/metadataEntity.xsd'> {element fileIdentifier {element gco:CharacterString {concat($DE/dgMetadataID/repositoryIdentifier, ':ISO19115:', $DE/dgMetadataID/localIdentifier)}}}"
532    xquery = xquery + "  {element language {"
533    xquery = xquery + "  element gmd:LanguageCode {"
534    xquery = xquery + "  attribute codeList {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#LanguageCode'},"
535    xquery = xquery + "  attribute codeListValue {'eng'},"
536    xquery = xquery + "  'English'"
537    xquery = xquery + "  }"
538    xquery = xquery + "  }"
539    xquery = xquery + "  }"
540    xquery = xquery + "  "
541    xquery = xquery + "  {element hierarchyLevel {"
542    xquery = xquery + "  element MD_ScopeCode {"
543    xquery = xquery + "  attribute codeList {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_ScopeCode'},"
544    xquery = xquery + "  attribute codeListValue {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_ScopeCode_dataset'},"
545    xquery = xquery + "  'dataset'"
546    xquery = xquery + "  }"
547    xquery = xquery + "  }"
548    xquery = xquery + "  }"
549    xquery = xquery + "  {for $parent in $DE/dgRelatedDataEntity[RelationID/dgValidTerm='is-part-of']"
550    xquery = xquery + "  return "
551    xquery = xquery + "  element parentIdentifier {element gco:CharacterString {concat($DE/dgMetadataID/repositoryIdentifier, ':', $DE/dgMetadataID/localIdentifier, ':', $DE/dgMetadataID/localIdentifier)}}"
552    xquery = xquery + "  }"
553    xquery = xquery + "  {for $DataCuratorRole in $DE/dgDataEntity/dgDataRoles/dgDataCurator/dgRoleHolder[not(exists(endDate)) or endDate='']"
554    xquery = xquery + "  return "
555    xquery = xquery + "  for $DataCuratorRoleHolder in collection('/db/ndg_B_metadata')/dgMetadata/*[(dgMetadataID/schemeIdentifier='NDG-B0'"
556    xquery = xquery + "  and dgMetadataID/repositoryIdentifier=$DataCuratorRole/*/repositoryIdentifier"
557    xquery = xquery + "  and dgMetadataID/localIdentifier=$DataCuratorRole/*/localIdentifier)]"
558    xquery = xquery + "  return "
559    xquery = xquery + "  <contact >"
560    xquery = xquery + "  {"
561    xquery = xquery + "  <CI_ResponsibleParty> "
562    xquery = xquery + "  {"
563    xquery = xquery + "  if (string(local-name($DataCuratorRoleHolder))='dgOrganisation') then"
564    xquery = xquery + " element organisationName {element gco:CharacterString {string($DataCuratorRoleHolder/name)}}"
565    xquery = xquery + " else if (string(local-name($DataCuratorRoleHolder))='dgPerson') then"
566    xquery = xquery + " element individualName {element gco:CharacterString {string(concat(string($DataCuratorRoleHolder/name/initials), ' ', string($DataCuratorRoleHolder/name/familyName)))}}"
567    xquery = xquery + " else ('empty content')"
568    xquery = xquery + "  }"
569    xquery = xquery + "  {element positionName "
570    xquery = xquery + "  {"
571    xquery = xquery + "  if (exists($DataCuratorRoleHolder/localName)) then "
572    xquery = xquery + "  element gco:CharacterString {$DataCuratorRoleHolder/localName}"
573    xquery = xquery + "  else if (exists($DataCuratorRole/roleName)) then "
574    xquery = xquery + "  element gco:CharacterString {$DataCuratorRole/roleName}"
575    xquery = xquery + "  else "
576    xquery = xquery + "  element gco:CharacterString {'Curator'}"
577    xquery = xquery + "  }"
578    xquery = xquery + "  } "
579    xquery = xquery + "  <contactInfo>"
580    xquery = xquery + "  <gmd:CI_Contact> {if (exists($DataCuratorRole/contactDetails/telephone or $DataCuratorRole/contactDetails/fax or $DataCuratorRoleHolder/contactDetails/telephone or $DataCuratorRoleHolder/contactDetails/fax)) then"
581    xquery = xquery + "  <phone><gmd:CI_Telephone> "
582    xquery = xquery + "  {if (exists($DataCuratorRole/contactDetails/telephone)) then"
583    xquery = xquery + "  element voice {"
584    xquery = xquery + "  element gco:CharacterString {data($DataCuratorRole/contactDetails/telephone)}"
585    xquery = xquery + "  }"
586    xquery = xquery + "  else if (exists($DataCuratorRoleHolder/contactDetails/telephone)) then"
587    xquery = xquery + "  element voice {"
588    xquery = xquery + "  element gco:CharacterString {data($DataCuratorRoleHolder/contactDetails/telephone)}"
589    xquery = xquery + "  }"
590    xquery = xquery + "  else ()"
591    xquery = xquery + "  }"
592    xquery = xquery + "  {if (exists($DataCuratorRole/contactDetails/fax)) then"
593    xquery = xquery + "  element facsimile {"
594    xquery = xquery + "  element gco:CharacterString {data($DataCuratorRoleHolder/contactDetails/fax)}"
595    xquery = xquery + "  }"
596    xquery = xquery + "  else if (exists($DataCuratorRoleHolder/contactDetails/telephone)) then"
597    xquery = xquery + "  element facsimile {"
598    xquery = xquery + "  element gco:CharacterString {data($DataCuratorRoleHolder/contactDetails/fax)}"
599    xquery = xquery + "  }"
600    xquery = xquery + "  else ()"
601    xquery = xquery + "  }"
602    xquery = xquery + "  </gmd:CI_Telephone></phone> "
603    xquery = xquery + "  else ()"
604    xquery = xquery + "  } "
605    xquery = xquery + "  <address><gmd:CI_Address>"
606    xquery = xquery + "  {if (exists($DataCuratorRole/contactDetails/address/addressline)) then "
607    xquery = xquery + "  for $addressline in $DataCuratorRole/contactDetails/address/addressline"
608    xquery = xquery + "  return"
609    xquery = xquery + "  element deliveryPoint {"
610    xquery = xquery + "  element gco:CharacterString {data($addressline)}"
611    xquery = xquery + "  }"
612    xquery = xquery + "  else if (exists($DataCuratorRoleHolder/contactDetails/address/addressline)) then"
613    xquery = xquery + "  for $addressline in $DataCuratorRoleHolder/contactDetails/address/addressline"
614    xquery = xquery + "  return"
615    xquery = xquery + "  element deliveryPoint {"
616    xquery = xquery + "  element gco:CharacterString {data($addressline)}"
617    xquery = xquery + "  }"
618    xquery = xquery + "  else "
619    xquery = xquery + "  ()}"
620    xquery = xquery + "  {if (exists($DataCuratorRole/contactDetails/address/city)) then"
621    xquery = xquery + "  element city {"
622    xquery = xquery + "  element gco:CharacterString {data($DataCuratorRole/contactDetails/address/city)}"
623    xquery = xquery + "  }"
624    xquery = xquery + "  else if (exists($DataCuratorRoleHolder/contactDetails/address/city)) then"
625    xquery = xquery + "  element city {"
626    xquery = xquery + "  element gco:CharacterString {data($DataCuratorRoleHolder/contactDetails/address/city)}"
627    xquery = xquery + "  }"
628    xquery = xquery + "  else "
629    xquery = xquery + "  ()}"
630    xquery = xquery + "  {if (exists($DataCuratorRole/contactDetails/eMail)) then"
631    xquery = xquery + "  element electronicMailAddress {"
632    xquery = xquery + "  element gco:CharacterString {data($DataCuratorRole/contactDetails/eMail)}"
633    xquery = xquery + "  }"
634    xquery = xquery + "  else if (exists($DataCuratorRoleHolder/contactDetails/address/postcode)) then"
635    xquery = xquery + "  element electronicMailAddress {"
636    xquery = xquery + "  element gco:CharacterString {data($DataCuratorRoleHolder/contactDetails/eMail)}"
637    xquery = xquery + "  }"
638    xquery = xquery + "  else "
639    xquery = xquery + "  ()}"
640    xquery = xquery + "  </gmd:CI_Address></address>"
641    xquery = xquery + "  </gmd:CI_Contact>"
642    xquery = xquery + "  </contactInfo> {element role "
643    xquery = xquery + "  {"
644    xquery = xquery + "  element CI_RoleCode "
645    xquery = xquery + "  {"
646    xquery = xquery + "  attribute codeList {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_RoleCode'}, "
647    xquery = xquery + "  attribute codeListValue {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_RoleCode_custodian'},"
648    xquery = xquery + "  if (exists($DataCuratorRole/localName)) then "
649    xquery = xquery + "  data($DataCuratorRole/localName)"
650    xquery = xquery + "  else if (exists($DataCuratorRoleHolder/localName)) then"
651    xquery = xquery + "  data($DataCuratorRoleHolder/localName)"
652    xquery = xquery + "  else 'Curator' "
653    xquery = xquery + "  }"
654    xquery = xquery + "  }"
655    xquery = xquery + "  }"
656    xquery = xquery + "  </CI_ResponsibleParty>"
657    xquery = xquery + "  }"
658    xquery = xquery + "  </contact>"
659    xquery = xquery + "  }"
660    xquery = xquery + "  {element dateStamp "
661    xquery = xquery + "  {"
662    xquery = xquery + "  element gco:Date "
663    xquery = xquery + "  {"
664    xquery = xquery + "  adjust-date-to-timezone(current-date())"
665    xquery = xquery + "  }"
666    xquery = xquery + "  }"
667    xquery = xquery + "  }"
668    xquery = xquery + "  {element metadataStandardName {element gco:CharacterString {'ISO 19115:2005'}}}"
669    xquery = xquery + "  {element metadataStandardVersion {element gco:CharacterString {'2005'}}}"
670    xquery = xquery + "  <identificationInfo>"
671    xquery = xquery + "  <gmd:MD_DataIdentification>"
672    xquery = xquery + "  <citation>"
673    xquery = xquery + "  <gmd:CI_Citation>"
674    xquery = xquery + "  {element title {element gco:CharacterString {data($DE/name)}}}"
675    xquery = xquery + "  {if (exists($DE/abbreviation) and not(empty($DE/abbreviation))) then "
676    xquery = xquery + "  element alternateTitle {element gco:CharacterString {data($DE/abbreviation)}}"
677    xquery = xquery + "  else ()"
678    xquery = xquery + "  }"
679    xquery = xquery + "  {element date "
680    xquery = xquery + "  {"
681    xquery = xquery + "  if (exists($DE/*/RecordCreation/CreatedDate)) then"
682    xquery = xquery + "  element gmd:CI_Date "
683    xquery = xquery + "  {"
684    xquery = xquery + "  element date "
685    xquery = xquery + "  {"
686    xquery = xquery + "  element gco:Date {adjust-date-to-timezone(data($DE/*/RecordCreation/CreatedDate))}"
687    xquery = xquery + "  }, "
688    xquery = xquery + "  element dateType "
689    xquery = xquery + "  {"
690    xquery = xquery + "  element CI_DateTypeCode "
691    xquery = xquery + "  {"
692    xquery = xquery + "  attribute codeList {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_DateTypeCode'}, "
693    xquery = xquery + "  attribute codeListValue {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_DateTypeCode_creation' },"
694    xquery = xquery + "  'Creation'"
695    xquery = xquery + "  }"
696    xquery = xquery + "  }"
697    xquery = xquery + "  }"
698    xquery = xquery + "  else "
699    xquery = xquery + "  attribute gco:nilReason {'unknown'}"
700    xquery = xquery + "  }"
701    xquery = xquery + "  }"
702    xquery = xquery + "  </gmd:CI_Citation>"
703    xquery = xquery + "  </citation>"
704    xquery = xquery + "  {element abstract {"
705    xquery = xquery + "  element gco:CharacterString {data($DE/dgMetadataDescription/abstract/abstractText)}}"
706    xquery = xquery + "  } {element language "
707    xquery = xquery + "  {"
708    xquery = xquery + "  element gmd:LanguageCode "
709    xquery = xquery + "  {"
710    xquery = xquery + "  attribute codeList {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#LanguageCode'},"
711    xquery = xquery + "  attribute codeListValue {'eng'},"
712    xquery = xquery + "  'English'"
713    xquery = xquery + "  }"
714    xquery = xquery + "  }"
715    xquery = xquery + "  }"
716    xquery = xquery + "  {for $ISOTopicCategory in ($DE/dgStructuredKeyword[dgValidTermID/ParentListID='http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_TopicCategoryCode'])"
717    xquery = xquery + "  return "
718    xquery = xquery + "  element topicCategory "
719    xquery = xquery + "  {"
720    xquery = xquery + "  element gmd:MD_TopicCategoryCode "
721    xquery = xquery + "  {"
722    xquery = xquery + "  attribute codeList {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_TopicCategoryCode'},"
723    xquery = xquery + "  attribute codeListValue {string($ISOTopicCategory/dgValidTerm)},"
724    xquery = xquery + "  string($ISOTopicCategory/dgValidTerm)"
725    xquery = xquery + "  }"
726    xquery = xquery + "  }"
727    xquery = xquery + "  }"
728    xquery = xquery + "  </gmd:MD_DataIdentification>"
729    xquery = xquery + "  </identificationInfo></MD_Metadata>"
730
731    return xquery
732
733def XQueryNDGB0(repositoryID, localID):
734    xquery = xquery + " for $DE in collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[dgDataEntity!='' and dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier="
735    xquery = xquery + "'" + repositoryID + "'"
736    xquery = xquery + " and dgMetadataID/localIdentifier="
737    xquery = xquery + "'" + localID + "'"
738    xquery = xquery + " ]"
739    xquery = xquery + " return $DE"
740    return xquery
741
742def XQueryNDGB1(repositoryID, localID, existDB):
743    xquery = "for $Obj in collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier="
744    xquery = xquery + "'" + repositoryID + "' and dgMetadataID/localIdentifier="
745    xquery = xquery + "'" + localID + "']  return <objectType>{if (exists($Obj/dgDataEntity)) then 4 else (if (exists($Obj/dgObservationStation)) then 3 else (if (exists($Obj/dgDataProductionTool)) then 2 else (if (exists($Obj/dgActivity)) then 1 else (0))))}</objectType>"
746    # run type check
747    id = existDB.xmlrpc.executeQuery(xquery,{})
748    i=0
749    while i>=0:
750        try:
751            res = existDB.xmlrpc.retrieve(id, i, {})
752            i+=1
753        except xmlrpclib.Fault:
754            break
755        except Exception,e:
756            existDB.xmlrpc.releaseQueryResult(id)
757            raise e
758
759    # select correct xquery
760    if i==0:
761        xquery = "<dgMetadata/>"
762    elif i>1:
763        xquery = "<dgMetadata/>"
764    else:
765        if res.data == "<objectType>4</objectType>":
766            return XQueryNDGB1DE(repositoryID, localID)
767        if res.data == "<objectType>3</objectType>":
768            return XQueryNDGB1ObsStn(repositoryID, localID)
769        if res.data == "<objectType>2</objectType>":
770            return XQueryNDGB1DPT(repositoryID, localID)
771        if res.data == "<objectType>1</objectType>":
772            return XQueryNDGB1Act(repositoryID, localID)
773        else:
774            return "<dgMetadata/>"
775           
776    # clear query results
777    existDB.xmlrpc.releaseQueryResult(id)
778   
779    return xquery
780
781def XQueryNDGB1Act(repositoryID, localID):
782    xquery = " for $DE in collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[dgDataEntity!='' and dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier="
783    xquery = xquery + "'" + repositoryID + "'"
784    xquery = xquery + " and dgMetadataID/localIdentifier="
785    xquery = xquery + "'" + localID + "'"
786    xquery = xquery + " ]"
787    xquery = xquery + " return "
788    xquery = xquery + "<dgMetadataRecord>"
789    xquery = xquery + " <dgMetadataID>"
790    xquery = xquery + " <schemeIdentifier>NDG-B1</schemeIdentifier>"
791    xquery = xquery + " {$Act/dgMetadataID/repositoryIdentifier}"
792    xquery = xquery + " {$Act/dgMetadataID/localIdentifier}"
793    xquery = xquery + " </dgMetadataID>"
794    xquery = xquery + " {$Act/dgMetadataDescription}"
795    xquery = xquery + " {$Act/name}"
796    xquery = xquery + " {$Act/abbreviation}"
797    xquery = xquery + " <dgActivity>"
798    xquery = xquery + " {for $RelatedActivities in $Act/dgActivity/relatedActivity"
799    xquery = xquery + "  for $RelatedActivity in collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier=$RelatedActivities/relatedActivityID/repositoryIdentifier and dgMetadataID/localIdentifier=$RelatedActivities/relatedActivityID/localIdentifier]"
800    xquery = xquery + " return "
801    xquery = xquery + " <relatedActivity>"
802    xquery = xquery + " {$RelatedActivities/relatedActivityID}"
803    xquery = xquery + " {$RelatedActivity/name}"
804    xquery = xquery + " {$RelatedActivity/abbreviation}"
805    xquery = xquery + " {$RelatedActivities/activityRelation}"
806    xquery = xquery + " </relatedActivity>"
807    xquery = xquery + " }"
808    xquery = xquery + " {$Act/dgActivityDataCollection}"
809    xquery = xquery + " {$Act/dgActivityDataProject}"
810    xquery = xquery + " {$Act/dgActivityDataCollection}"
811    xquery = xquery + " {$Act/dgActivityDataInvestigation}"
812    xquery = xquery + " <dgActivityRole>"
813    xquery = xquery + " <dgInvestigator>"
814    xquery = xquery + " <dgPrincipalInvestigator>"
815    xquery = xquery + " {$Act/dgActivity/dgActivityRole/dgInvestigator/dgPrincipalInvestigator/dgMetadataID}"
816    xquery = xquery + " {$Act/dgActivity/dgActivityRole/dgInvestigator/dgPrincipalInvestigator/roleName}"
817    xquery = xquery + " {$Act/dgActivity/dgActivityRole/dgInvestigator/dgPrincipalInvestigator/abbreviation}"
818    xquery = xquery + " {$Act/dgActivity/dgActivityRole/dgInvestigator/dgPrincipalInvestigator/contactDetails}"
819    xquery = xquery + " {for $PIRole in $Act/dgActivity/dgActivityRole/dgInvestigator/dgPrincipalInvestigator/dgRoleHolder "
820    xquery = xquery + " order by $PIRole/startDate empty least, $PIRole/endDate empty least"
821    xquery = xquery + " return "
822    xquery = xquery + " <dgRoleHolder>"
823    xquery = xquery + " {if (exists($PIRole/dgOrganisationID)) then ("
824    xquery = xquery + " for $PIRoleHolder in collection('/db/ndg_B_metadata')/dgMetadata/dgOrganisation[dgMetadataID[schemeIdentifier='NDG-B0' and repositoryIdentifier=$PIRole/dgOrganisationID/repositoryIdentifier and localIdentifier=$PIRole/dgOrganisationID/localIdentifier]]"
825    xquery = xquery + " return $PIRoleHolder)"
826    xquery = xquery + "  else ()"
827    xquery = xquery + " }"
828    xquery = xquery + " {if (exists($PIRole/dgPersonID)) then ("
829    xquery = xquery + " for $PIRoleHolder in collection('/db/ndg_B_metadata')/dgMetadata/dgPerson[dgMetadataID[schemeIdentifier='NDG-B0' and repositoryIdentifier=$PIRole/dgPersonID/repositoryIdentifier and localIdentifier=$PIRole/dgPersonID/localIdentifier]]"
830    xquery = xquery + " return $PIRoleHolder)"
831    xquery = xquery + "  else ()"
832    xquery = xquery + " }"
833    xquery = xquery + " {$PIRole/startDate}"
834    xquery = xquery + " {$PIRole/endDate}"
835    xquery = xquery + " {$PIRole/localName}"
836    xquery = xquery + " </dgRoleHolder>"
837    xquery = xquery + " }"
838    xquery = xquery + " </dgPrincipalInvestigator>"
839    xquery = xquery + " {for $CI in $Act/dgActivity/dgActivityRole/dgInvestigator/dgCoInvestigator "
840    xquery = xquery + " return  "
841    xquery = xquery + " <dgCoInvestigator>"
842    xquery = xquery + " {$CI/dgMetadataID}"
843    xquery = xquery + " {$CI/roleName}"
844    xquery = xquery + " {$CI/abbreviation}"
845    xquery = xquery + " {$CI/contactDetails}"
846    xquery = xquery + " {for $CIRole in $CI/dgRoleHolder "
847    xquery = xquery + " order by $CIRole/startDate empty least, $CIRole/endDate empty least"
848    xquery = xquery + " return "
849    xquery = xquery + " <dgRoleHolder>"
850    xquery = xquery + " {if (exists($CIRole/dgOrganisationID)) then ("
851    xquery = xquery + " for $CIRoleHolder in collection('/db/ndg_B_metadata')/dgMetadata/dgOrganisation[dgMetadataID[schemeIdentifier='NDG-B0' and repositoryIdentifier=$CIRole/dgOrganisationID/repositoryIdentifier and localIdentifier=$CIRole/dgOrganisationID/localIdentifier]]"
852    xquery = xquery + " return $CIRoleHolder)"
853    xquery = xquery + "  else ()"
854    xquery = xquery + " }"
855    xquery = xquery + " {if (exists($CIRole/dgPersonID)) then ("
856    xquery = xquery + " for $CIRoleHolder in collection('/db/ndg_B_metadata')/dgMetadata/dgPerson[dgMetadataID[schemeIdentifier='NDG-B0' and repositoryIdentifier=$CIRole/dgPersonID/repositoryIdentifier and localIdentifier=$CIRole/dgPersonID/localIdentifier]]"
857    xquery = xquery + " return $CIRoleHolder)"
858    xquery = xquery + "  else ()"
859    xquery = xquery + " }"
860    xquery = xquery + " {$CIRole/startDate}"
861    xquery = xquery + " {$CIRole/endDate}"
862    xquery = xquery + " {$CIRole/localName}"
863    xquery = xquery + " </dgRoleHolder>"
864    xquery = xquery + " }"
865    xquery = xquery + " </dgCoInvestigator>"
866    xquery = xquery + " }"
867    xquery = xquery + " </dgInvestigator>"
868    xquery = xquery + " {if (exists($Act/dgActivity/dgActivityRole/dgTechnicalContact)) then ("
869    xquery = xquery + " <dgTechnicalContact>"
870    xquery = xquery + " {$Act/dgActivity/dgActivityRole/dgTechnicalContact/dgMetadataID}"
871    xquery = xquery + " {$Act/dgActivity/dgActivityRole/dgTechnicalContact/roleName}"
872    xquery = xquery + " {$Act/dgActivity/dgActivityRole/dgTechnicalContact/abbreviation}"
873    xquery = xquery + " {$Act/dgActivity/dgActivityRole/dgTechnicalContact/contactDetails}"
874    xquery = xquery + " {for $TechConRole in $Act/dgActivity/dgActivityRole/dgTechnicalContact/dgRoleHolder "
875    xquery = xquery + " order by $TechConRole/startDate empty least, $TechConRole/endDate empty least"
876    xquery = xquery + " return "
877    xquery = xquery + " <dgRoleHolder>"
878    xquery = xquery + " {for $TechConRoleHolder in collection('/db/ndg_B_metadata')/dgMetadata/(dgOrganisation | dgPerson)[(dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier=$TechConRole/*/repositoryIdentifier and dgMetadataID/localIdentifier=$TechConRole/*/localIdentifier)] return $TechConRoleHolder}"
879    xquery = xquery + " {$TechConRole/startDate}"
880    xquery = xquery + " {$TechConRole/endDate}"
881    xquery = xquery + " {$TechConRole/localName}"
882    xquery = xquery + " </dgRoleHolder>}"
883    xquery = xquery + " </dgTechnicalContact>"
884    xquery = xquery + " )"
885    xquery = xquery + " else ()"
886    xquery = xquery + " }"
887    xquery = xquery + " {if (exists($Act/dgActivity/dgActivityRole/dgProjectManager)) then ("
888    xquery = xquery + " <dgProjectManager>"
889    xquery = xquery + " {$Act/dgActivity/dgActivityRole/dgProjectManager/dgMetadataID}"
890    xquery = xquery + " {$Act/dgActivity/dgActivityRole/dgProjectManager/roleName}"
891    xquery = xquery + " {$Act/dgActivity/dgActivityRole/dgProjectManager/abbreviation}"
892    xquery = xquery + " {$Act/dgActivity/dgActivityRole/dgProjectManager/contactDetails}"
893    xquery = xquery + " {for $PMRole in $Act/dgActivity/dgActivityRole/dgProjectManager/dgRoleHolder "
894    xquery = xquery + " order by $PMRole/startDate empty least, $PMRole/endDate empty least"
895    xquery = xquery + " return "
896    xquery = xquery + " <dgRoleHolder>"
897    xquery = xquery + " {for $PMRoleHolder in collection('/db/ndg_B_metadata')/dgMetadata/(dgOrganisation | dgPerson)[(dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier=$PMRole/*/repositoryIdentifier and dgMetadataID/localIdentifier=$PMRole/*/localIdentifier)] return $PMRoleHolder}"
898    xquery = xquery + " {$PMRole/startDate}"
899    xquery = xquery + " {$PMRole/endDate}"
900    xquery = xquery + " {$PMRole/localName}"
901    xquery = xquery + " </dgRoleHolder>}"
902    xquery = xquery + " </dgProjectManager>"
903    xquery = xquery + " )"
904    xquery = xquery + " else ()"
905    xquery = xquery + " }"
906    xquery = xquery + " </dgActivityRole>"
907    xquery = xquery + " {for $RelDep in $Act/dgActivity/ActivityDeployment"
908    xquery = xquery + " return"
909    xquery = xquery + " <ActivityDeployment>"
910    xquery = xquery + " {$RelDep/DateStart}"
911    xquery = xquery + " {$RelDep/DateEnd}"
912    xquery = xquery + " {$RelDep/dgMetadataID}"
913    xquery = xquery + " {for $SRDPT in collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[(dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier=$RelDep/DataProductionToolID/repositoryIdentifier and dgMetadataID/localIdentifier=$RelDep/DataProductionToolID/localIdentifier)]"
914    xquery = xquery + " return"
915    xquery = xquery + " <dataproductiontool>"
916    xquery = xquery + " {$SRDPT/dgMetadataID}"
917    xquery = xquery + " {$SRDPT/dgMetadataDescription}"
918    xquery = xquery + " {$SRDPT/name}"
919    xquery = xquery + " {$SRDPT/abbreviation}"
920    xquery = xquery + " <dgDataProductionTool>"
921    xquery = xquery + " {$SRDPT/dgDataProductionTool/contactDetails}"
922    xquery = xquery + " {$SRDPT/dgDataProductionTool/dgModel}"
923    xquery = xquery + " {$SRDPT/dgDataProductionTool/dgInstrument}"
924    xquery = xquery + " </dgDataProductionTool>"
925    xquery = xquery + " </dataproductiontool>"
926    xquery = xquery + " }"
927    xquery = xquery + " {for $SRObsStn in collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[(dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier=$RelDep/ObservationStationID/repositoryIdentifier and dgMetadataID/localIdentifier=$RelDep/ObservationStationID/localIdentifier)]"
928    xquery = xquery + " return"
929    xquery = xquery + " <observationstation>"
930    xquery = xquery + " {$SRObsStn/dgMetadataID}"
931    xquery = xquery + " {$SRObsStn/dgMetadataDescription}"
932    xquery = xquery + " {$SRObsStn/name}"
933    xquery = xquery + " {$SRObsStn/abbreviation}"
934    xquery = xquery + " <dgObservationStation>"
935    xquery = xquery + " {$SRObsStn/dgObservationStation/contactDetails}"
936    xquery = xquery + " {$SRObsStn/dgObservationStation/dgStationaryPlatform}"
937    xquery = xquery + " {$SRObsStn/dgObservationStation/dgMovingPlatform}"
938    xquery = xquery + " </dgObservationStation>"
939    xquery = xquery + " </observationstation>"
940    xquery = xquery + " }"
941    xquery = xquery + " {for $DE in collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[dgMetadataID/schemeIdentifier='NDG-B0' and dgDataEntity/RelatedDeployment/dgMetadataID/repositoryIdentifier=$RelDep/dgMetadataID/repositoryIdentifier and dgDataEntity/RelatedDeployment/dgMetadataID/localIdentifier=$RelDep/dgMetadataID/localIdentifier]return"
942    xquery = xquery + " <dataEntity>"
943    xquery = xquery + " {$DE/dgMetadataID}"
944    xquery = xquery + " {$DE/dgMetadataDescription}"
945    xquery = xquery + " {$DE/name}"
946    xquery = xquery + " {$DE/abbreviation}"
947    xquery = xquery + " <dgDataEntity>"
948    xquery = xquery + " {$DE/dgDataEntity/dgDataSetType}"
949    xquery = xquery + " {$DE/dgDataEntity/dgDataObjectType}"
950    xquery = xquery + " {$DE/dgDataEntity/dgDataGranule}"
951    xquery = xquery + " {$DE/dgDataEntity/dgDataSummary}"
952    xquery = xquery + " </dgDataEntity>"
953    xquery = xquery + " </dataEntity>"
954    xquery = xquery + " }"
955    xquery = xquery + " </ActivityDeployment>"
956    xquery = xquery + " }"
957    xquery = xquery + " {$Act/dgActivityCoverage}"
958    xquery = xquery + " {$Act/ActivityDuration}"
959    xquery = xquery + " </dgActivity>"
960    xquery = xquery + " {$Act/dgStructuredKeyword}"
961    xquery = xquery + " {$Act/DataProvenance}"
962    xquery = xquery + " {$Act/MetadataSecurity}"
963    xquery = xquery + " </dgMetadataRecord>"
964    return xquery
965
966def XQueryNDGB1DPT(repositoryID, localID):
967    xquery = " for $DE in collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[dgDataEntity!='' and dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier="
968    xquery = xquery + "'" + repositoryID + "'"
969    xquery = xquery + " and dgMetadataID/localIdentifier="
970    xquery = xquery + "'" + localID + "'"
971    xquery = xquery + " ]"
972    xquery = xquery + " return "
973    xquery = xquery + "<dgMetadataRecord> "
974    xquery = xquery + " {$DPT/dgMetadataID}"
975    xquery = xquery + " <dgMetadataID>"
976    xquery = xquery + " <schemeIdentifier>NDG-B1</schemeIdentifier> "
977    xquery = xquery + " {$DPT/dgMetadataID/repositoryIdentifier}"
978    xquery = xquery + " {$DPT/dgMetadataID/localIdentifier}"
979    xquery = xquery + " </dgMetadataID> "
980    xquery = xquery + " {$DPT/dgMetadataDescription}"
981    xquery = xquery + " {$DPT/name}"
982    xquery = xquery + " {$DPT/abbreviation}"
983    xquery = xquery + " <dgDataProductionTool> "
984    xquery = xquery + " {$DPT/contactDetails}"
985    xquery = xquery + " {if (exists($DPT/dgModel)) then ("
986    xquery = xquery + "  <dgModel/>"
987    xquery = xquery + "     ) "
988    xquery = xquery + " else ($DPT/dgInstrument) "
989    xquery = xquery + " }"
990    xquery = xquery + " {if (exists($DPT/dgDPTRoles)) then ("
991    xquery = xquery + "  <dgDPTRoles>Roles are available, and will be added soon</dgDPTRoles> "
992    xquery = xquery + " ) else() }"
993    xquery = xquery + " {for $RelDep in $DPT/dgDataProductionTool/DPTDeployment "
994    xquery = xquery + " return "
995    xquery = xquery + " <DPTDeployment> "
996    xquery = xquery + " {$RelDep/DateStart}"
997    xquery = xquery + " {$RelDep/DateEnd}"
998    xquery = xquery + " {$RelDep/dgMetadataID}"
999    xquery = xquery + " {for $SRAct in collection('/db/ndg_B_metadata')/*/dgMetadataRecord[(dgMetadataID/repositoryIdentifier=$RelDep/ActivityID/repositoryIdentifier and dgMetadataID/localIdentifier=$RelDep/ActivityID/localIdentifier)] "
1000    xquery = xquery + " return "
1001    xquery = xquery + " <activity> "
1002    xquery = xquery + " {$SRAct/dgMetadataID}"
1003    xquery = xquery + " {$SRAct/dgMetadataDescription}"
1004    xquery = xquery + " {$SRAct/name}{$SRAct/abbreviation}"
1005    xquery = xquery + " <dgActivity>"
1006    xquery = xquery + " {$SRAct/*/dgActivityDataCollection}"
1007    xquery = xquery + " {$SRAct/*/dgActivityDataProject}"
1008    xquery = xquery + " {$SRAct/*/dgActivityDataCampaign}"
1009    xquery = xquery + " {$SRAct/*/dgActivityDataInvestigation}"
1010    xquery = xquery + " {$SRAct/*/dgActivityCoverage}"
1011    xquery = xquery + " {$SRAct/*/dgActivityDuration}"
1012    xquery = xquery + " </dgActivity> "
1013    xquery = xquery + " </activity> "
1014    xquery = xquery + " }"
1015    xquery = xquery + " {for $SRObsStn in collection('/db/ndg_B_metadata')/*/dgMetadataRecord[(dgMetadataID/repositoryIdentifier=$RelDep/ObservationStationID/repositoryIdentifier and dgMetadataID/localIdentifier=$RelDep/ObservationStationID/localIdentifier)] "
1016    xquery = xquery + " return "
1017    xquery = xquery + " <observationstation> "
1018    xquery = xquery + " {$SRObsStn/dgMetadataID}"
1019    xquery = xquery + " {$SRObsStn/dgMetadataDescription}"
1020    xquery = xquery + " {$SRObsStn/name}"
1021    xquery = xquery + " {$SRObsStn/abbreviation}"
1022    xquery = xquery + " <dgObservationStation> "
1023    xquery = xquery + " {$SRObsStn/dgObservationStation/contactDetails}"
1024    xquery = xquery + " {$SRObsStn/dgObservationStation/dgStationaryPlatform}"
1025    xquery = xquery + " {$SRObsStn/dgObservationStation/dgMovingPlatform}"
1026    xquery = xquery + " </dgObservationStation> "
1027    xquery = xquery + " </observationstation> }"
1028    xquery = xquery + " {for $DE in collection('/db/ndg_B_metadata')/*/dgMetadataRecord[dgDataEntity/RelatedDeployment/dgMetadataID/repositoryIdentifier=$RelDep/dgMetadataID/repositoryIdentifier and dgDataEntity/RelatedDeployment/dgMetadataID/localIdentifier=$RelDep/dgMetadataID/localIdentifier] "
1029    xquery = xquery + " return "
1030    xquery = xquery + " <dataEntity> "
1031    xquery = xquery + " {$DE/dgMetadataID}"
1032    xquery = xquery + " {$DE/dgMetadataDescription}"
1033    xquery = xquery + " {$DE/name}"
1034    xquery = xquery + " {$DE/abbreviation}"
1035    xquery = xquery + " <dgDataEntity> "
1036    xquery = xquery + " {$DE/dgDataEntity/dgDataSetType}"
1037    xquery = xquery + " {$DE/dgDataEntity/dgDataObjectType}"
1038    xquery = xquery + " {$DE/dgDataEntity/dgDataGranule}"
1039    xquery = xquery + " {$DE/dgDataEntity/dgDataSummary}"
1040    xquery = xquery + " <dgDataRoles> "
1041    xquery = xquery + " <dgDataCurator> "
1042    xquery = xquery + " {$DE/dgDataEntity/dgDataRoles/dgDataCurator/dgMetadataID}"
1043    xquery = xquery + " {$DE/dgDataEntity/dgDataRoles/dgDataCurator/roleName}"
1044    xquery = xquery + " {$DE/dgDataEntity/dgDataRoles/dgDataCurator/abbreviation}"
1045    xquery = xquery + " {$DE/dgDataEntity/dgDataRoles/dgDataCurator/contactDetails}"
1046    xquery = xquery + " {for $DataCuratorRole in $DE/dgDataEntity/dgDataRoles/dgDataCurator/dgRoleHolder  "
1047    xquery = xquery + " order by $DataCuratorRole/startDate empty least, $DataCuratorRole/endDate empty least "
1048    xquery = xquery + " return  "
1049    xquery = xquery + " <dgRoleHolder> "
1050    xquery = xquery + " {for $DataCuratorRoleHolder in collection('/db/ndg_B_metadata')/*/(dgOrganisation | dgPerson)[(dgMetadataID/repositoryIdentifier=$DataCuratorRole/*/repositoryIdentifier and dgMetadataID/localIdentifier=$DataCuratorRole/*/localIdentifier)] "
1051    xquery = xquery + " return $DataCuratorRoleHolder}"
1052    xquery = xquery + " {$DataCuratorRole/startDate}"
1053    xquery = xquery + " {$DataCuratorRole/endDate}"
1054    xquery = xquery + " {$DataCuratorRole/localName}"
1055    xquery = xquery + " </dgRoleHolder>}"
1056    xquery = xquery + " </dgDataCurator> "
1057    xquery = xquery + " </dgDataRoles> "
1058    xquery = xquery + " </dgDataEntity> "
1059    xquery = xquery + " </dataEntity> "
1060    xquery = xquery + " }"
1061    xquery = xquery + " </DPTDeployment> "
1062    xquery = xquery + " }"
1063    xquery = xquery + " </dgDataProductionTool> "
1064    xquery = xquery + " {$DPT/dgStructuredKeyword}"
1065    xquery = xquery + " {$DPT/DataProvenance}"
1066    xquery = xquery + " {$DPT/MetadataSecurity}"
1067    xquery = xquery + " </dgMetadataRecord>"
1068    return xquery
1069
1070def XQueryNDGB1ObsStn(repositoryID, localID):
1071    xquery = " for $DE in collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[dgDataEntity!='' and dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier="
1072    xquery = xquery + "'" + repositoryID + "'"
1073    xquery = xquery + " and dgMetadataID/localIdentifier="
1074    xquery = xquery + "'" + localID + "'"
1075    xquery = xquery + " ]"
1076    xquery = xquery + " return "
1077    xquery = xquery + " <dgMetadataRecord>"
1078    xquery = xquery + " <dgMetadataID>"
1079    xquery = xquery + " <schemeIdentifier>NDG-B1</schemeIdentifier> "
1080    xquery = xquery + " {$ObsStn/dgMetadataID/repositoryIdentifier}"
1081    xquery = xquery + " {$ObsStn/dgMetadataID/localIdentifier}"
1082    xquery = xquery + " </dgMetadataID> "
1083    xquery = xquery + " {$ObsStn/dgMetadataDescription}"
1084    xquery = xquery + " {$ObsStn/name}"
1085    xquery = xquery + " {$ObsStn/abbreviation}"
1086    xquery = xquery + " <dgObservationStation> "
1087    xquery = xquery + " {$ObsStn/dgObservationStation/contactDetails}"
1088    xquery = xquery + " {if (exists($ObsStn/dgObservationStation/dgStationaryPlatform)) then ("
1089    xquery = xquery + " <dgStationaryPlatform> "
1090    xquery = xquery + " {$ObsStn/dgObservationStation/dgStationaryPlatform/position}"
1091    xquery = xquery + " {if (exists($ObsStn/dgObservationStation/dgStationaryPlatform/dgMooring)) then  ( "
1092    xquery = xquery + " <dgMooring> "
1093    xquery = xquery + " {$ObsStn/dgObservationStation/dgStationaryPlatform/dgMooring/dateStart}"
1094    xquery = xquery + " {$ObsStn/dgObservationStation/dgStationaryPlatform/dgMooring/dateEnd}"
1095    xquery = xquery + " {for $DepositingCruise in collection('/db/ndg_B_metadata')/*/dgMetadataRecord[(dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier=$ObsStn/dgObservationStation/dgStationaryPlatform/dgMooring/DepositingCruise/repositoryIdentifier and dgMetadataID/localIdentifier=$ObsStn/dgObservationStation/dgStationaryPlatform/dgMooring/DepositingCruise/localIdentifier)] "
1096    xquery = xquery + " return "
1097    xquery = xquery + " <depositingcruise> "
1098    xquery = xquery + " {$DepositingCruise/dgMetadataID}"
1099    xquery = xquery + " {$DepositingCruise/name}"
1100    xquery = xquery + " {$DepositingCruise/abbreviation}"
1101    xquery = xquery + " {$DepositingCruise/dgMetadataDescription}"
1102    xquery = xquery + " </depositingcruise> "
1103    xquery = xquery + " }"
1104    xquery = xquery + " {if (exists($ObsStn/dgObservationStation/dgStationaryPlatform/dgMooring/dgStationGrouping)) then  ( "
1105    xquery = xquery + " for $StationGrouping in collection('/db/ndg_B_metadata')/*/dgMetadataRecord[(dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier=$ObsStn/dgObservationStation/dgStationaryPlatform/dgMooring/DepositingCruise/repositoryIdentifier and dgMetadataID/localIdentifier=$ObsStn/dgObservationStation/dgStationaryPlatform/dgMooring/DepositingCruise/localIdentifier)] "
1106    xquery = xquery + " return  "
1107    xquery = xquery + " <dgStationGrouping> "
1108    xquery = xquery + " {$StationGrouping/dgMetadataID}"
1109    xquery = xquery + " {$StationGrouping/name}"
1110    xquery = xquery + " {$StationGrouping/abbreviation}"
1111    xquery = xquery + " {$StationGrouping/dgMetadataDescription}"
1112    xquery = xquery + " {$StationGrouping/dgObservationStation/dgStationaryPlatform/position}"
1113    xquery = xquery + " </dgStationGrouping> ) "
1114    xquery = xquery + " else ()}"
1115    xquery = xquery + " </dgMooring>) "
1116    xquery = xquery + " else if (exists($ObsStn/dgObservationStation/dgStationaryPlatform/dgMooring)) then  ( "
1117    xquery = xquery + " <dgStationGroup> "
1118    xquery = xquery + " {$ObsStn/dgObservationStation/dgStationaryPlatform/dgMooring/dateStart}"
1119    xquery = xquery + " {$ObsStn/dgObservationStation/dgStationaryPlatform/dgMooring/dateEnd}"
1120    xquery = xquery + " <dgGroupedStations> "
1121    xquery = xquery + " {for $GroupedStations in collection('/db/ndg_B_metadata')/*/dgMetadataRecord[(dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier=$ObsStn/dgObservationStation/dgStationaryPlatform/dgStationGroup/dgGroupedStations/dgGroupedStation/repositoryIdentifier and dgMetadataID/localIdentifier=$ObsStn/dgObservationStation/dgStationaryPlatform/dgStationGroup/dgGroupedStations/dgGroupedStation/localIdentifier)] "
1122    xquery = xquery + " return "
1123    xquery = xquery + " <dgGroupedStation> "
1124    xquery = xquery + " {$GroupedStations/dgMetadataID}"
1125    xquery = xquery + " {$GroupedStations/name}"
1126    xquery = xquery + " {$GroupedStations/abbreviation}"
1127    xquery = xquery + " {$GroupedStations/dgMetadataDescription}"
1128    xquery = xquery + " {$GroupedStations/dgObservationStation/dgStationaryPlatform/position}"
1129    xquery = xquery + " </dgGroupedStation> }"
1130    xquery = xquery + " </dgGroupedStations>"
1131    xquery = xquery + " </dgStationGroup> ) "
1132    xquery = xquery + " else ($ObsStn/dgObservationStation/dgLandStation) "
1133    xquery = xquery + " }"
1134    xquery = xquery + " </dgStationaryPlatform> ) "
1135    xquery = xquery + " else ($ObsStn/dgObservationStation/dgMovingPlatform) "
1136    xquery = xquery + " }"
1137    xquery = xquery + " {for $RelDep in $ObsStn/*/ObsStationDeployment "
1138    xquery = xquery + " return "
1139    xquery = xquery + " <ObsStationDeployment> "
1140    xquery = xquery + " {$RelDep/DateStart}"
1141    xquery = xquery + " {$RelDep/DateEnd}"
1142    xquery = xquery + " {$RelDep/dgMetadataID}"
1143    xquery = xquery + " {for $SRAct in collection('/db/ndg_B_metadata')/*/dgMetadataRecord[(dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier=$RelDep/ActivityID/repositoryIdentifier and dgMetadataID/localIdentifier=$RelDep/ActivityID/localIdentifier)] "
1144    xquery = xquery + " return "
1145    xquery = xquery + " <activity> "
1146    xquery = xquery + " {$SRAct/dgMetadataID}"
1147    xquery = xquery + " {$SRAct/dgMetadataDescription}"
1148    xquery = xquery + " {$SRAct/name}"
1149    xquery = xquery + " {$SRAct/abbreviation}"
1150    xquery = xquery + " <dgActivity> "
1151    xquery = xquery + " {$SRAct/*/dgActivityDataCollection}"
1152    xquery = xquery + " {$SRAct/*/dgActivityDataProject}"
1153    xquery = xquery + " {$SRAct/*/dgActivityDataCampaign}"
1154    xquery = xquery + " {$SRAct/*/dgActivityDataInvestigation}"
1155    xquery = xquery + " {$SRAct/*/dgActivityCoverage}"
1156    xquery = xquery + " {$SRAct/*/dgActivityDuration}"
1157    xquery = xquery + " </dgActivity>"
1158    xquery = xquery + " </activity> "
1159    xquery = xquery + " }"
1160    xquery = xquery + " {for $SRDPT in collection('/db/ndg_B_metadata')/*/dgMetadataRecord[(dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier=$RelDep/DataProductionToolID/repositoryIdentifier and dgMetadataID/localIdentifier=$RelDep/DataProductionToolID/localIdentifier)] "
1161    xquery = xquery + " return "
1162    xquery = xquery + " <dataproductiontool> "
1163    xquery = xquery + " {$SRDPT/dgMetadataID}"
1164    xquery = xquery + " {$SRDPT/dgMetadataDescription}"
1165    xquery = xquery + " {$SRDPT/name}"
1166    xquery = xquery + " {$SRDPT/abbreviation}"
1167    xquery = xquery + " <dgDataProductionTool> "
1168    xquery = xquery + " {$SRDPT/dgDataProductionTool/contactDetails}"
1169    xquery = xquery + " {$SRDPT/dgDataProductionTool/dgModel}"
1170    xquery = xquery + " {$SRDPT/dgDataProductionTool/dgInstrument}"
1171    xquery = xquery + " </dgDataProductionTool>"
1172    xquery = xquery + " </dataproductiontool>}"
1173    xquery = xquery + " {for $DE in collection('/db/ndg_B_metadata')/*/dgMetadataRecord[dgMetadataID/schemeIdentifier='NDG-B0' and dgDataEntity/RelatedDeployment/dgMetadataID/repositoryIdentifier=$RelDep/dgMetadataID/repositoryIdentifier and dgDataEntity/RelatedDeployment/dgMetadataID/localIdentifier=$RelDep/dgMetadataID/localIdentifier] "
1174    xquery = xquery + " return "
1175    xquery = xquery + " <dataEntity> "
1176    xquery = xquery + " {$DE/dgMetadataID}"
1177    xquery = xquery + " {$DE/dgMetadataDescription}"
1178    xquery = xquery + " {$DE/name}"
1179    xquery = xquery + " {$DE/abbreviation}"
1180    xquery = xquery + " <dgDataEntity> "
1181    xquery = xquery + " {$DE/dgDataEntity/dgDataSetType}"
1182    xquery = xquery + " {$DE/dgDataEntity/dgDataObjectType}"
1183    xquery = xquery + " {$DE/dgDataEntity/dgDataGranule}"
1184    xquery = xquery + " {$DE/dgDataEntity/dgDataSummary}"
1185    xquery = xquery + " <dgDataRoles>"
1186    xquery = xquery + " <dgDataCurator> "
1187    xquery = xquery + " {$DE/dgDataEntity/dgDataRoles/dgDataCurator/dgMetadataID}"
1188    xquery = xquery + " {$DE/dgDataEntity/dgDataRoles/dgDataCurator/roleName}"
1189    xquery = xquery + " {$DE/dgDataEntity/dgDataRoles/dgDataCurator/abbreviation}"
1190    xquery = xquery + " {$DE/dgDataEntity/dgDataRoles/dgDataCurator/contactDetails}"
1191    xquery = xquery + " {for $DataCuratorRole in $DE/dgDataEntity/dgDataRoles/dgDataCurator/dgRoleHolder  "
1192    xquery = xquery + " order by $DataCuratorRole/startDate empty least, $DataCuratorRole/endDate empty least "
1193    xquery = xquery + " return  "
1194    xquery = xquery + " <dgRoleHolder> "
1195    xquery = xquery + " {for $DataCuratorRoleHolder in collection('/db/ndg_B_metadata')/*/(dgOrganisation | dgPerson)[(dgMetadataID/repositoryIdentifier=$DataCuratorRole/*/repositoryIdentifier and dgMetadataID/localIdentifier=$DataCuratorRole/*/localIdentifier)] "
1196    xquery = xquery + " return "
1197    xquery = xquery + " $DataCuratorRoleHolder}"
1198    xquery = xquery + " {$DataCuratorRole/startDate}"
1199    xquery = xquery + " {$DataCuratorRole/endDate}"
1200    xquery = xquery + " {$DataCuratorRole/localName}"
1201    xquery = xquery + " </dgRoleHolder>"
1202    xquery = xquery + " }"
1203    xquery = xquery + " </dgDataCurator>"
1204    xquery = xquery + " </dgDataRoles>"
1205    xquery = xquery + " </dgDataEntity>"
1206    xquery = xquery + " </dataEntity> "
1207    xquery = xquery + " }"
1208    xquery = xquery + " </ObsStationDeployment> "
1209    xquery = xquery + " }"
1210    xquery = xquery + " </dgObservationStation> "
1211    xquery = xquery + " {$ObsStn/dgStructuredKeyword}"
1212    xquery = xquery + " {$ObsStn/DataProvenance}"
1213    xquery = xquery + " {$ObsStn/MetadataSecurity}"
1214    xquery = xquery + " </dgMetadataRecord>"
1215    return xquery
1216
1217def XQueryNDGB1DE(repositoryID, localID):
1218    xquery = " for $DE in collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[dgDataEntity!='' and dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier="
1219    xquery = xquery + "'" + repositoryID + "'"
1220    xquery = xquery + " and dgMetadataID/localIdentifier="
1221    xquery = xquery + "'" + localID + "'"
1222    xquery = xquery + " ]"
1223    xquery = xquery + " return "
1224    xquery = xquery + "<dgMetadataRecord>"
1225    xquery = xquery + " <dgMetadataID>"
1226    xquery = xquery + " <schemeIdentifier>NDG-B1</schemeIdentifier>"
1227    xquery = xquery + " {$DE/dgMetadataID/repositoryIdentifier}"
1228    xquery = xquery + " {$DE/dgMetadataID/localIdentifier}"
1229    xquery = xquery + " </dgMetadataID>"
1230    xquery = xquery + " {$DE/dgMetadataDescription}"
1231    xquery = xquery + " {$DE/name}"
1232    xquery = xquery + " {$DE/abbreviation}"
1233    xquery = xquery + " <dgDataEntity>"
1234    xquery = xquery + " {$DE/dgDataEntity/dgDataSetType}"
1235    xquery = xquery + " {$DE/dgDataEntity/dgDataObjectType}"
1236    xquery = xquery + " {$DE/dgDataEntity/dgDataGranule}"
1237    xquery = xquery + " {$DE/dgDataEntity/dgDataSummary}"
1238    xquery = xquery + " <dgDataRoles>"
1239    xquery = xquery + " {if (exists($DE/dgDataEntity/dgDataRoles/dgDataCreator/dgMetadataID)) then ("
1240    xquery = xquery + " <dgDataCreator>"
1241    xquery = xquery + " {$DE/dgDataEntity/dgDataRoles/dgDataCreator/dgMetadataID}"
1242    xquery = xquery + " {$DE/dgDataEntity/dgDataRoles/dgDataCreator/roleName}"
1243    xquery = xquery + " {$DE/dgDataEntity/dgDataRoles/dgDataCreator/abbreviation}"
1244    xquery = xquery + " {$DE/dgDataEntity/dgDataRoles/dgDataCreator/contactDetails}"
1245    xquery = xquery + " {for $DataCreatorRole in $DE/dgDataEntity/dgDataRoles/dgDataCreator/dgRoleHolder "
1246    xquery = xquery + " order by $DataCreatorRole/startDate empty least, $DataCreatorRole/endDate empty least"
1247    xquery = xquery + " return "
1248    xquery = xquery + " <dgRoleHolder>"
1249    xquery = xquery + " {if (exists($DataCreatorRole/dgOrganisationID)) then ("
1250    xquery = xquery + " for $DataCreatorRoleHolder in collection('/db/ndg_B_metadata')/dgMetadata/dgOrganisation[dgMetadataID[schemeIdentifier='NDG-B0' and repositoryIdentifier=$DataCreatorRole/dgOrganisationID/repositoryIdentifier and localIdentifier=$DataCreatorRole/dgOrganisationID/localIdentifier]]"
1251    xquery = xquery + " return $DataCreatorRoleHolder)"
1252    xquery = xquery + "  else ()"
1253    xquery = xquery + " }"
1254    xquery = xquery + " {if (exists($DataCreatorRole/dgPersonID)) then ("
1255    xquery = xquery + " for $DataCreatorRoleHolder in collection('/db/ndg_B_metadata')/dgMetadata/dgPerson[dgMetadataID[schemeIdentifier='NDG-B0' and repositoryIdentifier=$DataCreatorRole/dgPersonID/repositoryIdentifier and localIdentifier=$DataCreatorRole/dgPersonID/localIdentifier]]"
1256    xquery = xquery + " return $DataCreatorRoleHolder)"
1257    xquery = xquery + "  else ()"
1258    xquery = xquery + " }"
1259    xquery = xquery + " {$DataCreatorRole/startDate}"
1260    xquery = xquery + " {$DataCreatorRole/endDate}"
1261    xquery = xquery + " {$DataCreatorRole/localName}"
1262    xquery = xquery + " </dgRoleHolder>"
1263    xquery = xquery + " }"
1264    xquery = xquery + " </dgDataCreator>)"
1265    xquery = xquery + " else ()}"
1266    xquery = xquery + " {if (exists($DE/dgDataEntity/dgDataRoles/dgDataCurator/dgMetadataID)) then ("
1267    xquery = xquery + " <dgDataCurator>"
1268    xquery = xquery + " {$DE/dgDataEntity/dgDataRoles/dgDataCurator/dgMetadataID}"
1269    xquery = xquery + " {$DE/dgDataEntity/dgDataRoles/dgDataCurator/roleName}"
1270    xquery = xquery + " {$DE/dgDataEntity/dgDataRoles/dgDataCurator/abbreviation}"
1271    xquery = xquery + " {$DE/dgDataEntity/dgDataRoles/dgDataCurator/contactDetails}"
1272    xquery = xquery + " {for $DataCuratorRole in $DE/dgDataEntity/dgDataRoles/dgDataCurator/dgRoleHolder "
1273    xquery = xquery + " order by $DataCuratorRole/startDate empty least, $DataCuratorRole/endDate empty least"
1274    xquery = xquery + " return "
1275    xquery = xquery + " <dgRoleHolder>"
1276    xquery = xquery + " {if (exists($DataCuratorRole/dgOrganisationID)) then ("
1277    xquery = xquery + " for $DataCuratorRoleHolder in collection('/db/ndg_B_metadata')/dgMetadata/dgOrganisation[dgMetadataID[schemeIdentifier='NDG-B0' and repositoryIdentifier=$DataCuratorRole/dgOrganisationID/repositoryIdentifier and localIdentifier=$DataCuratorRole/dgOrganisationID/localIdentifier]]"
1278    xquery = xquery + " return $DataCuratorRoleHolder)"
1279    xquery = xquery + "  else ()"
1280    xquery = xquery + " }"
1281    xquery = xquery + " {if (exists($DataCuratorRole/dgPersonID)) then ("
1282    xquery = xquery + " for $DataCuratorRoleHolder in collection('/db/ndg_B_metadata')/dgMetadata/dgPerson[dgMetadataID[schemeIdentifier='NDG-B0' and repositoryIdentifier=$DataCuratorRole/dgPersonID/repositoryIdentifier and localIdentifier=$DataCuratorRole/dgPersonID/localIdentifier]]"
1283    xquery = xquery + " return $DataCuratorRoleHolder)"
1284    xquery = xquery + "  else ()"
1285    xquery = xquery + " }"
1286    xquery = xquery + " {$DataCuratorRole/startDate}"
1287    xquery = xquery + " {$DataCuratorRole/endDate}"
1288    xquery = xquery + " {$DataCuratorRole/localName}"
1289    xquery = xquery + " </dgRoleHolder>}"
1290    xquery = xquery + " </dgDataCurator>)"
1291    xquery = xquery + " else ()}"
1292    xquery = xquery + " "
1293    xquery = xquery + " {if (exists($DE/dgDataEntity/dgDataRoles/dgDataOtherRoles/dgMetadataID)) then ("
1294    xquery = xquery + " <dgDataOtherRoles>"
1295    xquery = xquery + " {$DE/dgDataEntity/dgDataRoles/dgDataOtherRoles/dgMetadataID}"
1296    xquery = xquery + " {$DE/dgDataEntity/dgDataRoles/dgDataOtherRoles/roleName}"
1297    xquery = xquery + " {$DE/dgDataEntity/dgDataRoles/dgDataOtherRoles/abbreviation}"
1298    xquery = xquery + " {$DE/dgDataEntity/dgDataRoles/dgDataOtherRoles/contactDetails}"
1299    xquery = xquery + " {for $DataOtherRolesRole in $DE/dgDataEntity/dgDataRoles/dgDataOtherRoles/dgRoleHolder "
1300    xquery = xquery + " order by $DataOtherRolesRole/startDate empty least, $DataOtherRolesRole/endDate empty least"
1301    xquery = xquery + " return"
1302    xquery = xquery + " <dgRoleHolder>"
1303    xquery = xquery + " {if (exists($DataOtherRolesRole/dgOrganisationID)) then ("
1304    xquery = xquery + " for $DataOtherRolesRoleHolder in /dgMetadata/dgOrganisation[dgMetadataID[schemeIdentifier='NDG-B0' and repositoryIdentifier=$DataOtherRolesRole/dgOrganisationID/repositoryIdentifier and localIdentifier=$DataOtherRolesRole/dgOrganisationID/localIdentifier]]"
1305    xquery = xquery + " return $DataOtherRolesRoleHolder)"
1306    xquery = xquery + "  else ()"
1307    xquery = xquery + " }"
1308    xquery = xquery + " {if (exists($DataOtherRolesRole/dgPersonID)) then ("
1309    xquery = xquery + " for $DataOtherRolesRoleHolder in /dgMetadata/dgPerson[dgMetadataID[schemeIdentifier='NDG-B0' and repositoryIdentifier=$DataOtherRolesRole/dgPersonID/repositoryIdentifier and localIdentifier=$DataOtherRolesRole/dgPersonID/localIdentifier]]"
1310    xquery = xquery + " return $DataOtherRolesRoleHolder)"
1311    xquery = xquery + "  else ()"
1312    xquery = xquery + " }"
1313    xquery = xquery + " {$DataOtherRolesRole/startDate}"
1314    xquery = xquery + " {$DataOtherRolesRole/endDate}"
1315    xquery = xquery + " {$DataOtherRolesRole/localName}"
1316    xquery = xquery + " </dgRoleHolder>}"
1317    xquery = xquery + " </dgDataOtherRoles>)"
1318    xquery = xquery + " else ()}"
1319    xquery = xquery + " "
1320    xquery = xquery + " </dgDataRoles>"
1321    xquery = xquery + " {for $RelDep in $DE/dgDataEntity/RelatedDeployment"
1322    xquery = xquery + " return"
1323    xquery = xquery + " <RelatedDeployment>"
1324    xquery = xquery + " {$RelDep/DateStart}"
1325    xquery = xquery + " {$RelDep/DateEnd}"
1326    xquery = xquery + " {$RelDep/dgMetadataID}"
1327    xquery = xquery + " {for $SRAct in collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[dgMetadataID[schemeIdentifier='NDG-B0' and repositoryIdentifier=$RelDep/ActivityID/repositoryIdentifier and localIdentifier=$RelDep/ActivityID/localIdentifier]]"
1328    xquery = xquery + " return"
1329    xquery = xquery + " <activity>"
1330    xquery = xquery + " {$SRAct/dgMetadataID}"
1331    xquery = xquery + " {$SRAct/dgMetadataDescription}"
1332    xquery = xquery + " {$SRAct/name}"
1333    xquery = xquery + " {$SRAct/abbreviation}"
1334    xquery = xquery + " <dgActivity>"
1335    xquery = xquery + " {$SRAct/dgActivity/dgActivityDataCollection}"
1336    xquery = xquery + " {$SRAct/dgActivity/dgActivityDataProject}"
1337    xquery = xquery + " {$SRAct/dgActivity/dgActivityDataCampaign}"
1338    xquery = xquery + " {$SRAct/dgActivity/dgActivityDataInvestigation}"
1339    xquery = xquery + " {$SRAct/dgActivity/dgActivityCoverage}"
1340    xquery = xquery + " {$SRAct/dgActivity/dgActivityDuration}"
1341    xquery = xquery + " </dgActivity>"
1342    xquery = xquery + " </activity>"
1343    xquery = xquery + " }"
1344    xquery = xquery + " {for $SRDPT in collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[dgMetadataID[schemeIdentifier='NDG-B0' and repositoryIdentifier=$RelDep/DataProductionToolID/repositoryIdentifier and localIdentifier=$RelDep/DataProductionToolID/localIdentifier]]"
1345    xquery = xquery + " return"
1346    xquery = xquery + " <dataproductiontool>"
1347    xquery = xquery + " {$SRDPT/dgMetadataID}"
1348    xquery = xquery + " {$SRDPT/dgMetadataDescription}"
1349    xquery = xquery + " {$SRDPT/name}"
1350    xquery = xquery + " {$SRDPT/abbreviation}"
1351    xquery = xquery + " <dgDataProductionTool>"
1352    xquery = xquery + " {$SRDPT/dgDataProductionTool/contactDetails}"
1353    xquery = xquery + " {$SRDPT/dgDataProductionTool/dgModel}"
1354    xquery = xquery + " {$SRDPT/dgDataProductionTool/dgInstrument}"
1355    xquery = xquery + " </dgDataProductionTool>"
1356    xquery = xquery + " </dataproductiontool>"
1357    xquery = xquery + " }"
1358    xquery = xquery + " {for $SRObsStn in collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[dgMetadataID[schemeIdentifier='NDG-B0' and repositoryIdentifier=$RelDep/ObservationStationID/repositoryIdentifier and localIdentifier=$RelDep/ObservationStationID/localIdentifier]]"
1359    xquery = xquery + " return"
1360    xquery = xquery + " <observationstation>"
1361    xquery = xquery + " {$SRObsStn/dgMetadataID}"
1362    xquery = xquery + " {$SRObsStn/dgMetadataDescription}"
1363    xquery = xquery + " {$SRObsStn/name}{$SRObsStn/abbreviation}"
1364    xquery = xquery + " <dgObservationStation>"
1365    xquery = xquery + " {$SRObsStn/dgObservationStation/contactDetails}"
1366    xquery = xquery + " {$SRObsStn/dgObservationStation/dgStationaryPlatform}"
1367    xquery = xquery + " {$SRObsStn/dgObservationStation/dgMovingPlatform}"
1368    xquery = xquery + " </dgObservationStation>"
1369    xquery = xquery + " </observationstation>"
1370    xquery = xquery + " }"
1371    xquery = xquery + " {$RelDep/Coverage}"
1372    xquery = xquery + " </RelatedDeployment>"
1373    xquery = xquery + " }"
1374    xquery = xquery + " {for $RelatedDataGranule in collection('/db/ndg_B_metadata')/dgMetadata/dgMetadataRecord[dgMetadataID[schemeIdentifier='NDG-B0' and repositoryIdentifier=$DE/dgRelatedDataGranuleID/dgRelatedDataGranuleID/repositoryIdentifier and localIdentifier=$DE/dgRelatedDataGranuleID/RelatedDataGranuleID/localIdentifier]]"
1375    xquery = xquery + " return"
1376    xquery = xquery + " <relateddatagranule>"
1377    xquery = xquery + " <relation>"
1378    xquery = xquery + " {$RelatedDataGranule/RelationID/dgValidTerm}"
1379    xquery = xquery + " {$RelatedDataGranule/RelationID/dgValidTermID}"
1380    xquery = xquery + " </relation>"
1381    xquery = xquery + " {$RelatedDataGranule/dgMetadataID}"
1382    xquery = xquery + " {$RelatedDataGranule/dgMetadataDescription}"
1383    xquery = xquery + " {$RelatedDataGranule/name}"
1384    xquery = xquery + " {$RelatedDataGranule/abbreviation}"
1385    xquery = xquery + " <dgDataEntity>"
1386    xquery = xquery + " {$RelatedDataGranule/dgDataEntity/dgDataSetType}"
1387    xquery = xquery + " {$RelatedDataGranule/dgDataEntity/dgDataObjectType}"
1388    xquery = xquery + " {$DE/dgDataEntity/dgDataGranule}"
1389    xquery = xquery + " {$DE/dgDataEntity/dgDataSummary}"
1390    xquery = xquery + " </dgDataEntity>"
1391    xquery = xquery + " </relateddatagranule>"
1392    xquery = xquery + " }"
1393    xquery = xquery + " </dgDataEntity>"
1394    xquery = xquery + " {$DE/dgStructuredKeyword}"
1395    xquery = xquery + " {$DE/DataProvenance}"
1396    xquery = xquery + " {$DE/MetadataSecurity}"
1397    xquery = xquery + " </dgMetadataRecord>"
1398    xquery = xquery + " "
1399    xquery = xquery + "     "
1400    return xquery
1401
1402def getMOLESbyID(repositoryID, localID, format, user='guest', userpw='guest', repository='localhost', portNumber=8080):
1403
1404    eXistConstants = InstanceObject(host=repository,
1405                                userid=user,
1406                                password=userpw,
1407                                base_path="/exist/servlet",
1408                                xmlrpc_base_path="/exist/xmlrpc",
1409                                port=portNumber)   
1410    existDB=eXist_Connector(constants=eXistConstants)
1411    if format == 'DC':
1412        xquery = XQueryDC(repositoryID, localID)
1413    elif format == 'ISO19115':
1414        xquery = XQueryISO19115(repositoryID, localID)
1415    elif format == 'NDG-B1':
1416        xquery = XQueryNDGB1(repositoryID=repositoryID, localID=localID, existDB=existDB)
1417    elif format == 'DIF':
1418        xquery = XQueryDIF(repositoryID=repositoryID, localID=localID)
1419    else:
1420        xquery = "<dgMetaData/>"
1421    id = existDB.xmlrpc.executeQuery(xquery,{})
1422    i=0
1423    while i>=0:
1424        try:
1425            res = existDB.xmlrpc.retrieve(id, i, {})
1426            i+=1
1427        except xmlrpclib.Fault:
1428            break
1429        except Exception,e:
1430            existDB.xmlrpc.releaseQueryResult(id)
1431            raise e
1432
1433    if i==0:
1434        system.exit(10)
1435    elif i>1:
1436        system.exit(11)
1437    else:
1438        print res.data
1439       
1440    existDB.xmlrpc.releaseQueryResult(id)
1441
Note: See TracBrowser for help on using the repository browser.