Ignore:
Timestamp:
06/02/07 17:23:34 (13 years ago)
Author:
mpritcha
Message:

Modified xqueries to check whether document in particular format already exists. Only generates doc on the fly if not. Some namespace fiddling required to return container element with doc inside. Removed DOM-related import statements as no longer needed.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • TI01-discovery/trunk/ws-Discovery2/src/ndg/services/discovery/PresentAgent.java

    r2096 r2114  
    88import java.io.*; 
    99 
    10  
    1110import org.apache.xmlrpc.XmlRpc; 
    1211import org.apache.xmlrpc.XmlRpcClient; 
    13  
    14 import javax.xml.parsers.DocumentBuilderFactory; 
    15 import javax.xml.parsers.DocumentBuilder; 
    16 import org.xml.sax.InputSource; 
    17 import org.w3c.dom.*; 
    18 import org.apache.xml.serialize.OutputFormat; 
    19 import org.apache.xml.serialize.XMLSerializer; 
    20  
    21 import javax.xml.namespace.*; 
    22 import javax.xml.xpath.*; 
    23 import javax.xml.*; 
    2412 
    2513import org.jdom.*; 
     
    2715import org.jdom.output.XMLOutputter; 
    2816import org.jdom.output.Format; 
    29 import org.jdom.output.EscapeStrategy; 
    3017 
    3118/** 
     
    7865 
    7966        /** 
    80          * Executes the remote getDocumentAsString method and returns document as a String 
    81          * @return String containing XML document 
     67         * Fetches document(s) in either "original" format or one of a number of supported<br> 
     68         * output formats (see presentFormatList).</p> 
     69         * In the case of each supported output format, a check is made as to whether the document<br> 
     70         * exists in that format within /db/discovery/original and if not, one is generated on the fly. 
     71         * @return PresentSummary object containing status, statusMessage and if appropriate, XML document as a String 
    8272         */ 
    8373        public PresentSummary doPresent() 
     
    120110                                        Vector queryParams = new Vector(); 
    121111 
    122                                         String xqueryStr = "let $doc := collection('/db/discovery/original')//root()[util:document-name(.) = '"+thisdoc+"' ] for $i in $doc return <document>{document-uri($i)}</document>"; 
    123                                         System.out.println("Doc search for present\n" + xqueryStr); 
     112                                        String xqueryStr = "let $doc := collection('/db/discovery/original')//root()[util:document-name(.) = '"+thisdoc+"' ] for $i in $doc return <document><collection>{util:collection-name($i)}</collection><content>{$i}</content></document>"; 
    124113 
    125114                                        queryParams.addElement( xqueryStr.getBytes("UTF-8") );  
     
    136125                                        ByteArrayInputStream resultStream = new ByteArrayInputStream( resultByteArray ); 
    137126 
    138                                         // Mark the beginning of the Stream, so can reset before each xpath evaluation (!) 
    139                                         resultStream.mark( resultStream.available() ); 
    140                                         InputSource resultSource = new InputSource( resultStream ); 
     127                                        SAXBuilder builder = new SAXBuilder(); 
     128                                        org.jdom.Document doc = builder.build( resultStream ); 
     129                                        org.jdom.Element root = doc.getRootElement(); 
     130 
     131                                        org.jdom.Element document = root.getChild("document"); 
     132                                        org.jdom.Element collection = document.getChild("collection"); 
     133                                        org.jdom.Element content = document.getChild("content"); 
     134 
     135                                        // Determine which subcollection of /db/discovery/original/FORMAT this doc belongs to and apply appropriate namespace for extraction of content 
     136                                        String[] collectionParts = collection.getTextTrim().split("/"); 
     137                                        String thisFormat = collectionParts[4]; 
    141138                                         
    142                                         XPath xpath = XPathFactory.newInstance().newXPath(); 
    143                                         String hitsExpr = "/exist:result/@hits";  
    144                                         String documentExpr = "//exist:result/document"; 
    145                                         xpath.setNamespaceContext( new existNamespaceContextImpl() ); 
    146                                         int hits = 0; 
    147                                         String docPath = ""; 
    148  
    149                                         try 
    150                                         { 
    151                                                 hits = (new Integer( xpath.evaluate(hitsExpr, resultSource) )).intValue(); 
     139                                        String namespaceURI = properties.getProperty("namespace." + thisFormat); 
     140                                        String rootElement = properties.getProperty("rootElement." + thisFormat); 
     141                                        String namespacePrefix = properties.getProperty("namespacePrefix." + thisFormat); 
     142 
     143                                        if ( content != null ) 
     144                                        { 
     145                                                org.jdom.Element elem = null;    
     146                                                if ( namespacePrefix.equals("") ) 
     147                                                { 
     148                                                        elem = content.getChild(rootElement, Namespace.getNamespace(namespaceURI) ); 
     149                                                } 
     150                                                else 
     151                                                { 
     152                                                        elem = content.getChild(rootElement,  Namespace.getNamespace(namespacePrefix, namespaceURI) ); 
     153                                                } 
     154                                                //  Use XMLOutputter 
     155                                                XMLOutputter out = new XMLOutputter (); 
     156                                                out.setFormat( Format.getCompactFormat() ); // UTF-8 & trimming of whitespace 
     157                                                returnDoc = out.outputString( elem ); 
     158 
     159                                                if (returnDoc != null) 
     160                                                { 
     161                                                        result.setStatus( true ); 
     162                                                        result.setStatusMessage( "Success" ); 
     163                                                        returnDocs.add( returnDoc );             
     164                                                } 
    152165                                        } 
    153                                         catch (NumberFormatException e) 
    154                                         { 
    155                                                 hits = 0; 
    156                                         } 
    157                                          
    158                                         resultStream.reset(); 
    159                                         NodeList nodeList = (NodeList)xpath.evaluate( documentExpr, resultSource, XPathConstants.NODESET );  
    160                                          
    161                                         if ( hits > 0 ) 
    162                                         { 
    163                                                 for (int i=0; i<nodeList.getLength(); i++) // limit to first doc of this name only 
    164                                                 { 
    165                                                         docPath = (String)nodeList.item(i).getFirstChild().getNodeValue(); 
    166                                                         System.out.println("PresentAgent found document : " + docPath); 
    167                                                         //2. Execute the remote getDocumentAsString()  
    168                                                         Vector getDocumentAsStringParams = new Vector(); 
    169                                                         getDocumentAsStringParams.addElement( docPath ); 
    170                                                         System.out.println("present request doc:\t "+docPath); 
    171                                                         getDocumentAsStringParams.addElement( options ); 
    172                                                         returnDoc = (String)xmlrpc.execute("getDocumentAsString", getDocumentAsStringParams ); 
    173                                                         if (returnDoc != null) 
    174                                                         { 
    175                                                                 result.setStatus( true ); 
    176                                                                 result.setStatusMessage( "Success" ); 
    177                                                                 returnDocs.add( returnDoc );             
    178                                                         } 
    179                                                         else { 
    180                                                                 throw new Exception("Got null response from getDocumentAsString()"); 
    181                                                         }                                                
    182                                                 }        
    183                                         } 
     166                                        else 
     167                                        { 
     168                                                throw new Exception("Unable to retrieve original format document"); 
     169                                        }                                                
     170 
    184171                                } 
    185172                                else if ( this.format.equals("DC") ) 
     
    187174                                        //1. Check to see if a dc-format document exists for this name 
    188175                                        Vector queryParams = new Vector(); 
    189                                         String xqueryStr = "declare default element namespace 'http://ndg.nerc.ac.uk/moles'; declare namespace dc='http://purl.org/dc/elements/1.1/'; declare namespace oai_dc='http://www.openarchives.org/OAI/2.0/oai_dc'; declare variable $gcmd_science_valids as xs:string {'http://gcmd.gsfc.nasa.gov/Resources/valids/gcmd_parameters.html'}; declare variable $gcmd_project_valids as xs:string {'http://gcmd.gsfc.nasa.gov/Resources/valids/projects.html'}; declare variable $cf_standard_names as xs:string {'http://www.cgd.ucar.edu/cms/eaton/cf-metadata/standard_name.html'}; declare variable $iso_topic_list as xs:string {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_TopicCategoryCode'}; for $DE in collection('/db/discovery/moles')/dgMetadata/dgMetadataRecord[dgDataEntity!='' and dgMetadataID/schemeIdentifier='NDG-B0'] where util:document-name($DE)='"+thisdoc+"' return <oai_dc:dc xmlns:oai_dc='http://www.openarchives.org/OAI/2.0/oai_dc/' xmlns:dc='http://purl.org/dc/elements/1.1/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd'> { element dc:title {string($DE/name)}, element dc:type {'Dataset'}, element dc:identifier {concat($DE/dgMetadataID/repositoryIdentifier, ':DC:', $DE/dgMetadataID/localIdentifier)}, element dc:description {string($DE/dgMetadataDescription/abstract/abstractText)}, element dc:date { if (exists($DE/(dgMetadataProvenance | DataProvenance)/RecordUpdate/UpdateDate)) then for $updatedate in $DE/(dgMetadataProvenance | DataProvenance)/RecordUpdate/UpdateDate order by xs:dateTime($updatedate) descending return xs:dateTime($updatedate[1]) else string($DE/(dgMetadataProvenance | DataProvenance)/RecordCreation/CreatedDate) }, for $StructuredKeyword in distinct-values($DE/dgStructuredKeyword [dgValidTermID/ParentListID=$cf_standard_names or dgValidTermID/ParentListID=$gcmd_science_valids or dgValidTermID/ParentListID=$gcmd_project_valids or dgValidTermID/ParentListID=$iso_topic_list ]//dgValidTerm) order by $StructuredKeyword return element dc:subject {string($StructuredKeyword)}, for $StructuredKeyword1 in distinct-values($DE/dgDataEntity/dgDataSummary/dgParameterSummary/dgStdParameterMeasured[dgValidTermID/ParentListID=$cf_standard_names or dgValidTermID/ParentListID=$gcmd_science_valids or dgValidTermID/ParentListID=$gcmd_project_valids]//dgValidTerm) order by $StructuredKeyword1 return element dc:subject {string($StructuredKeyword1)}, for $DataCreatorRole in $DE/dgDataEntity/dgDataRoles/dgDataCreator/dgRoleHolder order by $DataCreatorRole/startDate empty least return for $DataCreatorRoleHolder in collection('/db/ndg_B_metadata')/dgMetadata/(dgOrganisation | dgPerson) [(dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier=$DataCreatorRole/(dgOrganisationID | dgPersonID)/repositoryIdentifier and dgMetadataID/localIdentifier=$DataCreatorRole/(dgOrganisationID | dgPersonID)/localIdentifier)] return element dc:creator { if (string(local-name($DataCreatorRoleHolder))='dgOrganisation') then (string($DataCreatorRoleHolder/name)) else if (string(local-name($DataCreatorRoleHolder))='dgPerson') then (string(concat(string($DataCreatorRoleHolder/name/initials), ' ', string($DataCreatorRoleHolder/name/familyName)))) else ('empty content') }, for $DataCuratorRole in $DE/dgDataEntity/dgDataRoles/dgDataCurator/dgRoleHolder[not(exists(endDate)) or endDate=''] order by $DataCuratorRole/startDate empty least return for $DataCuratorRoleHolder in collection('/db/ndg_B_metadata')/dgMetadata/(dgOrganisation | dgPerson) [(dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier=$DataCuratorRole/(dgOrganisationID | dgPersonID)/repositoryIdentifier and dgMetadataID/localIdentifier=$DataCuratorRole/(dgOrganisationID | dgPersonID)/localIdentifier)] return element dc:publisher { if (string(local-name($DataCuratorRoleHolder))='dgOrganisation') then (string($DataCuratorRoleHolder/name)) else if (string(local-name($DataCuratorRoleHolder))='dgPerson') then (string(concat(string($DataCuratorRoleHolder/name/initials), ' ', string($DataCuratorRoleHolder/name/familyName)))) else ('empty content') } } </oai_dc:dc>"; 
     176                                        String xqueryStr = "declare default element namespace 'http://ndg.nerc.ac.uk/moles'; declare namespace dummy='http://ndg.nerc.ac.uk/dummy'; declare namespace dc='http://purl.org/dc/elements/1.1/'; declare namespace oai_dc='http://www.openarchives.org/OAI/2.0/oai_dc'; declare variable $gcmd_science_valids as xs:string {'http://gcmd.gsfc.nasa.gov/Resources/valids/gcmd_parameters.html'}; declare variable $gcmd_project_valids as xs:string {'http://gcmd.gsfc.nasa.gov/Resources/valids/projects.html'}; declare variable $cf_standard_names as xs:string {'http://www.cgd.ucar.edu/cms/eaton/cf-metadata/standard_name.html'}; declare variable $iso_topic_list as xs:string {'http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_TopicCategoryCode'}; declare function local:docExists($coll as xs:string, $doc as xs:string) as item()* { let $testset := collection($coll)//root()  let $matches :=   for $i in $testset  where util:document-name($i) = $doc  return  $i  return $matches  }; let $i := local:docExists('/db/discovery/original/"+this.format+"', '"+thisdoc+"')return if ( fn:empty($i) ) then ( for $DE in collection('/db/discovery/moles')/dgMetadata/dgMetadataRecord[dgDataEntity!='' and dgMetadataID/schemeIdentifier='NDG-B0'] where util:document-name($DE)='"+thisdoc+"' return element dummy:container { <oai_dc:dc xmlns:oai_dc='http://www.openarchives.org/OAI/2.0/oai_dc/' xmlns:dc='http://purl.org/dc/elements/1.1/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd'> { element dc:title {string($DE/name)}, element dc:type {'Dataset'}, element dc:identifier {concat($DE/dgMetadataID/repositoryIdentifier, ':DC:', $DE/dgMetadataID/localIdentifier)}, element dc:description {string($DE/dgMetadataDescription/abstract/abstractText)}, element dc:date { if (exists($DE/(dgMetadataProvenance | DataProvenance)/RecordUpdate/UpdateDate)) then for $updatedate in $DE/(dgMetadataProvenance | DataProvenance)/RecordUpdate/UpdateDate order by xs:dateTime($updatedate) descending return xs:dateTime($updatedate[1]) else string($DE/(dgMetadataProvenance | DataProvenance)/RecordCreation/CreatedDate) }, for $StructuredKeyword in distinct-values($DE/dgStructuredKeyword [dgValidTermID/ParentListID=$cf_standard_names or dgValidTermID/ParentListID=$gcmd_science_valids or dgValidTermID/ParentListID=$gcmd_project_valids or dgValidTermID/ParentListID=$iso_topic_list ]//dgValidTerm) order by $StructuredKeyword return element dc:subject {string($StructuredKeyword)}, for $StructuredKeyword1 in distinct-values($DE/dgDataEntity/dgDataSummary/dgParameterSummary/dgStdParameterMeasured[dgValidTermID/ParentListID=$cf_standard_names or dgValidTermID/ParentListID=$gcmd_science_valids or dgValidTermID/ParentListID=$gcmd_project_valids]//dgValidTerm) order by $StructuredKeyword1 return element dc:subject {string($StructuredKeyword1)}, for $DataCreatorRole in $DE/dgDataEntity/dgDataRoles/dgDataCreator/dgRoleHolder order by $DataCreatorRole/startDate empty least return for $DataCreatorRoleHolder in collection('/db/ndg_B_metadata')/dgMetadata/(dgOrganisation | dgPerson) [(dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier=$DataCreatorRole/(dgOrganisationID | dgPersonID)/repositoryIdentifier and dgMetadataID/localIdentifier=$DataCreatorRole/(dgOrganisationID | dgPersonID)/localIdentifier)] return element dc:creator { if (string(local-name($DataCreatorRoleHolder))='dgOrganisation') then (string($DataCreatorRoleHolder/name)) else if (string(local-name($DataCreatorRoleHolder))='dgPerson') then (string(concat(string($DataCreatorRoleHolder/name/initials), ' ', string($DataCreatorRoleHolder/name/familyName)))) else ('empty content') }, for $DataCuratorRole in $DE/dgDataEntity/dgDataRoles/dgDataCurator/dgRoleHolder[not(exists(endDate)) or endDate=''] order by $DataCuratorRole/startDate empty least return for $DataCuratorRoleHolder in collection('/db/ndg_B_metadata')/dgMetadata/(dgOrganisation | dgPerson) [(dgMetadataID/schemeIdentifier='NDG-B0' and dgMetadataID/repositoryIdentifier=$DataCuratorRole/(dgOrganisationID | dgPersonID)/repositoryIdentifier and dgMetadataID/localIdentifier=$DataCuratorRole/(dgOrganisationID | dgPersonID)/localIdentifier)] return element dc:publisher { if (string(local-name($DataCuratorRoleHolder))='dgOrganisation') then (string($DataCuratorRoleHolder/name)) else if (string(local-name($DataCuratorRoleHolder))='dgPerson') then (string(concat(string($DataCuratorRoleHolder/name/initials), ' ', string($DataCuratorRoleHolder/name/familyName)))) else ('empty content') } } </oai_dc:dc> } ) else ( element dummy:container { fn:item-at($i, 1) } ) "; 
    190177 
    191178                                        queryParams.addElement( xqueryStr.getBytes("UTF-8") );  
     
    200187 
    201188                                        byte[] resultByteArray = (byte[])xmlrpc.execute( "query", queryParams ); 
    202  
    203189                                        ByteArrayInputStream resultStream = new ByteArrayInputStream( resultByteArray ); 
    204190 
     
    206192                                        org.jdom.Document doc = builder.build( resultStream ); 
    207193                                        org.jdom.Element root = doc.getRootElement(); 
    208                                         org.jdom.Element elem = root.getChild("dc", Namespace.getNamespace("oai_dc", "http://www.openarchives.org/OAI/2.0/oai_dc/") ); 
     194                                        org.jdom.Element container = root.getChild("container", Namespace.getNamespace("dummy","http://ndg.nerc.ac.uk/dummy")); 
     195                                        org.jdom.Element elem = container.getChild("dc", Namespace.getNamespace("oai_dc", "http://www.openarchives.org/OAI/2.0/oai_dc/") ); 
    209196 
    210197                                        //  Use XMLOutputter 
     
    226213                                { 
    227214                                        Vector queryParams = new Vector(); 
    228                                         String xqueryStr = "declare default element namespace 'http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/';declare namespace xsi='http://www.w3.org/2001/XMLSchema-instance';declare namespace moles='http://ndg.nerc.ac.uk/moles';declare namespace f='http://ndg.nerc.ac.uk/moles/localfunctions';for $DE in collection('/db/discovery/moles')/moles:dgMetadata/moles:dgMetadataRecord[exists('moles:dgDataEntity')  and moles:dgMetadataID/moles:schemeIdentifier='NDG-B0'] where util:document-name($DE)='"+thisdoc+"' return element DIF {attribute xsi:schemaLocation {'http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/ http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/dif_v9.4.xsd'},element Entry_ID {concat($DE/moles:dgMetadataID/moles:repositoryIdentifier, ':DIF:', $DE/moles:dgMetadataID/moles:localIdentifier)},element Entry_Title {string($DE/moles:name)},element Data_Set_Citation {for $DataCreatorRole in $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:dgRoleHolder[not(exists(moles:endDate)) or moles:endDate=''][1] return  for $DataCreatorRoleHolder in collection('/db/discovery/moles')/moles:dgMetadata/*[(moles:dgMetadataID/moles:schemeIdentifier='NDG-B0' and moles:dgMetadataID/moles:repositoryIdentifier=$DataCreatorRole/*/moles:repositoryIdentifier and moles:dgMetadataID/moles:localIdentifier=$DataCreatorRole/*/moles:localIdentifier)] return  element Data_Creator {if (exists($DataCreatorRoleHolder/moles:name/moles:initials)) then  string(concat(string($DataCreatorRoleHolder/moles:name/moles:initials), ' ', string($DataCreatorRoleHolder/moles:name/moles:familyName))) else  string($DataCreatorRoleHolder/moles:abbreviation)},element Dataset_Title {string($DE/moles:name)}},for $StructuredKeyword in ($DE//(moles:dgStructuredKeyword | moles:dgStdParameterMeasured)[moles:dgValidTermID/moles:ParentListID='http://gcmd.gsfc.nasa.gov/Resources/valids/gcmd_parameters.html' and moles:ListLevel = 0]) return if (exists($StructuredKeyword/*/moles:dgValidTerm)) then  element Parameters {element Category {string($StructuredKeyword/*/moles:dgValidTerm)},if (exists($StructuredKeyword//moles:dgValidSubterm)  and $StructuredKeyword//moles:dgValidSubterm != ''  and $StructuredKeyword//moles:dgValidSubterm != ' ') then  for $Subterm in $StructuredKeyword//moles:dgValidSubterm[exists(moles:dgValidTerm)] where exists($Subterm/moles:dgValidSubterm) order by $Subterm/moles:ListLevel return  if ($Subterm/moles:ListLevel=1) then element Topic {string($Subterm/moles:dgValidSubterm/moles:dgValidTerm)}  else if ($Subterm/moles:ListLevel=2) then element Term {string($Subterm/moles:dgValidSubterm/moles:dgValidTerm)}  else if ($Subterm/moles:ListLevel=3) then element Variable {string($Subterm/moles:dgValidSubterm/moles:dgValidTerm)}  else if ($Subterm/moles:ListLevel=4) then element Detailed_Variable {string($Subterm/moles:dgValidSubterm/moles:dgValidTerm)}  else element GCMD_Science_Valid {string($Subterm/moles:dgValidSubterm/moles:dgValidTerm)} else()} else(),for $ISOTopicCategory in ($DE/moles:dgStructuredKeyword[moles:dgValidTermID/moles:ParentListID='http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_TopicCategoryCode']) return  element ISO_Topic_Category {string($ISOTopicCategory/moles:dgValidTerm)},for $Keyword in distinct-values($DE//moles:dgStructuredKeyword[ moles:dgValidTermID/moles:ParentListID!='http://gcmd.gsfc.nasa.gov/Resources/valids/gcmd_parameters.html'  and  moles:dgValidTermID/moles:ParentListID!='http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_TopicCategoryCode'  ]/moles:dgValidTerm) return element Keyword {string($Keyword)},  for $DepDPT in ($DE/moles:dgDataEntity/moles:RelatedDeployment/moles:DataProductionToolID)  return  element Sensor_Name {for $DepDPTAbbrev in distinct-values((collection('/db/discovery/moles')/moles:dgMetadata/moles:dgMetadataRecord[moles:dgMetadataID[moles:schemeIdentifier='NDG-B0' and moles:repositoryIdentifier=$DepDPT/moles:repositoryIdentifier and moles:localIdentifier=$DepDPT/moles:localIdentifier]]/moles:abbreviation)) return element Short_Name {data($DepDPTAbbrev)},for $DepDPTName in distinct-values((collection('/db/discovery/moles')/moles:dgMetadata/moles:dgMetadataRecord[moles:dgMetadataID[moles:schemeIdentifier='NDG-B0' and moles:repositoryIdentifier=$DepDPT/moles:repositoryIdentifier and moles:localIdentifier=$DepDPT/moles:localIdentifier]]/moles:name)) return element Long_Name {data($DepDPTName)}},for $DepObsStn in ($DE/moles:dgDataEntity/moles:RelatedDeployment/moles:ObservationStationID) return  element Source_Name {for $DepObsStnAbbrev in distinct-values((collection('/db/discovery/moles')/moles:dgMetadata/moles:dgMetadataRecord[moles:dgMetadataID[moles:schemeIdentifier='NDG-B0' and moles:repositoryIdentifier=$DepObsStn/moles:repositoryIdentifier and moles:localIdentifier=$DepObsStn/moles:localIdentifier]]/moles:abbreviation)) return element Short_Name {data($DepObsStnAbbrev)},for $DepObsStnName in distinct-values((collection('/db/discovery/moles')/moles:dgMetadata/moles:dgMetadataRecord[moles:dgMetadataID[moles:schemeIdentifier='NDG-B0' and moles:repositoryIdentifier=$DepObsStn/moles:repositoryIdentifier and moles:localIdentifier=$DepObsStn/moles:localIdentifier]]/moles:name)) return element Long_Name {data($DepObsStnName)}},for $TemporalRange in ($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataCoverage//moles:dgDateRange) return  element Temporal_Coverage {element Start_Date {data($TemporalRange/moles:DateRangeStart)},element End_Date {data($TemporalRange/moles:DateRangeEnd)}},for $TemporalTerm in ($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataCoverage//moles:dgArea/moles:dgValidTerm) return element Paleo_Temporal_Coverage {element Chronostratigraphic_Unit {data($TemporalTerm)}},  for $Data_Set_Progress in ($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataStatus/moles:dgDatasetClosure) return element Data_Set_Progress {data($Data_Set_Progress)},for $BoundingBox in ($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataCoverage//moles:BoundingBox) return  element Spatial_Coverage {element Southernmost_Latitude {data($BoundingBox/moles:LimitSouth)},element Northernmost_Latitude {data($BoundingBox/moles:LimitNorth)},element Westernmost_Longitude {data($BoundingBox/moles:LimitWest)},element Easternmost_Longitude {data($BoundingBox/moles:LimitEast)}},for $Location in ($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataCoverage//moles:dgArea[moles:dgValidTermID/moles:ParentListID='http://gcmd.gsfc.nasa.gov/Resources/valids/gcmd_locations.html']) return element Location {$Location},  for $DepAct in ($DE/moles:dgDataEntity/moles:RelatedDeployment/moles:ActivityID) return  element Project {for $DepActAbbrev in distinct-values(collection('/db/discovery/moles')/moles:dgMetadata/moles:dgMetadataRecord[moles:dgMetadataID[moles:schemeIdentifier='NDG-B0' and moles:repositoryIdentifier=$DepAct/moles:repositoryIdentifier and moles:localIdentifier=$DepAct/moles:localIdentifier]]/moles:abbreviation) return  element Short_Name {data($DepActAbbrev)},for $DepActName in distinct-values(collection('/db/discovery/moles')/moles:dgMetadata/moles:dgMetadataRecord[moles:dgMetadataID[moles:schemeIdentifier='NDG-B0' and moles:repositoryIdentifier=$DepAct/moles:repositoryIdentifier and moles:localIdentifier=$DepAct/moles:localIdentifier]]/moles:name) return  element Long_Name {data($DepActName)}},if (exists($DE/moles:dgDataEntity/moles:dgDataGranule/moles:accessControlPolicy)) then  for $DG in $DE/moles:dgDataEntity/moles:dgDataGranule return  element Access_Constraints {if (exists($DG/moles:dgGranuleSummary/moles:dgGranuleName)) then  concat('For data granule ', $DG/moles:dgGranuleSummary/moles:dgGranuleName, ': ') else (),if (exists($DG/moles:accessControlPolicy/moles:accessControlPolicyURL)) then concat('See access control policy at ', escape-uri($DG/moles:accessControlPolicy/moles:accessControlPolicyURL, true())) else if (exists($DG/moles:accessControlPolicy/moles:accessControlPolicyText)) then data($DG/moles:accessControlPolicy/moles:accessControlPolicyText) else  for $securityCondition in $DG/moles:accessControlPolicy/moles:dgSecurityCondition return if (exists($securityCondition/moles:conditionExplanationText)) then concat('Effect: ', data($securityCondition/moles:effect), ' - ', data($securityCondition/moles:conditionExplanationText)) else concat('Effect: ', data($securityCondition/moles:effect), 'needs ', data($securityCondition/moles:attauthRole), ' from ', data($securityCondition/moles:dgAttributeAuthority))} else (),if (exists($DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:dgRoleHolder)) then for $DataCreatorRole in $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:dgRoleHolder  order by $DataCreatorRole/moles:startDate empty least return  for $DataCreatorRoleHolder in collection('/db/discovery/moles')/moles:dgMetadata/(moles:dgOrganisation | moles:dgPerson) [(moles:dgMetadataID/moles:schemeIdentifier='NDG-B0' and moles:dgMetadataID/moles:repositoryIdentifier=$DataCreatorRole/(moles:dgOrganisationID | moles:dgPersonID)/moles:repositoryIdentifier and moles:dgMetadataID/moles:localIdentifier=$DataCreatorRole/(moles:dgOrganisationID | moles:dgPersonID)/moles:localIdentifier)] return  element Originating_Center {if (string(local-name($DataCreatorRoleHolder))='dgOrganisation') then (string($DataCreatorRoleHolder/moles:name)) else if (string(local-name($DataCreatorRoleHolder))='dgPerson') then (string(concat(string($DataCreatorRoleHolder/moles:name/moles:initials), ' ', string($DataCreatorRoleHolder/moles:name/moles:familyName)))) else ('empty content')} else (),for $DataCuratorRole in $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCurator/moles:dgRoleHolder[not(exists(moles:endDate)) or moles:endDate=''] return  for $DataCuratorRoleHolder in collection('/db/discovery/moles')/moles:dgMetadata/*[(moles:dgMetadataID/moles:schemeIdentifier='NDG-B0' and moles:dgMetadataID/moles:repositoryIdentifier=$DataCuratorRole/*/moles:repositoryIdentifier and moles:dgMetadataID/moles:localIdentifier=$DataCuratorRole/*/moles:localIdentifier)] return  element Data_Center {element Data_Center_Name {element Short_Name {if (exists($DataCuratorRoleHolder/moles:name/moles:initials)) then  string(concat(string($DataCuratorRoleHolder/moles:name/moles:initials), ' ', string($DataCuratorRoleHolder/moles:name/moles:familyName))) else  string($DataCuratorRoleHolder/moles:abbreviation)},element Long_Name {if (exists($DataCuratorRoleHolder/moles:name/moles:initials)) then  string(concat(string($DataCuratorRoleHolder/moles:name/moles:initials), ' ', string($DataCuratorRoleHolder/moles:name/moles:familyName))) else string($DataCuratorRoleHolder/moles:name)}},if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:URI)) then  element Data_Center_URL {data($DataCuratorRoleHolder/moles:contactDetails/moles:URI)} else (),for $DGID in $DE/moles:dgDataEntity/moles:dgDataGranule/moles:dataModelID return  element Data_Set_ID {concat($DGID/moles:repositoryIdentifier, ':', $DGID/moles:schemeIdentifier, ':', $DGID/moles:localIdentifier)},element Personnel {element Role {'Data Center Contact'},if (exists($DataCuratorRoleHolder/name/knownAs)) then  element First_Name {string($DataCuratorRoleHolder/moles:name/moles:knownAs)} else if (exists($DataCuratorRoleHolder/moles:name/moles:initials)) then  element First_Name {string($DataCuratorRoleHolder/moles:name/moles:initials)} else (),element Last_Name {if (exists($DataCuratorRoleHolder/moles:name/moles:familyName)) then  string($DataCuratorRoleHolder/moles:name/moles:familyName) else string($DataCuratorRoleHolder/moles:name)},if (exists($DataCuratorRole/moles:contactDetails/moles:eMail)) then  element Email {string($DataCuratorRole/moles:contactDetails/moles:eMail)} else  if (exists($DataCuratorRoleHolder/contactDetails/eMail)) then  (element Email {string($DataCuratorRoleHolder/moles:contactDetails/moles:eMail)}) else (),if (exists($DataCuratorRole/moles:contactDetails/moles:telephone)) then  element Phone {string($DataCuratorRole/moles:contactDetails/moles:telephone)} else if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:telephone)) then  element Phone {string($DataCuratorRoleHolder/moles:contactDetails/moles:telephone)} else (),if (exists($DataCuratorRole/moles:contactDetails/moles:fax)) then  element Fax {string($DataCuratorRole/moles:contactDetails/moles:fax)} else if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:fax)) then  element Fax {string($DataCuratorRoleHolder/moles:contactDetails/moles:fax)} else (),if (exists($DataCuratorRole/moles:contactDetails/moles:address)) then  element Contact_Address {for $addressline in $DataCuratorRole/moles:contactDetails/moles:address/moles:addressline return element address {data($addressline)},if (exists($DataCuratorRole/moles:contactDetails/moles:address/moles:city)) then  element City {string($DataCuratorRole/moles:contactDetails/moles:address/moles:city)} else (),if (exists($DataCuratorRole/moles:contactDetails/moles:address/moles:postcode)) then  element Postal_Code {string($DataCuratorRole/moles:contactDetails/moles:address/moles:postcode)} else (),if (exists($DataCuratorRole/moles:contactDetails/moles:address/moles:country)) then  element Country {string($DataCuratorRole/moles:contactDetails/moles:address/moles:country)} else ()} else if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:address)) then  element Contact_Address {for $addressline in $DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:addressline return element address {data($addressline)},if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:city)) then  element City {string($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:city)} else (),if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:postcode)) then  element Postal_Code {string($DataCuratorRole/moles:contactDetails/moles:postcode)} else (),if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:country)) then  element Country {string($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:country)} else ()} else ()}},element Summary {string($DE/moles:dgMetadataDescription/moles:abstract/moles:abstractText)},element Related_URL {element URL_Content_Type {'NDG_B_SERVICE'},element URL {data($DE/moles:dgMetadataID/moles:repositoryIdentifier)},element Description {'The NDG service for browsing metadata.'}},for $DG in $DE/moles:dgDataEntity/moles:dgDataGranule return if ($DG/moles:dataModelID/moles:schemeIdentifier='NDG-A0') then  (element Related_URL {element URL_Content_Type {'NDG_A_SERVICE'},if (exists($DG/instance/URI)) then element URL {escape-uri($DG/instance/URI, true())} else if ($DG/moles:dataModelID/moles:repositoryIdentifier='badc.nerc.ac.uk') then element URL {escape-uri('http://dmgdev1.esc.rl.ac.uk/cgi-bin/ndgDataAccess?datasetSource=dmgdev1.esc.rl.ac.uk&amp;datasetID=', true())} else ($DG/moles:dataModelID/moles:repositoryIdentifier),element Description {'The NDG service delivering data via NDG A metadata.'}},element Related_URL {element URL_Content_Type {'GET DATA > CSML'},if (exists($DG/instance)) then element URL {escape-uri($DG/instance/URI, true())} else if ($DG/moles:dataModelID/moles:repositoryIdentifier='badc.nerc.ac.uk') then element URL {escape-uri('http://dmgdev1.esc.rl.ac.uk/cgi-bin/ndgDataAccess?datasetSource=dmgdev1.esc.rl.ac.uk&amp;datasetID=', true())} else (),element Description {'The NDG service delivering data via NDG A metadata. Additional tag to be more in line with latest version of GCMD valids'}}) else if ($DG/moles:dataModelID/moles:schemeIdentifier='CDML-0') then  (element Related_URL {  element URL_Content_Type {'NDG_A_SERVICE'},if (exists($DG/instance)) then element URL {escape-uri($DG/instance/URI, true())} else if ($DG/moles:dataModelID/moles:repositoryIdentifier='badc.nerc.ac.uk') then element URL {escape-uri('http://cdat.badc.nerc.ac.uk/cgi-bin/dxui.py?datasetURI_1=/', true())} else (),element Description {'The NDG service delivering data via Data extractor. Additional tag to be more in line with latest version of GCMD valids'}},element Related_URL {element URL_Content_Type {'GET DATA > DX'},if (exists($DG/instance)) then element URL {escape-uri($DG/instance/URI, true())} else if ($DG/moles:dataModelID/moles:repositoryIdentifier='badc.nerc.ac.uk') then element URL {escape-uri('http://cdat.badc.nerc.ac.uk/cgi-bin/dxui.py?datasetURI_1=/', true())} else (),element Description {'The NDG service delivering data via Data extractor. Additional tag to be more in line with latest version of GCMD valids'}}) else if ($DG/moles:dataModelID/moles:schemeIdentifier='URI') then  element Related_URL {element URL {data($DG/moles:instance/moles:URI)},if (exists($DG/moles:instance/moles:instanceComment)) then  element Description {data($DG/moles:instance/moles:instanceComment)}  else  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.'}} else (),for $RelURL_Desc in ($DE/moles:dgMetadataDescription/moles:descriptionSection/moles:descriptionOnlineReference)  return element Related_URL {element URL {data($RelURL_Desc)},element Description {concat(data($RelURL_Desc/moles:name), ' - ', data($RelURL_Desc/moles:notes))} },element Metadata_Name {'[CEOS IDN DIF]'},element Metadata_Version {'9.4'},if (exists($DE/moles:dgMetadataProvenance/moles:RecordCreation)) then  element DIF_Creation_Date {data($DE/moles:dgMetadataProvenance/moles:RecordCreation/moles:CreatedDate)} else (),for $MDUpdt in $DE/moles:dgMetadataProvenance/moles:RecordUpdate return  element DIF_Revision_History {concat(data($MDUpdt/moles:UpdateDate), ' - ', data($MDUpdt/moles:UpdateSummary), ' - ', data($MDUpdt/moles:UpdatedBy))},if (exists($DE/moles:dgMetadataProvenance/moles:RecordReview)) then  element Future_DIF_Review_Date {data($DE/moles:dgMetadataProvenance/moles:RecordReview/moles:ReviewDate)} else ()}"; 
     215                                        String xqueryStr = "declare default element namespace 'http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/';declare namespace dummy='http://ndg.nerc.ac.uk/dummy';declare namespace xsi='http://www.w3.org/2001/XMLSchema-instance';declare namespace moles='http://ndg.nerc.ac.uk/moles';declare namespace f='http://ndg.nerc.ac.uk/moles/localfunctions'; declare function local:docExists($coll as xs:string, $doc as xs:string) as item()* { let $testset := collection($coll)//root()  let $matches :=   for $i in $testset  where util:document-name($i) = $doc  return  document-uri($i)  return $matches  }; let $i := local:docExists('/db/discovery/original/"+this.format+"', '"+thisdoc+"')return if ( fn:empty($i) ) then ( for $DE in collection('/db/discovery/moles')/moles:dgMetadata/moles:dgMetadataRecord[exists('moles:dgDataEntity')  and moles:dgMetadataID/moles:schemeIdentifier='NDG-B0'] where util:document-name($DE)='"+thisdoc+"' return element dummy:container { element DIF {attribute xsi:schemaLocation {'http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/ http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/dif_v9.4.xsd'},element Entry_ID {concat($DE/moles:dgMetadataID/moles:repositoryIdentifier, ':DIF:', $DE/moles:dgMetadataID/moles:localIdentifier)},element Entry_Title {string($DE/moles:name)},element Data_Set_Citation {for $DataCreatorRole in $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:dgRoleHolder[not(exists(moles:endDate)) or moles:endDate=''][1] return  for $DataCreatorRoleHolder in collection('/db/discovery/moles')/moles:dgMetadata/*[(moles:dgMetadataID/moles:schemeIdentifier='NDG-B0' and moles:dgMetadataID/moles:repositoryIdentifier=$DataCreatorRole/*/moles:repositoryIdentifier and moles:dgMetadataID/moles:localIdentifier=$DataCreatorRole/*/moles:localIdentifier)] return  element Data_Creator {if (exists($DataCreatorRoleHolder/moles:name/moles:initials)) then  string(concat(string($DataCreatorRoleHolder/moles:name/moles:initials), ' ', string($DataCreatorRoleHolder/moles:name/moles:familyName))) else  string($DataCreatorRoleHolder/moles:abbreviation)},element Dataset_Title {string($DE/moles:name)}},for $StructuredKeyword in ($DE//(moles:dgStructuredKeyword | moles:dgStdParameterMeasured)[moles:dgValidTermID/moles:ParentListID='http://gcmd.gsfc.nasa.gov/Resources/valids/gcmd_parameters.html' and moles:ListLevel = 0]) return if (exists($StructuredKeyword/*/moles:dgValidTerm)) then  element Parameters {element Category {string($StructuredKeyword/*/moles:dgValidTerm)},if (exists($StructuredKeyword//moles:dgValidSubterm)  and $StructuredKeyword//moles:dgValidSubterm != ''  and $StructuredKeyword//moles:dgValidSubterm != ' ') then  for $Subterm in $StructuredKeyword//moles:dgValidSubterm[exists(moles:dgValidTerm)] where exists($Subterm/moles:dgValidSubterm) order by $Subterm/moles:ListLevel return  if ($Subterm/moles:ListLevel=1) then element Topic {string($Subterm/moles:dgValidSubterm/moles:dgValidTerm)}  else if ($Subterm/moles:ListLevel=2) then element Term {string($Subterm/moles:dgValidSubterm/moles:dgValidTerm)}  else if ($Subterm/moles:ListLevel=3) then element Variable {string($Subterm/moles:dgValidSubterm/moles:dgValidTerm)}  else if ($Subterm/moles:ListLevel=4) then element Detailed_Variable {string($Subterm/moles:dgValidSubterm/moles:dgValidTerm)}  else element GCMD_Science_Valid {string($Subterm/moles:dgValidSubterm/moles:dgValidTerm)} else()} else(),for $ISOTopicCategory in ($DE/moles:dgStructuredKeyword[moles:dgValidTermID/moles:ParentListID='http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_TopicCategoryCode']) return  element ISO_Topic_Category {string($ISOTopicCategory/moles:dgValidTerm)},for $Keyword in distinct-values($DE//moles:dgStructuredKeyword[ moles:dgValidTermID/moles:ParentListID!='http://gcmd.gsfc.nasa.gov/Resources/valids/gcmd_parameters.html'  and  moles:dgValidTermID/moles:ParentListID!='http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_TopicCategoryCode'  ]/moles:dgValidTerm) return element Keyword {string($Keyword)},  for $DepDPT in ($DE/moles:dgDataEntity/moles:RelatedDeployment/moles:DataProductionToolID)  return  element Sensor_Name {for $DepDPTAbbrev in distinct-values((collection('/db/discovery/moles')/moles:dgMetadata/moles:dgMetadataRecord[moles:dgMetadataID[moles:schemeIdentifier='NDG-B0' and moles:repositoryIdentifier=$DepDPT/moles:repositoryIdentifier and moles:localIdentifier=$DepDPT/moles:localIdentifier]]/moles:abbreviation)) return element Short_Name {data($DepDPTAbbrev)},for $DepDPTName in distinct-values((collection('/db/discovery/moles')/moles:dgMetadata/moles:dgMetadataRecord[moles:dgMetadataID[moles:schemeIdentifier='NDG-B0' and moles:repositoryIdentifier=$DepDPT/moles:repositoryIdentifier and moles:localIdentifier=$DepDPT/moles:localIdentifier]]/moles:name)) return element Long_Name {data($DepDPTName)}},for $DepObsStn in ($DE/moles:dgDataEntity/moles:RelatedDeployment/moles:ObservationStationID) return  element Source_Name {for $DepObsStnAbbrev in distinct-values((collection('/db/discovery/moles')/moles:dgMetadata/moles:dgMetadataRecord[moles:dgMetadataID[moles:schemeIdentifier='NDG-B0' and moles:repositoryIdentifier=$DepObsStn/moles:repositoryIdentifier and moles:localIdentifier=$DepObsStn/moles:localIdentifier]]/moles:abbreviation)) return element Short_Name {data($DepObsStnAbbrev)},for $DepObsStnName in distinct-values((collection('/db/discovery/moles')/moles:dgMetadata/moles:dgMetadataRecord[moles:dgMetadataID[moles:schemeIdentifier='NDG-B0' and moles:repositoryIdentifier=$DepObsStn/moles:repositoryIdentifier and moles:localIdentifier=$DepObsStn/moles:localIdentifier]]/moles:name)) return element Long_Name {data($DepObsStnName)}},for $TemporalRange in ($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataCoverage//moles:dgDateRange) return  element Temporal_Coverage {element Start_Date {data($TemporalRange/moles:DateRangeStart)},element End_Date {data($TemporalRange/moles:DateRangeEnd)}},for $TemporalTerm in ($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataCoverage//moles:dgArea/moles:dgValidTerm) return element Paleo_Temporal_Coverage {element Chronostratigraphic_Unit {data($TemporalTerm)}},  for $Data_Set_Progress in ($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataStatus/moles:dgDatasetClosure) return element Data_Set_Progress {data($Data_Set_Progress)},for $BoundingBox in ($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataCoverage//moles:BoundingBox) return  element Spatial_Coverage {element Southernmost_Latitude {data($BoundingBox/moles:LimitSouth)},element Northernmost_Latitude {data($BoundingBox/moles:LimitNorth)},element Westernmost_Longitude {data($BoundingBox/moles:LimitWest)},element Easternmost_Longitude {data($BoundingBox/moles:LimitEast)}},for $Location in ($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDataCoverage//moles:dgArea[moles:dgValidTermID/moles:ParentListID='http://gcmd.gsfc.nasa.gov/Resources/valids/gcmd_locations.html']) return element Location {$Location},  for $DepAct in ($DE/moles:dgDataEntity/moles:RelatedDeployment/moles:ActivityID) return  element Project {for $DepActAbbrev in distinct-values(collection('/db/discovery/moles')/moles:dgMetadata/moles:dgMetadataRecord[moles:dgMetadataID[moles:schemeIdentifier='NDG-B0' and moles:repositoryIdentifier=$DepAct/moles:repositoryIdentifier and moles:localIdentifier=$DepAct/moles:localIdentifier]]/moles:abbreviation) return  element Short_Name {data($DepActAbbrev)},for $DepActName in distinct-values(collection('/db/discovery/moles')/moles:dgMetadata/moles:dgMetadataRecord[moles:dgMetadataID[moles:schemeIdentifier='NDG-B0' and moles:repositoryIdentifier=$DepAct/moles:repositoryIdentifier and moles:localIdentifier=$DepAct/moles:localIdentifier]]/moles:name) return  element Long_Name {data($DepActName)}},if (exists($DE/moles:dgDataEntity/moles:dgDataGranule/moles:accessControlPolicy)) then  for $DG in $DE/moles:dgDataEntity/moles:dgDataGranule return  element Access_Constraints {if (exists($DG/moles:dgGranuleSummary/moles:dgGranuleName)) then  concat('For data granule ', $DG/moles:dgGranuleSummary/moles:dgGranuleName, ': ') else (),if (exists($DG/moles:accessControlPolicy/moles:accessControlPolicyURL)) then concat('See access control policy at ', escape-uri($DG/moles:accessControlPolicy/moles:accessControlPolicyURL, true())) else if (exists($DG/moles:accessControlPolicy/moles:accessControlPolicyText)) then data($DG/moles:accessControlPolicy/moles:accessControlPolicyText) else  for $securityCondition in $DG/moles:accessControlPolicy/moles:dgSecurityCondition return if (exists($securityCondition/moles:conditionExplanationText)) then concat('Effect: ', data($securityCondition/moles:effect), ' - ', data($securityCondition/moles:conditionExplanationText)) else concat('Effect: ', data($securityCondition/moles:effect), 'needs ', data($securityCondition/moles:attauthRole), ' from ', data($securityCondition/moles:dgAttributeAuthority))} else (),if (exists($DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:dgRoleHolder)) then for $DataCreatorRole in $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCreator/moles:dgRoleHolder  order by $DataCreatorRole/moles:startDate empty least return  for $DataCreatorRoleHolder in collection('/db/discovery/moles')/moles:dgMetadata/(moles:dgOrganisation | moles:dgPerson) [(moles:dgMetadataID/moles:schemeIdentifier='NDG-B0' and moles:dgMetadataID/moles:repositoryIdentifier=$DataCreatorRole/(moles:dgOrganisationID | moles:dgPersonID)/moles:repositoryIdentifier and moles:dgMetadataID/moles:localIdentifier=$DataCreatorRole/(moles:dgOrganisationID | moles:dgPersonID)/moles:localIdentifier)] return  element Originating_Center {if (string(local-name($DataCreatorRoleHolder))='dgOrganisation') then (string($DataCreatorRoleHolder/moles:name)) else if (string(local-name($DataCreatorRoleHolder))='dgPerson') then (string(concat(string($DataCreatorRoleHolder/moles:name/moles:initials), ' ', string($DataCreatorRoleHolder/moles:name/moles:familyName)))) else ('empty content')} else (),for $DataCuratorRole in $DE/moles:dgDataEntity/moles:dgDataRoles/moles:dgDataCurator/moles:dgRoleHolder[not(exists(moles:endDate)) or moles:endDate=''] return  for $DataCuratorRoleHolder in collection('/db/discovery/moles')/moles:dgMetadata/*[(moles:dgMetadataID/moles:schemeIdentifier='NDG-B0' and moles:dgMetadataID/moles:repositoryIdentifier=$DataCuratorRole/*/moles:repositoryIdentifier and moles:dgMetadataID/moles:localIdentifier=$DataCuratorRole/*/moles:localIdentifier)] return  element Data_Center {element Data_Center_Name {element Short_Name {if (exists($DataCuratorRoleHolder/moles:name/moles:initials)) then  string(concat(string($DataCuratorRoleHolder/moles:name/moles:initials), ' ', string($DataCuratorRoleHolder/moles:name/moles:familyName))) else  string($DataCuratorRoleHolder/moles:abbreviation)},element Long_Name {if (exists($DataCuratorRoleHolder/moles:name/moles:initials)) then  string(concat(string($DataCuratorRoleHolder/moles:name/moles:initials), ' ', string($DataCuratorRoleHolder/moles:name/moles:familyName))) else string($DataCuratorRoleHolder/moles:name)}},if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:URI)) then  element Data_Center_URL {data($DataCuratorRoleHolder/moles:contactDetails/moles:URI)} else (),for $DGID in $DE/moles:dgDataEntity/moles:dgDataGranule/moles:dataModelID return  element Data_Set_ID {concat($DGID/moles:repositoryIdentifier, ':', $DGID/moles:schemeIdentifier, ':', $DGID/moles:localIdentifier)},element Personnel {element Role {'Data Center Contact'},if (exists($DataCuratorRoleHolder/name/knownAs)) then  element First_Name {string($DataCuratorRoleHolder/moles:name/moles:knownAs)} else if (exists($DataCuratorRoleHolder/moles:name/moles:initials)) then  element First_Name {string($DataCuratorRoleHolder/moles:name/moles:initials)} else (),element Last_Name {if (exists($DataCuratorRoleHolder/moles:name/moles:familyName)) then  string($DataCuratorRoleHolder/moles:name/moles:familyName) else string($DataCuratorRoleHolder/moles:name)},if (exists($DataCuratorRole/moles:contactDetails/moles:eMail)) then  element Email {string($DataCuratorRole/moles:contactDetails/moles:eMail)} else  if (exists($DataCuratorRoleHolder/contactDetails/eMail)) then  (element Email {string($DataCuratorRoleHolder/moles:contactDetails/moles:eMail)}) else (),if (exists($DataCuratorRole/moles:contactDetails/moles:telephone)) then  element Phone {string($DataCuratorRole/moles:contactDetails/moles:telephone)} else if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:telephone)) then  element Phone {string($DataCuratorRoleHolder/moles:contactDetails/moles:telephone)} else (),if (exists($DataCuratorRole/moles:contactDetails/moles:fax)) then  element Fax {string($DataCuratorRole/moles:contactDetails/moles:fax)} else if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:fax)) then  element Fax {string($DataCuratorRoleHolder/moles:contactDetails/moles:fax)} else (),if (exists($DataCuratorRole/moles:contactDetails/moles:address)) then  element Contact_Address {for $addressline in $DataCuratorRole/moles:contactDetails/moles:address/moles:addressline return element address {data($addressline)},if (exists($DataCuratorRole/moles:contactDetails/moles:address/moles:city)) then  element City {string($DataCuratorRole/moles:contactDetails/moles:address/moles:city)} else (),if (exists($DataCuratorRole/moles:contactDetails/moles:address/moles:postcode)) then  element Postal_Code {string($DataCuratorRole/moles:contactDetails/moles:address/moles:postcode)} else (),if (exists($DataCuratorRole/moles:contactDetails/moles:address/moles:country)) then  element Country {string($DataCuratorRole/moles:contactDetails/moles:address/moles:country)} else ()} else if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:address)) then  element Contact_Address {for $addressline in $DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:addressline return element address {data($addressline)},if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:city)) then  element City {string($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:city)} else (),if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:postcode)) then  element Postal_Code {string($DataCuratorRole/moles:contactDetails/moles:postcode)} else (),if (exists($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:country)) then  element Country {string($DataCuratorRoleHolder/moles:contactDetails/moles:address/moles:country)} else ()} else ()}},element Summary {string($DE/moles:dgMetadataDescription/moles:abstract/moles:abstractText)},element Related_URL {element URL_Content_Type {'NDG_B_SERVICE'},element URL {data($DE/moles:dgMetadataID/moles:repositoryIdentifier)},element Description {'The NDG service for browsing metadata.'}},for $DG in $DE/moles:dgDataEntity/moles:dgDataGranule return if ($DG/moles:dataModelID/moles:schemeIdentifier='NDG-A0') then  (element Related_URL {element URL_Content_Type {'NDG_A_SERVICE'},if (exists($DG/instance/URI)) then element URL {escape-uri($DG/instance/URI, true())} else if ($DG/moles:dataModelID/moles:repositoryIdentifier='badc.nerc.ac.uk') then element URL {escape-uri('http://dmgdev1.esc.rl.ac.uk/cgi-bin/ndgDataAccess?datasetSource=dmgdev1.esc.rl.ac.uk&amp;datasetID=', true())} else ($DG/moles:dataModelID/moles:repositoryIdentifier),element Description {'The NDG service delivering data via NDG A metadata.'}},element Related_URL {element URL_Content_Type {'GET DATA > CSML'},if (exists($DG/instance)) then element URL {escape-uri($DG/instance/URI, true())} else if ($DG/moles:dataModelID/moles:repositoryIdentifier='badc.nerc.ac.uk') then element URL {escape-uri('http://dmgdev1.esc.rl.ac.uk/cgi-bin/ndgDataAccess?datasetSource=dmgdev1.esc.rl.ac.uk&amp;datasetID=', true())} else (),element Description {'The NDG service delivering data via NDG A metadata. Additional tag to be more in line with latest version of GCMD valids'}}) else if ($DG/moles:dataModelID/moles:schemeIdentifier='CDML-0') then  (element Related_URL {  element URL_Content_Type {'NDG_A_SERVICE'},if (exists($DG/instance)) then element URL {escape-uri($DG/instance/URI, true())} else if ($DG/moles:dataModelID/moles:repositoryIdentifier='badc.nerc.ac.uk') then element URL {escape-uri('http://cdat.badc.nerc.ac.uk/cgi-bin/dxui.py?datasetURI_1=/', true())} else (),element Description {'The NDG service delivering data via Data extractor. Additional tag to be more in line with latest version of GCMD valids'}},element Related_URL {element URL_Content_Type {'GET DATA > DX'},if (exists($DG/instance)) then element URL {escape-uri($DG/instance/URI, true())} else if ($DG/moles:dataModelID/moles:repositoryIdentifier='badc.nerc.ac.uk') then element URL {escape-uri('http://cdat.badc.nerc.ac.uk/cgi-bin/dxui.py?datasetURI_1=/', true())} else (),element Description {'The NDG service delivering data via Data extractor. Additional tag to be more in line with latest version of GCMD valids'}}) else if ($DG/moles:dataModelID/moles:schemeIdentifier='URI') then  element Related_URL {element URL {data($DG/moles:instance/moles:URI)},if (exists($DG/moles:instance/moles:instanceComment)) then  element Description {data($DG/moles:instance/moles:instanceComment)}  else  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.'}} else (),for $RelURL_Desc in ($DE/moles:dgMetadataDescription/moles:descriptionSection/moles:descriptionOnlineReference)  return element Related_URL {element URL {data($RelURL_Desc)},element Description {concat(data($RelURL_Desc/moles:name), ' - ', data($RelURL_Desc/moles:notes))} },element Metadata_Name {'[CEOS IDN DIF]'},element Metadata_Version {'9.4'},if (exists($DE/moles:dgMetadataProvenance/moles:RecordCreation)) then  element DIF_Creation_Date {data($DE/moles:dgMetadataProvenance/moles:RecordCreation/moles:CreatedDate)} else (),for $MDUpdt in $DE/moles:dgMetadataProvenance/moles:RecordUpdate return  element DIF_Revision_History {concat(data($MDUpdt/moles:UpdateDate), ' - ', data($MDUpdt/moles:UpdateSummary), ' - ', data($MDUpdt/moles:UpdatedBy))},if (exists($DE/moles:dgMetadataProvenance/moles:RecordReview)) then  element Future_DIF_Review_Date {data($DE/moles:dgMetadataProvenance/moles:RecordReview/moles:ReviewDate)} else ()} } ) else ( element dummy:container { doc(fn:item-at($i, 1)) } )"; 
    229216 
    230217                                        queryParams.addElement( xqueryStr.getBytes("UTF-8") );  
     
    239226 
    240227                                        byte[] resultByteArray = (byte[])xmlrpc.execute( "query", queryParams ); 
    241  
    242228                                        ByteArrayInputStream resultStream = new ByteArrayInputStream( resultByteArray ); 
     229 
    243230 
    244231                                        SAXBuilder builder = new SAXBuilder(); 
    245232                                        org.jdom.Document doc = builder.build( resultStream ); 
    246233                                        org.jdom.Element root = doc.getRootElement(); 
    247                                         org.jdom.Element elem = root.getChild("DIF", Namespace.getNamespace("http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/") ); 
     234                                        org.jdom.Element container = root.getChild("container", Namespace.getNamespace("dummy","http://ndg.nerc.ac.uk/dummy")); 
     235                                        org.jdom.Element elem = container.getChild("DIF", Namespace.getNamespace("http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/") ); 
    248236 
    249237                                        //  Use XMLOutputter 
     
    266254                                        //1. Check to see if a dc-format document exists for this name 
    267255                                        Vector queryParams = new Vector(); 
    268                                         String xqueryStr = "declare default element namespace 'http://www.dassh.ac.uk';declare namespace moles='http://ndg.nerc.ac.uk/moles';declare namespace gco='http://www.isotc211.org/2005/gco';declare namespace xsi='http://www.w3.org/2001/XMLSchema-instance'; declare namespace f='http://ndg.nerc.ac.uk/moles/localfunctions';declare variable $ISO_639-2_ns as xs:string{'UKGemini_Langauge_Categories'};declare variable $ISO_3166_ns as xs:string{'UKGemini_Land_Area_Categories'};for $DE in collection('/db/discovery/moles')/moles:dgMetadata/moles:dgMetadataRecord[ exists('moles:dgDataEntity')    and moles:dgMetadataID/moles:schemeIdentifier='NDG-B0'] where util:document-name($DE)='"+thisdoc+"' return element Metadata {   element Title {data($DE/moles:name)},   if (exists($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDatasetLanguage)) then            for $lang in $DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDatasetLanguage         return                  element Language{                               element LanguageName {data($lang/dgValidTerm)},                         element LanguageVocab {data($lang/dgValidTermID/ParentListID)},                         element LanguageCode {data($lang/dgValidTermID/TermID)}                 }                                       else (),        element Abstract {},    for $isoTopic in $DE/moles:dgStructuredKeyword[moles:dgValidTermID/moles:ParentListID='']       return element TopicCategory {},        for $subject in $DE/moles:dgDataEntity/moles:dgParameterSummary/moles:dgStdParameterMeasured[moles:dgValidTermID/moles:ParentListID=''] return element Subject {},      element Date {          element DatasetStartDate {},            element DatasetEndDate {}       }}"; 
     256                                        String xqueryStr = "declare default element namespace 'http://www.dassh.ac.uk';declare namespace dummy='http://ndg.nerc.ac.uk/dummy';declare namespace moles='http://ndg.nerc.ac.uk/moles';declare namespace gco='http://www.isotc211.org/2005/gco';declare namespace xsi='http://www.w3.org/2001/XMLSchema-instance'; declare namespace f='http://ndg.nerc.ac.uk/moles/localfunctions';declare variable $ISO_639-2_ns as xs:string{'UKGemini_Langauge_Categories'};declare variable $ISO_3166_ns as xs:string{'UKGemini_Land_Area_Categories'}; declare function local:docExists($coll as xs:string, $doc as xs:string) as item()* { let $testset := collection($coll)//root()  let $matches :=   for $i in $testset  where util:document-name($i) = $doc  return  document-uri($i)  return $matches  }; let $i := local:docExists('/db/discovery/original/"+this.format+"', '"+thisdoc+"') return if ( fn:empty($i) ) then ( for $DE in collection('/db/discovery/moles')/moles:dgMetadata/moles:dgMetadataRecord[    exists('moles:dgDataEntity')    and moles:dgMetadataID/moles:schemeIdentifier='NDG-B0'] where util:document-name($DE)='"+thisdoc+"' return element dummy:container { element Metadata { element Title {data($DE/moles:name)},   if (exists($DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDatasetLanguage)) then            for $lang in $DE/moles:dgDataEntity/moles:dgDataSummary/moles:dgDatasetLanguage         return                  element Language{                               element LanguageName {data($lang/dgValidTerm)},                         element LanguageVocab {data($lang/dgValidTermID/ParentListID)},                         element LanguageCode {data($lang/dgValidTermID/TermID)}                 }                                       else (),        element Abstract {},    for $isoTopic in $DE/moles:dgStructuredKeyword[moles:dgValidTermID/moles:ParentListID='']       return element TopicCategory {},        for $subject in $DE/moles:dgDataEntity/moles:dgParameterSummary/moles:dgStdParameterMeasured[moles:dgValidTermID/moles:ParentListID=''] return element Subject {},      element Date {          element DatasetStartDate {},            element DatasetEndDate {}       }} } ) else ( element dummy:container { doc(fn:item-at($i, 1)) } )"; 
    269257 
    270258                                        queryParams.addElement( xqueryStr.getBytes("UTF-8") );  
     
    279267 
    280268                                        byte[] resultByteArray = (byte[])xmlrpc.execute( "query", queryParams ); 
    281                                         System.out.println( new String( resultByteArray ) ); 
    282  
    283269                                        ByteArrayInputStream resultStream = new ByteArrayInputStream( resultByteArray ); 
     270 
     271                                        //  Use XMLOutputter 
     272                                        XMLOutputter out = new XMLOutputter (); 
     273                                        out.setFormat( Format.getCompactFormat() ); // UTF-8 & trimming of whitespace 
    284274 
    285275                                        SAXBuilder builder = new SAXBuilder(); 
    286276                                        org.jdom.Document doc = builder.build( resultStream ); 
    287277                                        org.jdom.Element root = doc.getRootElement(); 
    288                                         org.jdom.Element elem = root.getChild("Metadata", Namespace.getNamespace("mdip","http://www.dassh.ac.uk") ); 
    289  
    290                                         //  Use XMLOutputter 
    291                                         XMLOutputter out = new XMLOutputter (); 
    292                                         out.setFormat( Format.getCompactFormat() ); // UTF-8 & trimming of whitespace 
     278                                        org.jdom.Element container = root.getChild("container", Namespace.getNamespace("dummy","http://ndg.nerc.ac.uk/dummy")); 
     279                                        org.jdom.Element elem = container.getChild("Metadata", Namespace.getNamespace("http://www.dassh.ac.uk")); 
     280 
    293281                                        returnDoc = out.outputString( elem ); 
    294282 
     
    300288                                        } 
    301289                                        else { 
    302                                                 throw new Exception("Unable to create MOLES format document"); 
     290                                                throw new Exception("Unable to create MDIP format document"); 
    303291                                        }                                                
    304292                                } 
     
    320308        } 
    321309 
    322         public class existNamespaceContextImpl implements NamespaceContext 
    323     { 
    324         public String getNamespaceURI(String prefix) 
    325         { 
    326                         return "http://exist.sourceforge.net/NS/exist"; 
    327         } 
    328       
    329                 // Doesn't matter what the prefix in the source doc is, override it 
    330                 // Important thing is that the namespace URI matches, and that 
    331                 // whatever prefix is set here, is used in the xpath query 
    332         public String getPrefix(String namespace) 
    333         { 
    334                         return "exist"; 
    335         } 
    336  
    337         public Iterator getPrefixes(String namespace) 
    338         { 
    339             return null; 
    340         } 
    341     }  
    342  
    343  
    344310} 
    345311 
Note: See TracChangeset for help on using the changeset viewer.