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

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

Interim commit of discovery/browse in ows stack.

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