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

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

Update ndg_xqueries.py

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