source: TI07-MOLES/trunk/PythonCode/wsgi/ndg_xqueries.py @ 2553

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI07-MOLES/trunk/PythonCode/wsgi/ndg_xqueries.py@2553
Revision 2553, 93.6 KB checked in by ko23, 12 years ago (diff)

Update of ndg_xqueries.py to include time-out capability

Line 
1# This version using xqueries from rev 1914 of
2# TI07-MOLES/trunk/JavaCode/returnmolesxmldb/ndg/services/returnmoles/Main.java
3# Update DIF/DC queries
4listingQuery='''
5declare default element namespace 'http://ndg.nerc.ac.uk/moles';for $DE
6in
7collection('TargetCollection')/dgMetadata/dgMetadataRecord[exists(dgDataEntity)] return
8<dgMetadataRecord>{$DE/dgMetadataID/repositoryIdentifier}
9{$DE/dgMetadataID/localIdentifier}<fileName>{util:document-name($DE)}</fileName></dgMetadataRecord>
10'''
11
12ObjectTypeQuery = '''declare default element namespace 'http://ndg.nerc.ac.uk/moles';declare variable $targetCollection as xs:string {'TargetCollection'};for $Obj in collection($targetCollection)/dgMetadata/dgMetadataRecord[dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier='RepositoryID' and dgMetadataID/localIdentifier='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>'''
13
14StubBDEQuery = '''declare default element namespace 'http://ndg.nerc.ac.uk/moles/dataentity';
15declare namespace f='http://ndg.nerc.ac.uk/moles/localfunctions';
16declare namespace moles='http://ndg.nerc.ac.uk/moles';
17declare option exist:timeout '24500';
18import module namespace voclib='http://ndg.nerc.ac.uk/xquery/lib/vocab' at 'xmldb:exist:///db/xqueryLib/Vocabs/vocab_xquery_lib.xquery';
19import module namespace utillib='http://ndg.nerc.ac.uk/xquery/lib/utilities' at 'xmldb:exist:///db/xqueryLib/Utilities/utility_xquery_lib.xquery';
20(:
21Will return when scope problem sussed... ;(
22import module namespace stubblib='http://ndg.nerc.ac.uk/xquery/lib/stubb' at 'xmldb:exist:///db/xqueryLib/StubB/stubb_xquery_lib.xquery';
23:)
24declare variable $targetCollection as xs:string {'TargetCollection'};
25declare variable $repositoryIdentifier as xs:string {'RepositoryID'};
26declare variable $localIdentifier as xs:string {'LocalID'};
27
28declare function f:return-stub-activity($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
29(: Returns a 'stubB' style activity record to expand an activity record :)
30(: Security not implemented here yet :)
31{
32let $SRAct := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
33moles:dgMetadataID/moles:localIdentifier=$locid
34and moles:dgMetadataID/moles:repositoryIdentifier=$repid ]
35return
36element  {$out-element-name} {
37($SRAct/moles:dgMetadataID),
38($SRAct/moles:name),
39($SRAct/moles:abbreviation),
40($SRAct/moles:logos),
41element dgActivity {
42} (: </dgActivity> :)
43} (: </activity> :)
44} ;
45
46declare function f:return-stub-dataentity($out-element-name as xs:string, $DE as element()) as element()
47(: Returns a 'stubB' style observation station record to expand an data entity record :)
48(: Security not implemented yet :)
49{
50let $SRDE := $DE
51return 
52element {$out-element-name} {
53($SRDE/moles:dgMetadataID),
54($SRDE/moles:name),
55($SRDE/moles:abbreviation),
56element dgDataEntity {
57} (: </dgDataEntity> :)       
58}
59} ;
60
61declare function f:return-stub-dpt($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
62(: Returns a 'stubB' style dpt record to expand a dpt record :)
63(: Security not implemented yet :)
64{
65let $SRDPT := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
66moles:dgMetadataID/moles:localIdentifier=$locid
67and
68moles:dgMetadataID/moles:repositoryIdentifier=$repid
69]
70return 
71element {$out-element-name} {
72$SRDPT/moles:dgMetadataID,
73$SRDPT/moles:name,
74$SRDPT/moles:abbreviation,
75$SRDPT/moles:logos,
76element dgDataProductionTool {
77} (: </dgDataProductionTool> :)
78} (: </dataproductiontool> :)
79} ;
80
81declare function f:return-stub-obsstn($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
82(: Returns a 'stubB' style observation station record to expand an observation station record :)
83(: Security not implemented here yet;  :)
84{
85let $SRObsStn := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
86moles:dgMetadataID/moles:localIdentifier=$locid
87and
88moles:dgMetadataID/moles:repositoryIdentifier=$repid
89]
90return
91element {$out-element-name} {
92($SRObsStn/moles:dgMetadataID),
93($SRObsStn/moles:name),
94($SRObsStn/moles:abbreviation),
95($SRObsStn/moles:logos),
96element dgObservationStation {
97} (: </dgObservationStation> :)
98}
99} ;
100
101declare function f:return-stub-person($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
102(: Returns a 'stubB' style observation station record to expand a person record :)
103(: Security not implemented yet :)
104{
105let $person := collection($targetCollection)/moles:dgMetadata/moles:dgPerson[
106moles:dgMetadataID/moles:localIdentifier=$locid
107and
108moles:dgMetadataID/moles:repositoryIdentifier=$repid
109]
110return
111element  {$out-element-name}
112{
113($person/moles:name),
114($person/moles:contactDetails),
115($person/moles:dgMetadataID)
116}
117} ;
118
119declare function f:return-stub-organisation($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
120(: Returns a 'stubB' style observation station record to expand an organisation record :)
121(: Security not implemented yet :)
122{
123let $org := collection($targetCollection)/moles:dgMetadata/moles:dgOrganisation[
124moles:dgMetadataID/moles:localIdentifier=$locid
125and
126moles:dgMetadataID/moles:repositoryIdentifier=$repid
127]
128return
129element  {$out-element-name} {
130$org/moles:dgMetadataID,
131$org/moles:name,
132$org/moles:abbreviation,
133$org/moles:contactDetails,
134$org/moles:logos
135}
136} ;
137
138for $DE in collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
139exists(moles:dgDataEntity)
140and moles:dgMetadataID[
141moles:schemeIdentifier='NDG-B0'
142and moles:repositoryIdentifier=$repositoryIdentifier
143and moles:localIdentifier=$localIdentifier]]
144return
145utillib:strip-namespace(element dgMetadataRecord {
146    element dgMetadataID {
147        element schemeIdentifier {'NDG-B1'},
148        $DE/moles:dgMetadataID/moles:repositoryIdentifier,
149        $DE/moles:dgMetadataID/moles:localIdentifier
150    }, (: </dgMetadataID> :)
151    $DE/moles:dgMetadataDescription,
152    $DE/moles:name,
153    $DE/moles:abbreviation,
154    element dgDataEntity {
155        $DE/moles:dgDataEntity/moles:dgDataSetType,
156        $DE/moles:dgDataEntity/moles:dgDataObjectType,
157        $DE/moles:dgDataEntity/moles:dgDataGranule,
158        $DE/moles:dgDataEntity/moles:dgDataSummary,
159        element dgDataRoles {
160            if (exists($DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:dgMetadataID)) then
161                element dgDataCreator {
162                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:dgMetadataID,
163                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:roleName,
164                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:abbreviation,
165                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:contactDetails,
166                for $DataCreatorRole in $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:dgRoleHolder
167                    order by $DataCreatorRole/moles:startDate empty least, $DataCreatorRole/moles:endDate empty least
168                    return
169                        element dgRoleHolder {
170                            if (exists($DataCreatorRole/moles:dgOrganisationID)) then
171                                f:return-stub-organisation('organisation', data($DataCreatorRole/moles:dgOrganisationID/moles:repositoryIdentifier), data($DataCreatorRole/moles:dgOrganisationID/moles:localIdentifier))
172                             else if (exists($DataCreatorRole/moles:dgPersonID)) then
173                                f:return-stub-person('person', string($DataCreatorRole/moles:dgPersonID/moles:repositoryIdentifier), string($DataCreatorRole/moles:dgPersonID/moles:localIdentifier))
174                             else (),
175                            $DataCreatorRole/moles:startDate,
176                            $DataCreatorRole/moles:endDate,
177                            $DataCreatorRole/moles:localName
178                        } (: </dgRoleHolder> :)
179                    } (: </dgDataCreator>) :)
180            else (),
181            if (exists($DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCurator/moles:dgMetadataID)) then
182                element dgDataCurator {
183                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCurator/moles:dgMetadataID,
184                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCurator/moles:roleName,
185                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCurator/moles:abbreviation,
186                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCurator/moles:contactDetails,
187                for $DataCuratorRole in $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCurator/moles:dgRoleHolder
188                    order by $DataCuratorRole/moles:startDate empty least, $DataCuratorRole/moles:endDate empty least
189                    return
190                        element dgRoleHolder {
191                            if (exists($DataCuratorRole/moles:dgOrganisationID)) then
192                                f:return-stub-organisation('organisation', data($DataCuratorRole/moles:dgOrganisationID/moles:repositoryIdentifier), data($DataCuratorRole/moles:dgOrganisationID/moles:localIdentifier))
193                             else if (exists($DataCuratorRole/moles:dgPersonID)) then
194                                f:return-stub-person('person', string($DataCuratorRole/moles:dgPersonID/moles:repositoryIdentifier), string($DataCuratorRole/moles:dgPersonID/moles:localIdentifier))
195                             else (),
196                            $DataCuratorRole/moles:startDate,
197                            $DataCuratorRole/moles:endDate,
198                            $DataCuratorRole/moles:localName
199                        } (: </dgRoleHolder> :)
200            } (: </dgDataCurator> :)
201            else (),
202            if (exists($DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataOtherRoles/moles:dgMetadataID)) then
203                element dgDataOtherRoles {
204                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataOtherRoles/moles:dgMetadataID,
205                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataOtherRoles/moles:roleName,
206                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataOtherRoles/moles:abbreviation,
207                $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataOtherRoles/moles:contactDetails,
208                for $DataOtherRolesRole in $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataOtherRoles/moles:dgRoleHolder
209                    order by $DataOtherRolesRole/moles:startDate empty least, $DataOtherRolesRole/moles:endDate empty least
210                    return
211                        element dgRoleHolder {
212                            if (exists($DataOtherRolesRole/moles:dgOrganisationID)) then
213                                f:return-stub-organisation('organisation', data($DataOtherRolesRole/moles:dgOrganisationID/moles:repositoryIdentifier), data($DataOtherRolesRole/moles:dgOrganisationID/moles:localIdentifier))
214                             else if (exists($DataOtherRolesRole/moles:dgPersonID)) then
215                                f:return-stub-person('person', string($DataOtherRolesRole/moles:dgPersonID/moles:repositoryIdentifier), string($DataOtherRolesRole/moles:dgPersonID/moles:localIdentifier))
216                             else (),
217                            $DataOtherRolesRole/moles:startDate,
218                            $DataOtherRolesRole/moles:endDate,
219                            $DataOtherRolesRole/moles:localName
220                        } (: </dgRoleHolder> :)
221            } (: </dgDataOtherRoles> :)
222            else ()
223        } , (: </dgDataRoles> :)
224        for $RelDep in $DE/moles:dgDataEntity/moles:RelatedDeployment
225            return
226            element RelatedDeployment {
227            $RelDep/moles:DateStart,
228            $RelDep/moles:DateEnd,
229            $RelDep/moles:dgMetadataID,
230            f:return-stub-activity('activity', data($RelDep/moles:ActivityID/moles:repositoryIdentifier), data($RelDep/moles:ActivityID/moles:localIdentifier)),
231            f:return-stub-dpt('dataproductiontool', data($RelDep/moles:DataProductionToolID/moles:repositoryIdentifier), data($RelDep/moles:DataProductionToolID/moles:localIdentifier)),
232            f:return-stub-obsstn('observationstation', data($RelDep/moles:ObservationStationID/moles:repositoryIdentifier), data($RelDep/moles:ObservationStationID/moles:localIdentifier)),
233            $RelDep/moles:Coverage
234        } (: </RelatedDeployment> :)
235        ,
236        for $RelatedDataEntity in $DE/moles:dgDataEntity/moles:dgRelatedDataEntity
237            return
238                element relateddataentity {
239                element relation {
240                    $RelatedDataEntity/moles:RelationID/moles:dgValidTerm,
241                    $RelatedDataEntity/moles:RelationID/moles:dgValidTermID
242                }, (: </relation> :)
243                let $DE := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[moles:dgDataEntity/moles:RelatedDeployment/moles:dgMetadataID/moles:repositoryIdentifier=$RelatedDataEntity/moles:RelatedDataEntityID/moles:repositoryIdentifier
244                      and moles:dgDataEntity/moles:RelatedDeployment/moles:dgMetadataID/moles:localIdentifier=$RelatedDataEntity/moles:RelatedDataEntityID/moles:localIdentifier]
245                 return
246                    f:return-stub-dataentity('dataentity', $DE)
247                }
248} (: </dgDataEntity> :),
249    for $strkwrd in $DE/moles:dgStructuredKeyword return $strkwrd,
250    if (exists($DE/moles:dgMetadataProvenance)) then $DE/moles:dgMetadataProvenance else (),
251    if (exists($DE/moles:dgMetadataSecurity)) then $DE/moles:dgMetadataSecurity else ()
252} (: </dgMetadataRecord> :)
253) (: end of namespace strip :)
254'''
255
256StubBActQuery = '''
257declare default element namespace 'http://ndg.nerc.ac.uk/moles/activity';
258declare namespace f='http://ndg.nerc.ac.uk/moles/localfunctions';
259declare namespace moles='http://ndg.nerc.ac.uk/moles';
260declare option exist:timeout '24500';
261
262import module namespace voclib='http://ndg.nerc.ac.uk/xquery/lib/vocab' at 'xmldb:exist:///db/xqueryLib/Vocabs/vocab_xquery_lib.xquery';
263import module namespace utillib='http://ndg.nerc.ac.uk/xquery/lib/utilities' at 'xmldb:exist:///db/xqueryLib/Utilities/utility_xquery_lib.xquery';
264(:
265Will return when scope problem sussed... ;(
266import module namespace stubblib='http://ndg.nerc.ac.uk/xquery/lib/stubb' at 'xmldb:exist:///db/xqueryLib/StubB/stubb_xquery_lib.xquery';
267:)
268declare variable $targetCollection as xs:string {'TargetCollection'};
269declare variable $repositoryIdentifier as xs:string {'RepositoryID'};
270declare variable $localIdentifier as xs:string {'LocalID'};
271
272declare function f:return-stub-activity($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
273(: Returns a 'stubB' style activity record to expand an activity record :)
274(: Security not implemented here yet :)
275{
276let $SRAct := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
277moles:dgMetadataID/moles:localIdentifier=$locid
278and moles:dgMetadataID/moles:repositoryIdentifier=$repid ]
279return
280element  {$out-element-name} {
281($SRAct/moles:dgMetadataID),
282($SRAct/moles:dgMetadataDescription),
283($SRAct/moles:name),
284($SRAct/moles:abbreviation),
285($SRAct/moles:logos),
286element dgActivity {
287} (: </dgActivity> :)
288} (: </activity> :)
289} ;
290
291declare function f:return-stub-dataentity($out-element-name as xs:string, $DE as element()) as element()
292(: Returns a 'stubB' style observation station record to expand an data entity record :)
293(: Security not implemented yet :)
294{
295let $SRDE := $DE
296return 
297element {$out-element-name} {
298($SRDE/moles:dgMetadataID),
299($SRDE/moles:dgMetadataDescription),
300($SRDE/moles:name),
301($SRDE/moles:abbreviation),
302element dgDataEntity {
303} (: </dgDataEntity> :)       
304}
305} ;
306
307declare function f:return-stub-dpt($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
308(: Returns a 'stubB' style dpt record to expand a dpt record :)
309(: Security not implemented yet :)
310{
311let $SRDPT := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
312moles:dgMetadataID/moles:localIdentifier=$locid
313and
314moles:dgMetadataID/moles:repositoryIdentifier=$repid
315]
316return 
317element {$out-element-name} {
318$SRDPT/moles:dgMetadataID,
319$SRDPT/moles:dgMetadataDescription,
320$SRDPT/moles:name,
321$SRDPT/moles:abbreviation,
322$SRDPT/moles:logos,
323element dgDataProductionTool {
324} (: </dgDataProductionTool> :)
325} (: </dataproductiontool> :)
326} ;
327
328declare function f:return-stub-obsstn($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
329(: Returns a 'stubB' style observation station record to expand an observation station record :)
330(: Security not implemented here yet;  :)
331{
332let $SRObsStn := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
333moles:dgMetadataID/moles:localIdentifier=$locid
334and
335moles:dgMetadataID/moles:repositoryIdentifier=$repid
336]
337return
338element {$out-element-name} {
339($SRObsStn/moles:dgMetadataID),
340($SRObsStn/moles:dgMetadataDescription),
341($SRObsStn/moles:name),
342($SRObsStn/moles:abbreviation),
343($SRObsStn/moles:logos),
344element dgObservationStation {
345} (: </dgObservationStation> :)
346}
347} ;
348
349declare function f:return-stub-person($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
350(: Returns a 'stubB' style observation station record to expand a person record :)
351(: Security not implemented yet :)
352{
353let $person := collection($targetCollection)/moles:dgMetadata/moles:dgPerson[
354moles:dgMetadataID/moles:localIdentifier=$locid
355and
356moles:dgMetadataID/moles:repositoryIdentifier=$repid
357]
358return
359element  {$out-element-name}
360{
361($person/moles:name),
362($person/moles:contactDetails),
363($person/moles:dgMetadataID)
364}
365} ;
366
367declare function f:return-stub-organisation($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
368(: Returns a 'stubB' style observation station record to expand an organisation record :)
369(: Security not implemented yet :)
370{
371let $org := collection($targetCollection)/moles:dgMetadata/moles:dgOrganisation[
372moles:dgMetadataID/moles:localIdentifier=$locid
373and
374moles:dgMetadataID/moles:repositoryIdentifier=$repid
375]
376return
377element  {$out-element-name} {
378$org/moles:dgMetadataID,
379$org/moles:name,
380$org/moles:abbreviation,
381$org/moles:contactDetails,
382$org/moles:logos
383}
384} ;
385
386for $Act in collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
387    moles:dgActivity!=''
388    and moles:dgMetadataID[
389    moles:schemeIdentifier='NDG-B0'
390    and moles:repositoryIdentifier=$repositoryIdentifier
391    and moles:localIdentifier=$localIdentifier]]
392    return
393utillib:strip-namespace(element dgMetadataRecord {
394    element dgMetadataID {
395        element schemeIdentifier {'NDG-B1'},
396        (element repositoryIdentifier {data($Act/moles:dgMetadataID/moles:repositoryIdentifier)}),
397        element localIdentifier {data($Act/moles:dgMetadataID/moles:localIdentifier)}
398    },
399    $Act/moles:dgMetadataDescription,
400    $Act/moles:name,
401    $Act/moles:abbreviation,
402    element dgActivity {
403        for $RelatedActivities in $Act/dgActivity/moles:relatedActivity
404            return
405                element relatedActivity {
406                    $RelatedActivities/moles:activityRelation,
407                    f:return-stub-activity('activity', data($RelatedActivities/moles:relatedActivityID/moles:repositoryIdentifier), data($RelatedActivities/moles:relatedActivityID/moles:localIdentifier))
408            },    (: </relatedActivity> :)
409        if (exists($Act/moles:dgActivity/moles:dgActivityDataCollection)) then ($Act/moles:dgActivity/moles:dgActivityDataCollection)
410        else if (exists($Act/moles:dgActivity/moles:dgActivityDataProject)) then ($Act/moles:dgActivity/moles:dgActivityDataProject)
411        else if (exists($Act/moles:dgActivity/moles:dgActivityDataInvestigation)) then ($Act/moles:dgActivity/moles:dgActivityDataInvestigation)
412        else if (exists($Act/moles:dgActivity/moles:dgActivityDataCampaign)) then ($Act/moles:dgActivity/moles:dgActivityDataCampaign)
413        else (),
414        element dgActivityRole {
415            element dgInvestigator {
416                element dgPrincipalInvestigator {
417                    ($Act/moles:dgActivity/moles:dgActivityRole/moles:dgInvestigator/moles:dgPrincipalInvestigator/moles:dgMetadataID),
418                    ($Act/moles:dgActivity/moles:dgActivityRole/moles:dgInvestigator/moles:dgPrincipalInvestigator/moles:roleName),
419                    ($Act/moles:dgActivity/moles:dgActivityRole/moles:dgInvestigator/moles:dgPrincipalInvestigator/moles:abbreviation),
420                    ($Act/moles:dgActivity/moles:dgActivityRole/moles:dgInvestigator/moles:dgPrincipalInvestigator/moles:contactDetails),
421                    for $PIRole in $Act/moles:dgActivity/moles:dgActivityRole/moles:dgInvestigator/moles:dgPrincipalInvestigator/moles:dgRoleHolder
422                        order by $PIRole/moles:startDate empty least, $PIRole/moles:endDate empty least
423                        return
424                        element dgRoleHolder {
425                            if (exists($PIRole/moles:dgOrganisationID)) then
426                                f:return-stub-organisation('organisation', data($PIRole/moles:dgOrganisationID/moles:repositoryIdentifier), data($PIRole/moles:dgOrganisationID/moles:localIdentifier))
427                             else if (exists($PIRole/moles:dgPersonID)) then
428                                f:return-stub-person('person', string($PIRole/moles:dgPersonID/moles:repositoryIdentifier), string($PIRole/moles:dgPersonID/moles:localIdentifier))
429                             else (),
430                            ($PIRole/moles:startDate),
431                            if (exists($PIRole/moles:endDate)) then
432                                ($PIRole/moles:endDate)
433                            else (),
434                            if (exists($PIRole/moles:localName)) then
435                                ($PIRole/moles:localName)
436                            else ()
437                        } (: </dgRoleHolder> :)
438                }, (: </dgPrincipalInvestigator> :)
439                for $CI in $Act/moles:dgActivity/moles:dgActivityRole/moles:dgInvestigator/moles:dgCoInvestigator
440                return 
441                    element dgCoInvestigator {
442                        ($CI/moles:dgMetadataID),
443                        ($CI/moles:roleName),
444                        ($CI/moles:abbreviation),
445                        ($CI/moles:contactDetails),
446                        for $CIRole in $CI/moles:dgRoleHolder
447                            order by $CIRole/moles:startDate empty least, $CIRole/moles:endDate empty least
448                        return
449                        element dgRoleHolder {
450                            if (exists(CIRole/moles:dgOrganisationID)) then
451                                f:return-stub-organisation('organisation', data($CIRole/moles:dgOrganisationID/moles:repositoryIdentifier), data($CIRole/moles:dgOrganisationID/moles:localIdentifier))
452                             else if (exists($CIRole/moles:dgPersonID)) then
453                                f:return-stub-person('person', string($CIRole/moles:dgPersonID/moles:repositoryIdentifier), string($CIRole/moles:dgPersonID/moles:localIdentifier))
454                             else (),
455                            ($CIRole/moles:startDate),
456                            if (exists($CIRole/moles:endDate)) then
457                                ($CIRole/moles:endDate)
458                            else (),
459                            if (exists($CIRole/moles:localName)) then
460                                ($CIRole/moles:localName)
461                            else ()
462                        } (: </dgRoleHolder> :)
463                } (: </dgCoInvestigator> :)
464        }, (: </dgInvestigator> :)
465        if (exists($Act/moles:dgActivity/moles:dgActivityRole/moles:dgTechnicalContact)) then (
466            element dgTechnicalContact {
467                ($Act/moles:dgActivity/moles:dgActivityRole/moles:dgTechnicalContact/moles:dgMetadataID),
468                ($Act/moles:dgActivity/moles:dgActivityRole/moles:dgTechnicalContact/moles:roleName),
469                ($Act/moles:dgActivity/moles:dgActivityRole/moles:dgTechnicalContact/moles:abbreviation),
470                ($Act/moles:dgActivity/moles:dgActivityRole/moles:dgTechnicalContact/moles:contactDetails),
471                for $TechConRole in $Act/moles:dgActivity/moles:dgActivityRole/moles:dgTechnicalContact/moles:dgRoleHolder
472                    order by $TechConRole/moles:startDate empty least, $TechConRole/moles:endDate empty least
473                    return
474                    element dgRoleHolder {
475                        if (exists($TechConRole/moles:dgOrganisationID)) then
476                            f:return-stub-organisation('organisation', data($TechConRole/moles:dgOrganisationID/moles:repositoryIdentifier), data($TechConRole/moles:dgOrganisationID/moles:localIdentifier))
477                         else if (exists($TechConRole/moles:dgPersonID)) then
478                            f:return-stub-person('person', string($TechConRole/moles:dgPersonID/moles:repositoryIdentifier), string($TechConRole/moles:dgPersonID/moles:localIdentifier))
479                         else (),
480                        ($TechConRole/moles:startDate),
481                        if (exists($TechConRole/moles:endDate)) then
482                            ($TechConRole/moles:endDate)
483                        else (),
484                        if (exists($TechConRole/moles:localName)) then
485                                ($TechConRole/moles:localName)
486                           else ()
487                    } (: </dgRoleHolder> :)
488            } (: </dgTechnicalContact> :)
489        )
490        else (),
491        if (exists($Act/dgActivity/dgActivityRole/dgProjectManager)) then (
492            element dgProjectManager {
493                ($Act/dgActivity/dgActivityRole/dgProjectManager/dgMetadataID),
494                ($Act/dgActivity/dgActivityRole/dgProjectManager/roleName),
495                ($Act/dgActivity/dgActivityRole/dgProjectManager/abbreviation),
496                ($Act/dgActivity/dgActivityRole/dgProjectManager/contactDetails),
497                for $PMRole in $Act/dgActivity/dgActivityRole/dgProjectManager/dgRoleHolder
498                    order by $PMRole/startDate empty least, $PMRole/endDate empty least
499                    return
500                    element dgRoleHolder {
501                        if (exists($PMRole/moles:dgOrganisationID)) then
502                            f:return-stub-organisation('organisation', data($PMRole/moles:dgOrganisationID/moles:repositoryIdentifier), data($PMRole/moles:dgOrganisationID/moles:localIdentifier))
503                         else if (exists($PMRole/moles:dgPersonID)) then
504                            f:return-stub-person('person', string($PMRole/moles:dgPersonID/moles:repositoryIdentifier), string($PMRole/moles:dgPersonID/moles:localIdentifier))
505                         else (),
506                        ($PMRole/startDate),
507                        if (exists($PMRole/moles:endDate)) then
508                            ($PMRole/moles:endDate)
509                        else (),
510                        if (exists($PMRole/moles:localName)) then
511                            ($PMRole/moles:localName)
512                        else ()
513                    } (: </dgRoleHolder> :)
514            } (: </dgProjectManager> :)
515        )
516        else ()
517    }, (: </dgActivityRole> :)
518    for $RelDep in $Act/moles:dgActivity/moles:ActivityDeployment
519        return
520        element ActivityDeployment {
521            ($RelDep/moles:DateStart),
522            if (exists($RelDep/moles:DateEnd)) then
523                ($RelDep/moles:DateEnd)
524            else (),
525            ($RelDep/moles:dgMetadataID),
526            f:return-stub-dpt('dataproductiontool', data($RelDep/moles:DataProductionToolID/moles:repositoryIdentifier), data($RelDep/moles:DataProductionToolID/moles:localIdentifier)),
527            f:return-stub-obsstn('observationstation', data($RelDep/moles:ObservationStationID/moles:repositoryIdentifier), data($RelDep/moles:ObservationStationID/moles:localIdentifier)),
528                for $DE in collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[moles:dgDataEntity/moles:RelatedDeployment/moles:dgMetadataID/moles:repositoryIdentifier=$RelDep/moles:dgMetadataID/moles:repositoryIdentifier
529and moles:dgDataEntity/moles:RelatedDeployment/moles:dgMetadataID/moles:localIdentifier=$RelDep/moles:dgMetadataID/moles:localIdentifier]
530return
531f:return-stub-dataentity('dataentity', $DE)
532        }, (: </ActivityDeployment> :)
533        if (exists($Act/dgActivityCoverage)) then
534            ($Act/dgActivityCoverage)
535            else (),
536        if (exists($Act/dgActivityDuration)) then
537            ($Act/dgActivityDuration)
538            else ()
539    } , (: </dgActivity> :)
540    for $strkwrd in $Act/moles:dgStructuredKeyword return $strkwrd,
541    if (exists($Act/moles:dgMetadataProvenance)) then $Act/moles:dgMetadataProvenance else (),
542    if (exists($Act/moles:dgMetadataSecurity)) then $Act/moles:dgMetadataSecurity else ()
543} (:</dgMRecord>:)
544) (: End namespace strip :)
545'''
546
547StubBDPTQuery = '''
548declare default element namespace 'http://ndg.nerc.ac.uk/moles/dataproductiontool';
549import module namespace voclib='http://ndg.nerc.ac.uk/xquery/lib/vocab' at 'xmldb:exist:///db/xqueryLib/Vocabs/vocab_xquery_lib.xquery';
550import module namespace utillib='http://ndg.nerc.ac.uk/xquery/lib/utilities' at 'xmldb:exist:///db/xqueryLib/Utilities/utility_xquery_lib.xquery';
551declare option exist:timeout '24500';
552(:
553Will return when scope problem sussed... ;(
554import module namespace stubblib='http://ndg.nerc.ac.uk/xquery/lib/stubb' at 'xmldb:exist:///db/xqueryLib/StubB/stubb_xquery_lib.xquery';
555:)
556declare namespace f='http://ndg.nerc.ac.uk/moles/localfunctions';
557declare namespace moles='http://ndg.nerc.ac.uk/moles';
558
559declare variable $targetCollection as xs:string {'TargetCollection'};
560declare variable $repositoryIdentifier as xs:string {'RepositoryID'};
561declare variable $localIdentifier as xs:string {'LocalID'};
562
563declare function f:return-stub-activity($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
564(: Returns a 'stubB' style activity record to expand an activity record :)
565(: Security not implemented here yet :)
566{
567let $SRAct := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
568moles:dgMetadataID/moles:localIdentifier=$locid
569and moles:dgMetadataID/moles:repositoryIdentifier=$repid ]
570return
571element  {$out-element-name} {
572($SRAct/moles:dgMetadataID),
573($SRAct/moles:name),
574($SRAct/moles:abbreviation),
575($SRAct/moles:logos),
576element dgActivity {
577} (: </dgActivity> :)
578} (: </activity> :)
579} ;
580
581declare function f:return-stub-dataentity($out-element-name as xs:string, $DE as element()) as element()
582(: Returns a 'stubB' style observation station record to expand an data entity record :)
583(: Security not implemented yet :)
584{
585let $SRDE := $DE
586return 
587element {$out-element-name} {
588($SRDE/moles:dgMetadataID),
589($SRDE/moles:name),
590($SRDE/moles:abbreviation),
591element dgDataEntity {
592} (: </dgDataEntity> :)       
593}
594} ;
595
596declare function f:return-stub-dpt($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
597(: Returns a 'stubB' style dpt record to expand a dpt record :)
598(: Security not implemented yet :)
599{
600let $SRDPT := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
601moles:dgMetadataID/moles:localIdentifier=$locid
602and
603moles:dgMetadataID/moles:repositoryIdentifier=$repid
604]
605return 
606element {$out-element-name} {
607$SRDPT/moles:dgMetadataID,
608$SRDPT/moles:name,
609$SRDPT/moles:abbreviation,
610$SRDPT/moles:logos,
611element dgDataProductionTool {
612} (: </dgDataProductionTool> :)
613} (: </dataproductiontool> :)
614} ;
615
616declare function f:return-stub-obsstn($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
617(: Returns a 'stubB' style observation station record to expand an observation station record :)
618(: Security not implemented here yet;  :)
619{
620let $SRObsStn := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
621moles:dgMetadataID/moles:localIdentifier=$locid
622and
623moles:dgMetadataID/moles:repositoryIdentifier=$repid
624]
625return
626element {$out-element-name} {
627($SRObsStn/moles:dgMetadataID),
628($SRObsStn/moles:name),
629($SRObsStn/moles:abbreviation),
630($SRObsStn/moles:logos),
631element dgObservationStation {
632} (: </dgObservationStation> :)
633}
634} ;
635
636declare function f:return-stub-person($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
637(: Returns a 'stubB' style observation station record to expand a person record :)
638(: Security not implemented yet :)
639{
640let $person := collection($targetCollection)/moles:dgMetadata/moles:dgPerson[
641moles:dgMetadataID/moles:localIdentifier=$locid
642and
643moles:dgMetadataID/moles:repositoryIdentifier=$repid
644]
645return
646element  {$out-element-name}
647{
648($person/moles:name),
649($person/moles:contactDetails),
650($person/moles:dgMetadataID)
651}
652} ;
653
654declare function f:return-stub-organisation($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
655(: Returns a 'stubB' style observation station record to expand an organisation record :)
656(: Security not implemented yet :)
657{
658let $org := collection($targetCollection)/moles:dgMetadata/moles:dgOrganisation[
659moles:dgMetadataID/moles:localIdentifier=$locid
660and
661moles:dgMetadataID/moles:repositoryIdentifier=$repid
662]
663return
664element  {$out-element-name} {
665$org/moles:dgMetadataID,
666$org/moles:name,
667$org/moles:abbreviation,
668$org/moles:contactDetails,
669$org/moles:logos
670}
671} ;
672
673for $DPT in collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
674    moles:dgDataProductionTool!=''
675    and moles:dgMetadataID[
676    moles:schemeIdentifier='NDG-B0'
677    and moles:repositoryIdentifier=$repositoryIdentifier
678    and moles:localIdentifier=$localIdentifier]]
679    return
680utillib:strip-namespace(element dgMetadataRecord {
681    $DPT/dgMetadataID,
682        element dgMetadataID {
683            element schemeIdentifier {'NDG-B1'},
684            $DPT/moles:dgMetadataID/moles:repositoryIdentifier,
685            $DPT/moles:dgMetadataID/moles:localIdentifier
686        } (: End </dgMetadataID> :),
687    $DPT/moles:dgMetadataDescription,
688    $DPT/moles:name,
689    $DPT/moles:abbreviation,
690    element dgDataProductionTool {
691        $DPT/moles:contactDetails,
692        if (exists($DPT/moles:dgModel)) then $DPT/moles:dgModel
693        else $DPT/moles:dgInstrument
694    ,
695    if (exists($DPT/moles:dgDPTRoles)) then
696        element dgDPTRoles {'Roles are available, and will be added soon'}
697     else(),
698    for $RelDep in $DPT/moles:dgDataProductionTool/moles:DPTDeployment
699    return
700        element DPTDeployment {
701            $RelDep/moles:DateStart,
702            $RelDep/moles:DateEnd,
703            $RelDep/moles:dgMetadataID,
704            f:return-stub-activity('activity', data($RelDep/moles:ActivityID/moles:repositoryIdentifier), data($RelDep/moles:ActivityID/moles:localIdentifier)),
705            f:return-stub-obsstn('observationstation', data($RelDep/moles:ObservationStationID/moles:repositoryIdentifier), data($RelDep/moles:ObservationStationID/moles:localIdentifier)),
706                for $DE in collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[moles:dgDataEntity/moles:RelatedDeployment/moles:dgMetadataID/moles:repositoryIdentifier=$RelDep/moles:dgMetadataID/moles:repositoryIdentifier
707and moles:dgDataEntity/moles:RelatedDeployment/moles:dgMetadataID/moles:localIdentifier=$RelDep/moles:dgMetadataID/moles:localIdentifier]
708return
709f:return-stub-dataentity('dataentity', $DE),
710            $RelDep/moles:Coverage
711        } (: </DPTDeployment> :)
712    } (: </dgDataProductionTool> :),
713    for $strkwrd in $DPT/moles:dgStructuredKeyword return $strkwrd,
714    if (exists($DPT/moles:dgMetadataProvenance)) then $DPT/moles:dgMetadataProvenance else (),
715    if (exists($DPT/moles:dgMetadataSecurity)) then $DPT/moles:dgMetadataSecurity else ()
716} (:End </dgMetadataRecord> :)
717) (: End namespace strip :)
718'''
719
720StubBObsStnQuery = '''
721declare default element namespace 'http://ndg.nerc.ac.uk/moles/observationstation';
722import module namespace voclib='http://ndg.nerc.ac.uk/xquery/lib/vocab' at 'xmldb:exist:///db/xqueryLib/Vocabs/vocab_xquery_lib.xquery';
723import module namespace utillib='http://ndg.nerc.ac.uk/xquery/lib/utilities' at 'xmldb:exist:///db/xqueryLib/Utilities/utility_xquery_lib.xquery';
724declare option exist:timeout '24500';
725(:
726Will return when scope problem sussed... ;(
727import module namespace stubblib='http://ndg.nerc.ac.uk/xquery/lib/stubb' at 'xmldb:exist:///db/xqueryLib/StubB/stubb_xquery_lib.xquery';
728:)
729declare namespace f='http://ndg.nerc.ac.uk/moles/localfunctions';
730declare namespace moles='http://ndg.nerc.ac.uk/moles';
731
732declare variable $targetCollection as xs:string {'TargetCollection'};
733declare variable $repositoryIdentifier as xs:string {'RepositoryID'};
734declare variable $localIdentifier as xs:string {'LocalID'};
735
736declare function f:return-stub-activity($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
737(: Returns a 'stubB' style activity record to expand an activity record :)
738(: Security not implemented here yet :)
739{
740let $SRAct := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
741moles:dgMetadataID/moles:localIdentifier=$locid
742and moles:dgMetadataID/moles:repositoryIdentifier=$repid ]
743return
744element  {$out-element-name} {
745($SRAct/moles:dgMetadataID),
746($SRAct/moles:name),
747($SRAct/moles:abbreviation),
748($SRAct/moles:logos),
749element dgActivity {
750} (: </dgActivity> :)
751} (: </activity> :)
752} ;
753
754declare function f:return-stub-dataentity($out-element-name as xs:string, $DE as element()) as element()
755(: Returns a 'stubB' style observation station record to expand an data entity record :)
756(: Security not implemented yet :)
757{
758let $SRDE := $DE
759return 
760element {$out-element-name} {
761($SRDE/moles:dgMetadataID),
762($SRDE/moles:name),
763($SRDE/moles:abbreviation),
764element dgDataEntity {
765} (: </dgDataEntity> :)       
766}
767} ;
768
769declare function f:return-stub-dpt($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
770(: Returns a 'stubB' style dpt record to expand a dpt record :)
771(: Security not implemented yet :)
772{
773let $SRDPT := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
774moles:dgMetadataID/moles:localIdentifier=$locid
775and
776moles:dgMetadataID/moles:repositoryIdentifier=$repid
777]
778return 
779element {$out-element-name} {
780$SRDPT/moles:dgMetadataID,
781$SRDPT/moles:name,
782$SRDPT/moles:abbreviation,
783$SRDPT/moles:logos,
784element dgDataProductionTool {
785} (: </dgDataProductionTool> :)
786} (: </dataproductiontool> :)
787} ;
788
789declare function f:return-stub-obsstn($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
790(: Returns a 'stubB' style observation station record to expand an observation station record :)
791(: Security not implemented here yet;  :)
792{
793let $SRObsStn := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
794moles:dgMetadataID/moles:localIdentifier=$locid
795and
796moles:dgMetadataID/moles:repositoryIdentifier=$repid
797]
798return
799element {$out-element-name} {
800($SRObsStn/moles:dgMetadataID),
801($SRObsStn/moles:name),
802($SRObsStn/moles:abbreviation),
803($SRObsStn/moles:logos),
804element dgObservationStation {
805} (: </dgObservationStation> :)
806}
807} ;
808
809declare function f:return-stub-person($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
810(: Returns a 'stubB' style observation station record to expand a person record :)
811(: Security not implemented yet :)
812{
813let $person := collection($targetCollection)/moles:dgMetadata/moles:dgPerson[
814moles:dgMetadataID/moles:localIdentifier=$locid
815and
816moles:dgMetadataID/moles:repositoryIdentifier=$repid
817]
818return
819element  {$out-element-name}
820{
821($person/moles:name),
822($person/moles:contactDetails),
823($person/moles:dgMetadataID)
824}
825} ;
826
827declare function f:return-stub-organisation($out-element-name as xs:string, $repid as xs:string, $locid as xs:string) as element()
828(: Returns a 'stubB' style observation station record to expand an organisation record :)
829(: Security not implemented yet :)
830{
831let $org := collection($targetCollection)/moles:dgMetadata/moles:dgOrganisation[
832moles:dgMetadataID/moles:localIdentifier=$locid
833and
834moles:dgMetadataID/moles:repositoryIdentifier=$repid
835]
836return
837element  {$out-element-name} {
838$org/moles:dgMetadataID,
839$org/moles:name,
840$org/moles:abbreviation,
841$org/moles:contactDetails,
842$org/moles:logos
843}
844} ;
845
846let $ObsStn := collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
847moles:dgObservationStation!=''
848and moles:dgMetadataID[
849moles:schemeIdentifier='NDG-B0'
850and moles:repositoryIdentifier=$repositoryIdentifier
851and moles:localIdentifier=$localIdentifier]]
852return
853utillib:strip-namespace(
854element dgMetadataRecord {
855element dgMetadataID {
856element schemeIdentifier {'NDG-B1'},
857$ObsStn/moles:dgMetadataID/moles:repositoryIdentifier,
858$ObsStn/moles:dgMetadataID/moles:localIdentifier
859} (: End </dgMetadataID> :),
860$ObsStn/moles:dgMetadataDescription,
861$ObsStn/moles:name,
862$ObsStn/moles:abbreviation,
863element dgObservationStation {
864$ObsStn/moles:dgObservationStation/moles:contactDetails,
865if (exists($ObsStn/moles:dgObservationStation/moles:dgStationaryPlatform)) then
866element dgStationaryPlatform {
867$ObsStn/moles:dgObservationStation/moles:dgStationaryPlatform/moles:position,
868if (exists($ObsStn/moles:dgObservationStation/moles:dgStationaryPlatform/moles:dgMooring)) then   
869element dgMooring {
870$ObsStn/moles:dgObservationStation/moles:dgStationaryPlatform/moles:dgMooring/moles:dateStart,
871$ObsStn/moles:dgObservationStation/moles:dgStationaryPlatform/moles:dgMooring/moles:dateEnd,
872for $DepositingCruise in $ObsStn/moles:dgObservationStation/moles:dgStationaryPlatform/moles:dgMooring/moles:DepositingCruise
873return
874f:return-stub-activity('depositingcruise', data($DepositingCruise/moles:dgMetadataID/moles:repositoryIdentifier), data($DepositingCruise/moles:dgMetadataID/moles:localIdentifier)),
875if (exists($ObsStn/moles:dgObservationStation/moles:dgStationaryPlatform/moles:dgMooring/moles:dgStationGrouping)) then   
876for $StationGrouping in $ObsStn/moles:dgObservationStation/moles:dgStationaryPlatform/moles:dgMooring/dgStationGrouping
877return 
878f:return-stub-obsstn('dgStationGrouping', data($StationGrouping/moles:dgMetadataID/moles:repositoryIdentifier), data($StationGrouping/moles:dgMetadataID/moles:localIdentifier))
879else ()
880} (: End </dgMooring> :) 
881else if (exists($ObsStn/dgObservationStation/dgStationaryPlatform/dgStationGroup)) then   
882element dgStationGroup {
883element dgGroupedStations {
884if (exists($ObsStn/dgObservationStation/dgStationaryPlatform/dgStationGroup/dgGroupedStations)) then
885for $GroupedStation in $ObsStn/dgObservationStation/dgStationaryPlatform/dgStationGroup/dgGroupedStation/dgGroupedStations
886return f:return-stub-obsstn('dgGroupedStation', data($GroupedStation/moles:dgMetadataID/moles:repositoryIdentifier), data($GroupedStation/moles:dgMetadataID/moles:localIdentifier))
887else ()
888} (: End </dgGroupedStations> :)
889} (: End </dgStationGroup> :)
890else $ObsStn/moles:dgObservationStation/moles:dgLandStation
891} (: End </dgStationaryPlatform>  :) 
892else $ObsStn/moles:dgObservationStation/moles:dgMovingPlatform ,
893for $RelDep in $ObsStn/moles:dgObservationStation/moles:ObsStationDeployment
894return
895element ObsStationDeployment {
896$RelDep/moles:DateStart,
897$RelDep/moles:DateEnd,
898$RelDep/moles:dgMetadataID,
899f:return-stub-activity('activity', data($RelDep/moles:ActivityID/moles:repositoryIdentifier), data($RelDep/moles:ActivityID/moles:localIdentifier)),
900f:return-stub-dpt('dataproductiontool', data($RelDep/moles:DataProductionToolID/moles:repositoryIdentifier), data($RelDep/moles:DataProductionToolID/moles:localIdentifier)),
901for $DE in collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[moles:dgDataEntity/moles:RelatedDeployment/moles:dgMetadataID/moles:repositoryIdentifier=$RelDep/moles:dgMetadataID/moles:repositoryIdentifier
902and moles:dgDataEntity/moles:RelatedDeployment/moles:dgMetadataID/moles:localIdentifier=$RelDep/moles:dgMetadataID/moles:localIdentifier]
903return
904f:return-stub-dataentity('dataentity', $DE),
905$RelDep/moles:Coverage
906} (: </RelatedDeployment> :)
907} (: </dgObservationStation> :),
908for $strkwrd in $ObsStn/moles:dgStructuredKeyword return $strkwrd,
909if (exists($ObsStn/moles:dgMetadataProvenance)) then $ObsStn/moles:dgMetadataProvenance else (),
910if (exists($ObsStn/moles:dgMetadataSecurity)) then $ObsStn/moles:dgMetadataSecurity else ()
911} (: End </dgMetadataRecord> :)
912) (: End namespace strip :)
913'''
914
915ISO19139Query = '''
916import module namespace voclib='http://ndg.nerc.ac.uk/xquery/lib/vocab' at 'xmldb:exist:///db/xqueryLib/Vocabs/vocab_xquery_lib.xquery';
917import module namespace utillib='http://ndg.nerc.ac.uk/xquery/lib/utilities' at 'xmldb:exist:///db/xqueryLib/Utilities/utility_xquery_lib.xquery';
918
919declare default element namespace 'http://www.isotc211.org/2005/gmd';
920declare namespace moles='http://ndg.nerc.ac.uk/moles';
921declare namespace gco='http://www.isotc211.org/2005/gco';
922declare namespace gmd='http://www.isotc211.org/2005/gmd';
923declare namespace gml='http://www.opengis.net/gml';
924declare namespace xlink='http://www.w3.org/1999/xlink';
925declare namespace xsi='http://www.w3.org/2001/XMLSchema-instance';
926declare option exist:timeout '24500';
927
928declare variable $targetCollection as xs:string {'TargetCollection'};
929declare variable $repositoryIdentifier as xs:string {'RepositoryID'};
930declare variable $localIdentifier as xs:string {'LocalID'};
931
932for $DE in collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
933    exists(moles:dgDataEntity)
934    and moles:dgMetadataID/moles:schemeIdentifier='NDG-B0'
935    and moles:dgMetadataID/moles:localIdentifier=$localIdentifier]
936return
937element MD_Metadata {
938    attribute xsi:schemaLocation {'http://www.isotc211.org/2005/gmd http://www.isotc211.org/2005/gmd/metadataEntity.xsd'},
939    element fileIdentifier {element gco:CharacterString {concat($DE/moles:dgMetadataID/moles:repositoryIdentifier, $utillib:moles_id_separator, 'ISO19115', $utillib:moles_id_separator, $DE/moles:dgMetadataID/moles:localIdentifier)}},
940    element language {
941        element gmd:LanguageCode {
942            attribute codeList {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#LanguageCode'},
943            attribute codeListValue {'eng'},
944            'English'}
945    } (: </language> :),
946    element hierarchyLevel {
947        element MD_ScopeCode {
948            attribute codeList {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_ScopeCode'},
949            attribute codeListValue {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_ScopeCode_dataset'},
950            'dataset'}
951    } (: </hierarchyLevel> :),
952    for $parent in $DE/moles:dgRelatedDataEntity[moles:RelationID/moles:dgValidTerm='is-part-of']
953    return
954        element parentIdentifier  {element gco:CharacterString {concat($DE/moles:dgMetadataID/moles:repositoryIdentifier, ':', $DE/moles:dgMetadataID/moles:localIdentifier, ':', $DE/moles:dgMetadataID/moles:localIdentifier)}},
955    for $DataCuratorRole in $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCurator/moles:dgRoleHolder[not(exists(moles:endDate)) or moles:endDate='']
956    return
957        for $DataCuratorRoleHolder in collection($targetCollection)/moles:dgMetadata/(moles:dgPerson | moles:dgOrganisation)[
958            moles:dgMetadataID/moles:schemeIdentifier='NDG-B0'
959            and moles:dgMetadataID/moles:repositoryIdentifier=$DataCuratorRole/(moles:dgPersonID | moles:dgOrganisationID)/moles:repositoryIdentifier
960            and moles:dgMetadataID/moles:localIdentifier=$DataCuratorRole/(moles:dgPersonID | moles:dgOrganisationID)/moles:localIdentifier]
961        return
962            element contact {
963                element CI_ResponsibleParty {
964                    if (string(local-name($DataCuratorRoleHolder))='dgOrganisation') then
965                        element organisationName {element gco:CharacterString {string($DataCuratorRoleHolder/moles:name)}}
966                    else if (string(local-name($DataCuratorRoleHolder))='dgPerson') then
967                        element individualName {element gco:CharacterString {string(concat(string($DataCuratorRoleHolder/moles:name/moles:initials), ' ', string($DataCuratorRoleHolder/moles:name/moles:familyName)))}}
968                    else ('empty content') ,     
969                    element positionName {
970                        if (exists($DataCuratorRoleHolder/moles:localName)) then
971                            element gco:CharacterString {$DataCuratorRoleHolder/moles:localName}
972                        else if (exists($DataCuratorRole/moles:roleName)) then
973                            element gco:CharacterString {$DataCuratorRole/moles:roleName}
974                        else
975                            element gco:CharacterString {'Curator'}
976                    } (: </positionName>:),
977                    element contactInfo {
978                        element gmd:CI_Contact {
979                            if (exists($DataCuratorRole/moles:contactDetails/moles:telephone
980                                or $DataCuratorRole/moles:contactDetails/moles:fax
981                                or $DataCuratorRoleHolder/moles:contactDetails/moles:telephone
982                                or $DataCuratorRoleHolder/moles:contactDetails/moles:fax)) then
983                                element phone {
984                                    element gmd:CI_Telephone {
985                                        if (exists($DataCuratorRole/moles:contactDetails/moles:telephone)) then
986                                            element voice {
987                                                element gco:CharacterString {data($DataCuratorRole/moles:contactDetails/moles:telephone)}
988                                            } (:</voice>:)
989                                        else if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:telephone)) then
990                                            element voice {
991                                                element gco:CharacterString {data($DataCuratorRoleHolder/moles:contactDetails/moles:telephone)}
992                                            } (:</voice>:)
993                                        else (),
994                                        if (exists($DataCuratorRole/moles:contactDetails/moles:fax)) then
995                                            element facsimile {
996                                                element gco:CharacterString {data($DataCuratorRoleHolder/moles:contactDetails/moles:fax)}
997                                            } (: </facsimile> :)
998                                        else if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:telephone)) then
999                                            element facsimile {
1000                                                element gco:CharacterString {data($DataCuratorRoleHolder/moles:contactDetails/moles:fax)}
1001                                            } (: </facsimile> :)
1002                                        else ()
1003                                    } (: </gmd:CI_Telephone> :)
1004                                } (: </phone> :)
1005                                                    else (),
1006                            element address {
1007                                element gmd:CI_Address {
1008                                    if (exists($DataCuratorRole/moles:contactDetails/moles:address/moles:addressline)) then                               
1009                                        for $addressline in $DataCuratorRole/moles:contactDetails/moles:address/moles:addressline
1010                                        return
1011                                            element deliveryPoint {element gco:CharacterString {data($addressline)}}
1012                                    else if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:addressline)) then
1013                                        for $addressline in $DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:addressline
1014                                        return
1015                                            element deliveryPoint {element gco:CharacterString {data($addressline)}}
1016                                    else (),
1017                                    if (exists($DataCuratorRole/moles:contactDetails/moles:address/moles:city)) then
1018                                        element city {element gco:CharacterString {data($DataCuratorRole/moles:contactDetails/moles:address/moles:city)}}
1019                                    else if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:city)) then
1020                                        element city {element gco:CharacterString {data($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:city)}}
1021                                    else (),
1022                                    if (exists($DataCuratorRole/moles:contactDetails/moles:eMail)) then
1023                                        element electronicMailAddress {element gco:CharacterString {data($DataCuratorRole/moles:contactDetails/moles:eMail)}}
1024                                    else if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:postcode)) then
1025                                        element electronicMailAddress {element gco:CharacterString {data($DataCuratorRoleHolder/moles:contactDetails/moles:eMail)}}
1026                                    else ()
1027                                } (: </gmd:CI_Address> :)
1028                            } (: </address> :)
1029                        } (: </gmd:CI_Contact> :)
1030                    } (: </contactInfo> :),
1031                    element role {
1032                        element CI_RoleCode {
1033                            attribute codeList {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_RoleCode'},
1034                            attribute codeListValue {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_RoleCode_custodian'},
1035                            if (exists($DataCuratorRole/moles:localName)) then                               
1036                                data($DataCuratorRole/moles:localName)
1037                            else if (exists($DataCuratorRoleHolder/moles:localName)) then
1038                                data($DataCuratorRoleHolder/moles:localName)
1039                            else 'Curator' 
1040                        } (: </CI_RoleCode> :)
1041                    } (: </role> :)
1042                } (: </CI_ResponsibleParty> :)
1043            } (: </contact> :),
1044
1045            element dateStamp {element gco:Date {adjust-date-to-timezone(current-date())}},
1046            element metadataStandardName {element gco:CharacterString {'ISO 19115:2003'}},
1047            element metadataStandardVersion {element gco:CharacterString {'2003'}},
1048            element identificationInfo {
1049                element gmd:MD_DataIdentification {
1050                    element citation {
1051                        element gmd:CI_Citation {
1052                            element title {element gco:CharacterString {data($DE/moles:name)}},
1053                            if (exists($DE/moles:abbreviation) and not(empty($DE/moles:abbreviation))) then
1054                                element alternateTitle {element gco:CharacterString {data($DE/moles:abbreviation)}}
1055                            else (),
1056                            element date {
1057                                if (exists($DE/(moles:DataProvenance | moles:dgMetadataProvenance)/moles:RecordCreation/moles:CreatedDate)) then
1058                                    element gmd:CI_Date {
1059                                        element date {element gco:Date {adjust-date-to-timezone(data($DE/(moles:DataProvenance | moles:dgMetadataProvenance)/moles:RecordCreation/moles:CreatedDate))}},
1060                                        element dateType {
1061                                            element CI_DateTypeCode {
1062                                                attribute codeList {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_DateTypeCode'},
1063                                                attribute codeListValue {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_DateTypeCode_creation' },
1064                                                'Creation'}
1065                                        } (: </dataType> :)
1066                                    } (: </gmd:CI_Date> :)
1067                                else
1068                                    attribute gco:nilReason {'unknown'}
1069                            } (: </date> :)
1070                        } (: </gmd:CI_Citation> :)
1071                    } (: </citation> :),
1072                    element abstract {element gco:CharacterString {data($DE/moles:dgMetadataDescription/moles:abstract/moles:abstractText)}},
1073                    element language {
1074                        element gmd:LanguageCode {
1075                            attribute codeList {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#LanguageCode'},
1076                            attribute codeListValue {'eng'},
1077                            'English' }
1078                    } (: </language> :),
1079                    for $ISOTopicCategory in ($DE/moles:dgStructuredKeyword[dgValidTermID/moles:ParentListID='http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_TopicCategoryCode'])
1080                    return
1081                        element topicCategory {
1082                            element gmd:MD_TopicCategoryCode {
1083                                attribute codeList {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_TopicCategoryCode'},
1084                                attribute codeListValue {string($ISOTopicCategory/moles:dgValidTerm)},
1085                                string($ISOTopicCategory/moles:dgValidTerm)}
1086                        } (: </topicCategory> :),
1087                    if (exists($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataCoverage)) then
1088                        element extent {
1089                            element gmd:EX_Extent {
1090                                (: add bounding boxes:)
1091                                for $geoBBox in $DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataCoverage//moles:BoundingBox
1092                                return
1093                                    element geographicElement {
1094                                        element EX_GeographicBoundingBox {
1095                                            element westBoundLongitude {element gco:Decimal {data($geoBBox/moles:LimitWest)}},
1096                                            element eastBoundLongitude {element gco:Decimal {data($geoBBox/moles:LimitEast)}},
1097                                            element southBoundLatitude {element gco:Decimal {data($geoBBox/moles:LimitSouth)}},
1098                                            element northBoundLatitude {element gco:Decimal {data($geoBBox/moles:LimitNorth)}}
1099                                        } (: </EX_GeographicBoundingBox> :)
1100                                    } (: </geographicElement> :),
1101                                (: add location terms:)
1102                                for $geoArea in $DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataCoverage//moles:dgArea
1103                                return
1104                                    element geographicElement {
1105                                        element EX_GeographicDescription {
1106                                            element geographicIdentifier {
1107                                                element gmd:RS_Identifier {
1108                                                element gco:CharacterString {element code {data($geoArea/moles:dgValidTerm)}},
1109                                                element gco:CharacterString {element codeSpace {data($geoArea/moles:dgValidTermID/moles:ParentListID)}}
1110                                                    }
1111                                                }
1112                                        } (: </EX_GeographicDescription> :)
1113                                    } (: </geographicElement> :)
1114                            } (: </gmd:EX_Extent> :)
1115                        } (: </extent> :)
1116                    else()
1117                } (:</gmd:MD_DataIdentification> :)
1118            } (: </identificationInfo> :)
1119} (: </MD_Metadata> :)'''
1120           
1121MOLESQuery = '''declare default element namespace 'http://ndg.nerc.ac.uk/moles';
1122declare variable $targetCollection as xs:string {'TargetCollection'};
1123declare variable $repositoryIdentifier as xs:string {'RepositoryID'};
1124declare variable $localIdentifier as xs:string {'LocalID'};
1125for $Moles in collection($targetCollection)/dgMetadata/dgMetadataRecord[dgMetadataID/schemeIdentifier='NDG-B0'
1126    and dgMetadataID/repositoryIdentifier=$repositoryIdentifier
1127    and dgMetadataID/localIdentifier=$localIdentifier]
1128    return $Moles '''
1129           
1130DIFQuery = '''import module namespace voclib='http://ndg.nerc.ac.uk/xquery/lib/vocab' at 'xmldb:exist:///db/xqueryLib/Vocabs/vocab_xquery_lib.xquery';
1131import module namespace utillib='http://ndg.nerc.ac.uk/xquery/lib/utilities' at 'xmldb:exist:///db/xqueryLib/Utilities/utility_xquery_lib.xquery';
1132declare default element namespace 'http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/';
1133declare namespace xsi='http://www.w3.org/2001/XMLSchema-instance';
1134declare namespace moles='http://ndg.nerc.ac.uk/moles';
1135declare option exist:timeout '24500';
1136
1137declare variable $targetCollection as xs:string {'TargetCollection'};
1138declare variable $repositoryIdentifier as xs:string {'RepositoryID'};
1139declare variable $localIdentifier as xs:string {'LocalID'};
1140
1141for $DE in collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
1142    exists('moles:dgDataEntity')
1143    and moles:dgMetadataID/moles:schemeIdentifier='NDG-B0'
1144    and moles:dgMetadataID/moles:repositoryIdentifier=$repositoryIdentifier
1145    and moles:dgMetadataID/moles:localIdentifier=$localIdentifier]
1146    return
1147element DIF {
1148    attribute xsi:schemaLocation {'http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/ http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/dif_v9.4.xsd'},
1149    element Entry_ID {concat($DE/moles:dgMetadataID/moles:repositoryIdentifier, $utillib:moles_id_separator, 'DIF', $utillib:moles_id_separator, $DE/moles:dgMetadataID/moles:localIdentifier)},
1150    element Entry_Title {string($DE/moles:name)},
1151    element Data_Set_Citation {
1152            for $DataCreatorRole in $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:dgRoleHolder[not(exists(moles:endDate)) or moles:endDate=''][1]
1153        return
1154            for $DataCreatorRoleHolder in collection($targetCollection)/moles:dgMetadata/*[(moles:dgMetadataID/moles:schemeIdentifier='NDG-B0'
1155                   and moles:dgMetadataID/moles:repositoryIdentifier=$DataCreatorRole/*/moles:repositoryIdentifier
1156                   and moles:dgMetadataID/moles:localIdentifier=$DataCreatorRole/*/moles:localIdentifier)]
1157            return
1158                    element Dataset_Creator {
1159                if (exists($DataCreatorRoleHolder/moles:name/moles:initials)) then
1160                    string(concat(string($DataCreatorRoleHolder/moles:name/moles:initials), ' ', string($DataCreatorRoleHolder/moles:name/moles:familyName)))
1161                else
1162                   string($DataCreatorRoleHolder/moles:abbreviation)
1163                    },
1164        element Dataset_Title {string($DE/moles:name)}
1165    },
1166    for $StructuredKeyword in ($DE/(moles:dgStructuredKeyword | moles:dgDataEntity/moles:dgDataSummary/moles:dgParameterSummary/moles:dgStdParameterMeasured)[(voclib:spot-vocab($voclib:gcmd_science_valids, moles:dgValidTermID/moles:ParentListID) or voclib:spot-vocab($voclib:gcmd_science_valids_correct, moles:dgValidTermID/moles:ParentListID) or voclib:spot-vocab($voclib:gcmd_science_valids_categories, moles:dgValidTermID/moles:ParentListID))]
1167    )
1168        return if (exists($StructuredKeyword/*/moles:dgValidTerm)) then
1169            element Parameters {
1170            element Category {string($StructuredKeyword/*/moles:dgValidTerm)},
1171            if (exists($StructuredKeyword//moles:dgValidSubterm)
1172                and $StructuredKeyword//moles:dgValidSubterm != ''
1173                and $StructuredKeyword//moles:dgValidSubterm != ' ') then
1174            for $Subterm in $StructuredKeyword//moles:dgValidSubterm[exists(moles:dgValidTerm)]
1175                where exists($Subterm/moles:dgValidSubterm)
1176                order by $Subterm/moles:ListLevel
1177                return
1178                    if ($Subterm/moles:ListLevel=1) then element Topic {string($Subterm/moles:dgValidSubterm/moles:dgValidTerm)}
1179                    else if ($Subterm/moles:ListLevel=2) then element Term {string($Subterm/moles:dgValidSubterm/moles:dgValidTerm)}
1180                    else if ($Subterm/moles:ListLevel=3) then element Variable {string($Subterm/moles:dgValidSubterm/moles:dgValidTerm)}
1181                    else if ($Subterm/moles:ListLevel=4) then element Detailed_Variable {string($Subterm/moles:dgValidSubterm/moles:dgValidTerm)}
1182                    else element GCMD_Science_Valid {$Subterm/moles:ListLevel,($Subterm/moles:dgValidSubterm/moles:dgValidTerm)}
1183            else()
1184                }
1185        else(),
1186    for $StructuredKeyword in ($DE//(moles:dgStructuredKeyword | moles:dgDataEntity/moles:dgDataSummary/moles:dgParameterSummary/moles:dgStdParameterMeasured)[voclib:spot-vocab($voclib:gcmd_science_valids, moles:dgValidTermID/moles:ParentListID) or voclib:spot-vocab($voclib:gcmd_science_valids_correct, moles:dgValidTermID/moles:ParentListID) or voclib:spot-vocab($voclib:gcmd_science_valids_deprecated, moles:dgValidTermID/moles:ParentListID) and (not(exists(moles:ListLevel)) or moles:ListLevel=0)])
1187    return
1188        element Parameters {data($StructuredKeyword/moles:dgValidTerm)},
1189    for $ISOTopicCategory in ($DE/moles:dgStructuredKeyword[voclib:spot-vocab($voclib:iso_topic_list, moles:dgValidTermID/moles:ParentListID)])
1190        return
1191            element ISO_Topic_Category {string($ISOTopicCategory/moles:dgValidTerm)},
1192    for $Keyword in distinct-values($DE//moles:dgStructuredKeyword[
1193    not (voclib:spot-vocab($voclib:iso_topic_list, moles:dgValidTermID/moles:ParentListID)
1194    or voclib:spot-vocab($voclib:gcmd_science_valids, moles:dgValidTermID/moles:ParentListID)
1195    or voclib:spot-vocab($voclib:gcmd_science_valids_correct, moles:dgValidTermID/moles:ParentListID)
1196    )]/moles:dgValidTerm)
1197    return element Keyword {string($Keyword)},
1198    for $DepDPT in ($DE/moles:dgDataEntity/moles:RelatedDeployment/moles:DataProductionToolID) 
1199    return
1200        element Sensor_Name {
1201            for $DepDPTAbbrev in ((collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[moles:dgMetadataID[moles:schemeIdentifier='NDG-B0' and moles:repositoryIdentifier=$DepDPT/moles:repositoryIdentifier and moles:localIdentifier=$DepDPT/moles:localIdentifier]]/moles:abbreviation))
1202                return element Short_Name {data($DepDPTAbbrev)},
1203            for $DepDPTName in ((collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[moles:dgMetadataID[moles:schemeIdentifier='NDG-B0' and moles:repositoryIdentifier=$DepDPT/moles:repositoryIdentifier and moles:localIdentifier=$DepDPT/moles:localIdentifier]]/moles:name))
1204                return element Long_Name {data($DepDPTName)}
1205            },
1206    for $DepObsStn in ($DE/moles:dgDataEntity/moles:RelatedDeployment/moles:ObservationStationID)
1207    return
1208        element Source_Name {
1209            for $DepObsStnAbbrev in ((collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[moles:dgMetadataID[moles:schemeIdentifier='NDG-B0' and moles:repositoryIdentifier=$DepObsStn/moles:repositoryIdentifier and moles:localIdentifier=$DepObsStn/moles:localIdentifier]]/moles:abbreviation))
1210                return element Short_Name {data($DepObsStnAbbrev)},
1211            for $DepObsStnName in ((collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[moles:dgMetadataID[moles:schemeIdentifier='NDG-B0' and moles:repositoryIdentifier=$DepObsStn/moles:repositoryIdentifier and moles:localIdentifier=$DepObsStn/moles:localIdentifier]]/moles:name))
1212                return element Long_Name {data($DepObsStnName)}
1213            },
1214    for $TemporalRange in ($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataCoverage//moles:DateRange)
1215        return
1216            element Temporal_Coverage
1217                {
1218                element Start_Date {data($TemporalRange/moles:DateRangeStart)},
1219                element End_Date {data($TemporalRange/moles:DateRangeEnd)}
1220                },
1221    for $TemporalTerm in ($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataCoverage//moles:dgArea[voclib:spot-vocab($voclib:gcmd_chronostratigraphic_valids, moles:dgValidTermID/moles:ParentListID)]/moles:dgValidTerm)
1222        return element Paleo_Temporal_Coverage {element Chronostratigraphic_Unit {data($TemporalTerm)}},
1223    for $Data_Set_Progress in ($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataStatus/moles:dgDatasetClosure)
1224        return element Data_Set_Progress {data($Data_Set_Progress)},
1225    for $BoundingBox in ($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataCoverage//moles:BoundingBox)
1226    return
1227        element Spatial_Coverage {
1228                element Southernmost_Latitude {data($BoundingBox/moles:LimitSouth)},
1229                element Northernmost_Latitude {data($BoundingBox/moles:LimitNorth)},
1230                element Westernmost_Longitude {data($BoundingBox/moles:LimitWest)},
1231                element Easternmost_Longitude {data($BoundingBox/moles:LimitEast)}
1232            },
1233    for $Location in ($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataCoverage//moles:dgArea[voclib:spot-vocab($voclib:gcmd_location_valids, moles:dgValidTermID/moles:ParentListID)])
1234        return element Location {data($Location/moles:dgValidTerm)},
1235    for $DepAct in ($DE/moles:dgDataEntity/moles:RelatedDeployment/moles:ActivityID)
1236    return
1237        element Project {
1238            for $DepActAbbrev in (collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[moles:dgMetadataID[moles:schemeIdentifier='NDG-B0' and moles:repositoryIdentifier=$DepAct/moles:repositoryIdentifier and moles:localIdentifier=$DepAct/moles:localIdentifier]]/moles:abbreviation)
1239                return
1240                    element Short_Name {data($DepActAbbrev)},
1241            for $DepActName in (collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[moles:dgMetadataID[moles:schemeIdentifier='NDG-B0' and moles:repositoryIdentifier=$DepAct/moles:repositoryIdentifier and moles:localIdentifier=$DepAct/moles:localIdentifier]]/moles:name)
1242                return
1243                    element Long_Name {data($DepActName)}
1244            },
1245    if (exists($DE/moles:dgDataEntity/moles:dgDataGranule/moles:accessControlPolicy)) then
1246            for $DG in $DE/moles:dgDataEntity/moles:dgDataGranule
1247                return
1248                                element Access_Constraints {
1249                            if (exists($DG/moles:dgGranuleSummary/moles:dgGranuleName)) then
1250                                concat('For data granule ', $DG/moles:dgGranuleSummary/moles:dgGranuleName, ': ')
1251                            else (),
1252                            if (exists($DG/moles:accessControlPolicy/moles:accessControlPolicyURL)) then
1253                                concat('See access control policy at ', escape-uri($DG/moles:accessControlPolicy/moles:accessControlPolicyURL, true()))
1254                            else if (exists($DG/moles:accessControlPolicy/moles:accessControlPolicyText)) then
1255                                data($DG/moles:accessControlPolicy/moles:accessControlPolicyText)
1256                             else
1257                                 for $securityCondition in $DG/moles:accessControlPolicy/moles:dgSecurityCondition
1258                                 return
1259                                     if (exists($securityCondition/moles:conditionExplanationText)) then
1260                                         concat('Effect: ', data($securityCondition/moles:effect), ' - ', data($securityCondition/moles:conditionExplanationText))
1261                                     else concat('Effect: ', data($securityCondition/moles:effect), 'needs ', data($securityCondition/moles:attauthRole), ' from ', data($securityCondition/moles:dgAttributeAuthority))
1262                        }
1263                else (),
1264    if (exists($DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:dgRoleHolder)) then
1265        for $DataCreatorRole in $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:dgRoleHolder
1266            order by $DataCreatorRole/moles:startDate empty least
1267                        return
1268                    for $DataCreatorRoleHolder in collection($targetCollection)/moles:dgMetadata/(moles:dgOrganisation | moles:dgPerson)
1269                                        [(moles:dgMetadataID/moles:schemeIdentifier='NDG-B0'
1270                                        and moles:dgMetadataID/moles:repositoryIdentifier=$DataCreatorRole/*/moles:repositoryIdentifier
1271                                        and moles:dgMetadataID/moles:localIdentifier=$DataCreatorRole/*/moles:localIdentifier)]
1272                    return
1273                            element Originating_Center {
1274                    if (string(local-name($DataCreatorRoleHolder))='dgOrganisation') then
1275                        (string($DataCreatorRoleHolder/moles:name))
1276                    else if (string(local-name($DataCreatorRoleHolder))='dgPerson') then
1277                        (string(concat(string($DataCreatorRoleHolder/moles:name/moles:initials), ' ', string($DataCreatorRoleHolder/moles:name/moles:familyName))))
1278                    else ('empty content')
1279                }
1280    else (),
1281    for $DataCuratorRole in $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCurator/moles:dgRoleHolder
1282    [not(exists(moles:endDate)) or moles:endDate='']
1283    return
1284    for $DataCuratorRoleHolder in collection($targetCollection)/moles:dgMetadata/(moles:dgOrganisation | moles:dgPerson)
1285    [(moles:dgMetadataID/moles:schemeIdentifier='NDG-B0'
1286    and moles:dgMetadataID/moles:repositoryIdentifier=$DataCuratorRole/*/moles:repositoryIdentifier
1287    and moles:dgMetadataID/moles:localIdentifier=$DataCuratorRole/*/moles:localIdentifier)]
1288    return
1289    element Data_Center {
1290    element Data_Center_Name {
1291    element Short_Name {
1292    if (exists($DataCuratorRoleHolder/moles:name/moles:initials)) then
1293    string(concat(string($DataCuratorRoleHolder/moles:name/moles:initials), ' ', string($DataCuratorRoleHolder/moles:name/moles:familyName)))
1294    else
1295    string($DataCuratorRoleHolder/moles:abbreviation)
1296    },
1297    element Long_Name {
1298    if (exists($DataCuratorRoleHolder/moles:name/moles:initials)) then
1299    string(concat(string($DataCuratorRoleHolder/moles:name/moles:initials), ' ', string($DataCuratorRoleHolder/moles:name/moles:familyName)))
1300    else string($DataCuratorRoleHolder/moles:name)
1301    }
1302    },
1303    if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:URI)) then
1304    element Data_Center_URL {data($DataCuratorRoleHolder/moles:contactDetails/moles:URI)}
1305    else (),
1306    for $DGID in $DE/moles:dgDataEntity/moles:dgDataGranule/moles:dataModelID
1307    return
1308    element Data_Set_ID {concat($DGID/moles:repositoryIdentifier, $utillib:moles_id_separator, $DGID/moles:schemeIdentifier, $utillib:moles_id_separator, $DGID/moles:localIdentifier)},
1309    element  Personnel {
1310    element Role {'Data Center Contact'},
1311    if (exists($DataCuratorRoleHolder/name/knownAs)) then
1312    element First_Name {string($DataCuratorRoleHolder/moles:name/moles:knownAs)}
1313    else if (exists($DataCuratorRoleHolder/moles:name/moles:initials)) then
1314    element First_Name {string($DataCuratorRoleHolder/moles:name/moles:initials)}
1315    else (),                   
1316    element Last_Name {
1317    if (exists($DataCuratorRoleHolder/moles:name/moles:familyName)) then
1318    string($DataCuratorRoleHolder/moles:name/moles:familyName)
1319    else string($DataCuratorRoleHolder/moles:name)
1320    },
1321    if (exists($DataCuratorRole/moles:contactDetails/moles:eMail)) then
1322    element Email {string($DataCuratorRole/moles:contactDetails/moles:eMail)}
1323    else
1324    if (exists($DataCuratorRoleHolder/contactDetails/eMail)) then
1325    (element Email {string($DataCuratorRoleHolder/moles:contactDetails/moles:eMail)})
1326    else (),
1327    if (exists($DataCuratorRole/moles:contactDetails/moles:telephone)) then
1328    element Phone {string($DataCuratorRole/moles:contactDetails/moles:telephone)}
1329    else if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:telephone)) then
1330    element Phone {string($DataCuratorRoleHolder/moles:contactDetails/moles:telephone)}
1331    else (),
1332    if (exists($DataCuratorRole/moles:contactDetails/moles:fax)) then
1333    element Fax {string($DataCuratorRole/moles:contactDetails/moles:fax)}
1334    else if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:fax)) then
1335    element Fax {string($DataCuratorRoleHolder/moles:contactDetails/moles:fax)}
1336    else (),
1337    if (exists($DataCuratorRole/moles:contactDetails/moles:address)) then
1338    element Contact_Address {
1339    for $addressline in $DataCuratorRole/moles:contactDetails/moles:address/moles:addressline
1340    return element Address {data($addressline)},
1341    if (exists($DataCuratorRole/moles:contactDetails/moles:address/moles:city)) then
1342    element City {string($DataCuratorRole/moles:contactDetails/moles:address/moles:city)}
1343    else (),
1344    if (exists($DataCuratorRole/moles:contactDetails/moles:address/moles:postcode)) then
1345    element Postal_Code {string($DataCuratorRole/moles:contactDetails/moles:address/moles:postcode)}
1346    else (),
1347    if (exists($DataCuratorRole/moles:contactDetails/moles:address/moles:country)) then
1348    element Country {string($DataCuratorRole/moles:contactDetails/moles:address/moles:country)}
1349    else ()
1350    }
1351    else if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:address)) then
1352    element Contact_Address {
1353    for $addressline in $DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:addressline
1354    return element Address {data($addressline)},
1355    if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:city)) then
1356    element City {string($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:city)}
1357    else (),
1358    if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:postcode)) then
1359    element Postal_Code {string($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:postcode)}
1360    else (),
1361    if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:country)) then
1362    element Country {string($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:country)}
1363    else ()
1364    }
1365    else ()
1366    }
1367    },
1368    element Summary {string($DE/moles:dgMetadataDescription/moles:abstract/moles:abstractText)},
1369    for $DG in $DE/moles:dgDataEntity/moles:dgDataGranule
1370        return
1371            if ($DG/moles:dataModelID/moles:schemeIdentifier='NDG-A0') then
1372                       (element Related_URL {
1373                               element URL_Content_Type {'NDG_A_SERVICE'},
1374                               if (exists($DG/instance/URI)) then
1375                                   element URL {escape-uri($DG/instance/URI, true())}
1376                               else if ($DG/moles:dataModelID/moles:repositoryIdentifier='badc.nerc.ac.uk') then
1377                                   element URL {escape-uri('http://dmgdev1.esc.rl.ac.uk/cgi-bin/ndgDataAccess?datasetSource=dmgdev1.esc.rl.ac.uk&amp;datasetID=', true())}
1378                               else ($DG/moles:dataModelID/moles:repositoryIdentifier),
1379                             element Description {'The NDG service delivering data via NDG A metadata.'}
1380                           },
1381                      element Related_URL {
1382                               element URL_Content_Type {'GET DATA > CSML'},
1383                               if (exists($DG/instance)) then
1384                                   element URL {escape-uri($DG/instance/URI, true())}
1385                               else if ($DG/moles:dataModelID/moles:repositoryIdentifier='badc.nerc.ac.uk') then
1386                                   element URL {escape-uri('http://dmgdev1.esc.rl.ac.uk/cgi-bin/ndgDataAccess?datasetSource=dmgdev1.esc.rl.ac.uk&amp;datasetID=', true())}
1387                               else (),
1388                             element Description {'The NDG service delivering data via NDG A metadata. Additional tag to be more in line with latest version of GCMD valids'}
1389                           })
1390            else if ($DG/moles:dataModelID/moles:schemeIdentifier='CDML-0') then
1391                           (element Related_URL {
1392                                   element URL_Content_Type {'NDG_A_SERVICE'},
1393                               if (exists($DG/instance)) then
1394                                   element URL {escape-uri($DG/instance/URI, true())}
1395                               else if ($DG/moles:dataModelID/moles:repositoryIdentifier='badc.nerc.ac.uk') then
1396                                   element URL {escape-uri('http://cdat.badc.nerc.ac.uk/cgi-bin/dxui.py?datasetURI_1=/', true())}
1397                               else (),
1398                             element Description {'The NDG service delivering data via Data extractor. Additional tag to be more in line with latest version of GCMD valids'}
1399                               },
1400                           element Related_URL {
1401                               element URL_Content_Type {'GET DATA > DX'},
1402                               if (exists($DG/instance)) then
1403                                   element URL {escape-uri($DG/instance/URI, true())}
1404                               else if ($DG/moles:dataModelID/moles:repositoryIdentifier='badc.nerc.ac.uk') then
1405                                   element URL {escape-uri('http://cdat.badc.nerc.ac.uk/cgi-bin/dxui.py?datasetURI_1=/', true())}
1406                               else (),
1407                             element Description {'The NDG service delivering data via Data extractor. Additional tag to be more in line with latest version of GCMD valids'}
1408                               })
1409            else if ($DG/moles:dataModelID/moles:schemeIdentifier='URI') then
1410                       element Related_URL {
1411                             element URL {data($DG/moles:instance/moles:URI)},
1412                             if (exists($DG/moles:instance/moles:instanceComment)) then
1413                                     element Description {data($DG/moles:instance/moles:instanceComment)}           
1414                             else
1415                                     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 curator.'}
1416                          }
1417        else (),
1418        for $RelURL_Desc in ($DE/moles:dgMetadataDescription/moles:descriptionSection/moles:descriptionOnlineReference)
1419        return
1420                       if (exists($RelURL_Desc/moles:dgSimpleLink)) then
1421                       element Related_URL {
1422                       element URL {data($RelURL_Desc/moles:dgSimpleLink/URI)},
1423                       element Description {concat(data($RelURL_Desc/dgSimpleLink/moles:name), ' - ', data($RelURL_Desc/dgSimpleLink/moles:notes))}
1424                       }
1425                       else (),
1426    element Metadata_Name {'[CEOS IDN DIF]'},
1427    element Metadata_Version {'9.4'},
1428    if  (exists($DE/moles:dgMetadataProvenance/moles:RecordCreation)) then
1429            element DIF_Creation_Date {data($DE/moles:dgMetadataProvenance/moles:RecordCreation/moles:CreatedDate)}
1430    else (),
1431    for $MDUpdt in $DE/moles:dgMetadataProvenance/moles:RecordUpdate
1432    return 
1433        element DIF_Revision_History {concat(data($MDUpdt/moles:UpdateDate), ' - ', data($MDUpdt/moles:UpdateSummary), ' - ', data($MDUpdt/moles:UpdatedBy))},
1434    if  (exists($DE/moles:dgMetadataProvenance/moles:RecordReview)) then
1435            element Future_DIF_Review_Date {data($DE/moles:dgMetadataProvenance/moles:RecordReview/moles:ReviewDate)}
1436    else ()
1437        }'''
1438       
1439DublinCoreDEQuery='''import module namespace voclib='http://ndg.nerc.ac.uk/xquery/lib/vocab' at 'xmldb:exist:///db/xqueryLib/Vocabs/vocab_xquery_lib.xquery';
1440import module namespace utillib='http://ndg.nerc.ac.uk/xquery/lib/utilities' at 'xmldb:exist:///db/xqueryLib/Utilities/utility_xquery_lib.xquery';
1441declare default element namespace 'http://ndg.nerc.ac.uk/moles';
1442declare namespace xsi='http://www.w3.org/2001/XMLSchema-instance';
1443declare namespace dc='http://purl.org/dc/elements/1.1/';
1444declare namespace oai_dc='http://www.openarchives.org/OAI/2.0/oai_dc';
1445declare variable $targetCollection as xs:string {'TargetCollection'};
1446declare variable $repositoryIdentifier as xs:string {'RepositoryID'};
1447declare variable $localIdentifier as xs:string {'LocalID'};
1448
1449for $DE in collection($targetCollection)/dgMetadata/dgMetadataRecord[
1450exists('dgDataEntity')
1451and dgMetadataID/schemeIdentifier='NDG-B0'
1452and dgMetadataID/repositoryIdentifier=$repositoryIdentifier
1453and dgMetadataID/localIdentifier=$localIdentifier]
1454return
1455element oai_dc:dc {
1456    attribute xsi:schemaLocation {'http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd'},
1457    element dc:title {string($DE/name)},
1458    element dc:type {'Dataset'},
1459    element dc:identifier {concat($DE/dgMetadataID/repositoryIdentifier, $utillib:moles_id_separator, 'DC', $utillib:moles_id_separator, $DE/dgMetadataID/localIdentifier)},
1460    element dc:description {string($DE/dgMetadataDescription/abstract/abstractText)},
1461    element dc:date
1462        {
1463        if (exists($DE/(dgMetadataProvenance | DataProvenance)/RecordUpdate/UpdateDate)) then
1464            for $updatedate in ($DE/(dgMetadataProvenance | DataProvenance)/RecordUpdate/UpdateDate)
1465                order by xs:dateTime($updatedate)
1466            return data($updatedate[1])
1467        else
1468            string($DE/(dgMetadataProvenance | DataProvenance)/RecordCreation/CreatedDate)
1469        },
1470    for $StructuredKeyword in distinct-values($DE/dgStructuredKeyword[
1471    voclib:spot-vocab($voclib:cf_standard_names, dgValidTermID/ParentListID)
1472    or voclib:spot-vocab($voclib:gcmd_science_valids, dgValidTermID/ParentListID)
1473    or voclib:spot-vocab($voclib:gcmd_project_valids, dgValidTermID/ParentListID)
1474    or voclib:spot-vocab($voclib:iso_topic_list, dgValidTermID/ParentListID)
1475    or voclib:spot-vocab($voclib:bodc_parameter_usage_vocab, dgValidTermID/ParentListID)
1476    or voclib:spot-vocab($voclib:bodc_parameter_discovery_vocab, dgValidTermID/ParentListID)
1477    ]/dgValidTerm)
1478    order by $StructuredKeyword
1479    return
1480        element dc:subject {string($StructuredKeyword)},
1481   
1482    for $StructuredKeyword1 in distinct-values($DE/dgDataEntity/dgDataSummary/dgParameterSummary/dgStdParameterMeasured[
1483    voclib:spot-vocab($voclib:gcmd_science_valids, dgValidTermID/ParentListID)
1484    or voclib:spot-vocab($voclib:gcmd_project_valids, dgValidTermID/ParentListID)
1485    or voclib:spot-vocab($voclib:bodc_parameter_usage_vocab, dgValidTermID/ParentListID)
1486    or voclib:spot-vocab($voclib:bodc_parameter_discovery_vocab, dgValidTermID/ParentListID)
1487    ]/dgValidTerm)
1488        order by $StructuredKeyword1
1489    return
1490        element dc:subject  {string($StructuredKeyword1)},
1491    for $DataCreatorRole in $DE/dgDataEntity/dgDataRoles/dgDataCreator/dgRoleHolder
1492        order by $DataCreatorRole/startDate empty least
1493    return
1494        for $DataCreatorRoleHolder in collection($targetCollection)/dgMetadata/(dgOrganisation | dgPerson)
1495            [(dgMetadataID/schemeIdentifier='NDG-B0'
1496            and dgMetadataID/repositoryIdentifier=$DataCreatorRole/(dgOrganisationID | dgPersonID)/repositoryIdentifier
1497            and dgMetadataID/localIdentifier=$DataCreatorRole/(dgOrganisationID | dgPersonID)/localIdentifier)]
1498        return
1499            element dc:creator {
1500                if (string(local-name($DataCreatorRoleHolder))='dgOrganisation') then
1501                    (string($DataCreatorRoleHolder/name))
1502                else if (string(local-name($DataCreatorRoleHolder))='dgPerson') then
1503                    (string(concat(string($DataCreatorRoleHolder/name/initials), ' ', string($DataCreatorRoleHolder/name/familyName))))
1504                else ('empty content')
1505            },
1506    for $DataCuratorRole in $DE/dgDataEntity/dgDataRoles/dgDataCurator/dgRoleHolder[not(exists(endDate)) or endDate='']
1507        order by $DataCuratorRole/startDate empty least
1508    return
1509        for $DataCuratorRoleHolder in collection($targetCollection)/dgMetadata/(dgOrganisation | dgPerson)
1510            [(dgMetadataID/schemeIdentifier='NDG-B0'
1511            and dgMetadataID/repositoryIdentifier=$DataCuratorRole/(dgOrganisationID | dgPersonID)/repositoryIdentifier
1512            and dgMetadataID/localIdentifier=$DataCuratorRole/(dgOrganisationID | dgPersonID)/localIdentifier)]
1513        return
1514            element dc:publisher {
1515                if (string(local-name($DataCuratorRoleHolder))='dgOrganisation') then
1516                    (string($DataCuratorRoleHolder/name))
1517                else if (string(local-name($DataCuratorRoleHolder))='dgPerson') then
1518                    (string(concat(string($DataCuratorRoleHolder/name/initials), ' ', string($DataCuratorRoleHolder/name/familyName))))
1519                else ('empty content')
1520            }
1521}  (: </oai_dc:dc> :)'''
1522
1523MDIPQuery='''import module namespace voclib='http://ndg.nerc.ac.uk/xquery/lib/vocab' at 'xmldb:exist:///db/xqueryLib/Vocabs/vocab_xquery_lib.xquery';
1524import module namespace utillib='http://ndg.nerc.ac.uk/xquery/lib/utilities' at 'xmldb:exist:///db/xqueryLib/Utilities/utility_xquery_lib.xquery';
1525declare default element namespace 'http://www.oceannet.org/mdip/xml';
1526declare namespace moles='http://ndg.nerc.ac.uk/moles';
1527declare namespace gco='http://www.isotc211.org/2005/gco';
1528declare namespace xsi='http://www.w3.org/2001/XMLSchema-instance';
1529declare variable $targetCollection as xs:string {'TargetCollection'};
1530declare variable $repositoryIdentifier as xs:string {'RepositoryID'};
1531declare variable $localIdentifier as xs:string {'LocalID'};
1532declare variable $ISO_639-2_ns as xs:string{$voclib:ISO_639-2_ns};
1533declare variable $ISO_3166_ns as xs:string{$voclib:ISO_3166_ns};
1534
1535for $DE in collection($targetCollection)/moles:dgMetadata/moles:dgMetadataRecord[
1536    exists('moles:dgDataEntity')
1537    and moles:dgMetadataID/moles:schemeIdentifier='NDG-B0'
1538    and moles:dgMetadataID/moles:repositoryIdentifier=$repositoryIdentifier
1539    and moles:dgMetadataID/moles:localIdentifier=$localIdentifier]
1540return
1541element Metadata {
1542    element Title {data($DE/moles:name)},
1543    if (exists($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDatasetLanguage)) then
1544        for $lang in $DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDatasetLanguage
1545        return
1546            element Language{
1547                element LanguageName {data($lang/moles:dgValidTerm)},
1548                element LanguageVocab {data($lang/moles:dgValidTermID/moles:ParentListID)},
1549                element LanguageCode {data($lang/moles:dgValidTermID/moles:TermID)}
1550            }
1551               
1552    else (),
1553
1554    element Abstract {string($DE/moles:dgMetadataDescription/moles:abstract/moles:abstractText)},
1555    for $isoTopic in $DE/moles:dgStructuredKeyword[voclib:spot-vocab($voclib:iso_topic_list, moles:dgValidTermID/moles:ParentListID)]
1556    return element TopicCategory {
1557    element TopicCategoryName {data($isoTopic/moles:dgValidTerm)},
1558    element TopicCategoryVocab {data($isoTopic/moles:dgValidTermID/moles:ParentListID)},
1559    element TopicCategoryCode {data($isoTopic/moles:dgValidTermID/moles:TermID)}
1560    },
1561    for $subject in ($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgParameterSummary/moles:dgStdParameterMeasured[
1562    voclib:spot-vocab($voclib:gcmd_science_valids, moles:dgValidTermID/moles:ParentListID)
1563    or voclib:spot-vocab($voclib:gcmd_project_valids, moles:dgValidTermID/moles:ParentListID)
1564    or voclib:spot-vocab($voclib:gcmd_science_valids_categories, moles:dgValidTermID/moles:ParentListID)
1565    or voclib:spot-vocab($voclib:bodc_parameter_usage_vocab, moles:dgValidTermID/moles:ParentListID)
1566    or voclib:spot-vocab($voclib:bodc_parameter_discovery_vocab, moles:dgValidTermID/moles:ParentListID)
1567    ])
1568    return (element Subject {
1569    element SubjectName {data($subject/moles:dgValidTerm)},
1570    element SubjectVocab {data($subject/moles:dgValidTermID/moles:ParentListID)},
1571    element SubjectCode {data($subject/moles:dgValidTermID/moles:TermID)}
1572    },
1573    for $subterm in $subject//moles:dgValidSubterm
1574    return (element Subject {
1575    element SubjectName {data($subterm/moles:dgValidTerm)},
1576    element SubjectVocab {data($subterm/moles:dgValidTermID/moles:ParentListID)},
1577    element SubjectCode {data($subterm/moles:dgValidTermID/moles:TermID)}
1578    }
1579    )
1580    ),
1581    if (exists($DE//moles:dgTemporalCoverage/(moles:DateSingle | moles:DateRange))) then
1582    element Date {
1583        element DatasetStartDate {
1584        let $dateStart:=min($DE//moles:dgTemporalCoverage/(moles:DateSingle | moles:DateRange/moles:DateRangeStart) cast as xs:date)
1585        return
1586        if (empty($dateStart)) then ()
1587        else data($dateStart)
1588        },
1589        element DatasetEndDate {
1590        let $dateEnd:=max($DE//moles:dgTemporalCoverage/(moles:DateSingle | moles:DateRange/moles:DateRangeEnd) cast as xs:date)
1591        return
1592        if (empty($dateEnd)) then ()
1593        else data($dateEnd)
1594        }
1595    }
1596    else (),
1597    let $west := min($DE/moles:dgDataEntity/moles:dgDataSummary//moles:BoundingBox/moles:LimitWest cast as xs:decimal)
1598    return element WestCoOrdinate {data($west)},
1599    let $east := max($DE/moles:dgDataEntity/moles:dgDataSummary//moles:BoundingBox/moles:LimitEast cast as xs:decimal)
1600    return element EastCoOrdinate {data($east)},
1601    let $north := max($DE/moles:dgDataEntity/moles:dgDataSummary//moles:BoundingBox/moles:LimitNorth cast as xs:decimal)
1602    return element NorthCoOrdinate {data($north)},
1603    let $south := min($DE/moles:dgDataEntity/moles:dgDataSummary//moles:BoundingBox/moles:LimitSouth cast as xs:decimal)
1604    return element SouthCoOrdinate {data($south)},
1605    element DatasetIdentifier {concat($DE/moles:dgMetadataID/moles:repositoryIdentifier, $utillib:moles_id_separator, 'MDIP', $utillib:moles_id_separator, $DE/moles:dgMetadataID/moles:localIdentifier)},
1606    for $target in $DE/moles:dgStructuredKeyword[voclib:spot-vocab($voclib:ndg_data_provider_vocab, moles:dgValidTermID/moles:ParentListID) ]
1607    return element Target {
1608    element TargetName {data($target/moles:dgValidTerm)},
1609    element TargetVocab {data($target/moles:dgValidTermID/moles:ParentListID)},
1610    element TargetCode {data($target/moles:dgValidTermID/moles:TermID)}
1611    }
1612    }
1613'''
1614
1615
Note: See TracBrowser for help on using the repository browser.