source: TI05-delivery/ows_framework/trunk/ows_server/ows_server/models/ndg_xqueries.py @ 3016

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI05-delivery/ows_framework/trunk/ows_server/ows_server/models/ndg_xqueries.py@3016
Revision 3016, 97.5 KB checked in by lawrence, 12 years ago (diff)

Improved the query for numsim searches.

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