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

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

Shopping cart, history and login framework for ows/discovery/browse.

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