Can edit Conceptual Domain and delete meanings etc.

xquery version "1.0";

(: ~
 : Module Name:             edit Conceptual Domain webpage and XQuery
 :
 : Module Version           3.0
 :
 : Date                     26th Aug 2009
 :
 : Copyright                The cagrid consortium
 :
 : Module overview          Edit Conceptual Domain
 :
 :)

(:~
 :    @author Steve Harris
 :    @version 0.1
 :
 :    @author Steve Harris
 :    @version 2.0
 :     now allows searching for concept terms
 :
 :    @author Rakesh Dhaval
 :    @version 3.0
 :    allows editing the DataElementConcept
~ :)

  import module namespace
  lib-forms="http://www.cagrid.org/xquery/library/forms"
  at "../edit/m-lib-forms.xquery";

  import module namespace
  lib-util="http://www.cagrid.org/xquery/library/util"
  at "../library/m-lib-util.xquery";

  import module namespace
  lib-rendering="http://www.cagrid.org/xquery/library/rendering"
  at "../web/m-lib-rendering.xquery";

  import module namespace
  lib-make-admin-item="http://www.cagrid.org/xquery/library/make-admin-item"
  at "../edit/m-lib-make-admin-item.xquery";

import module namespace
   administered-item="http://www.cagrid.org/xquery/library/administered-item"
   at "../library/m-administered-item.xquery";

import module namespace
    lib-uri-resolution="http://www.cagrid.org/xquery/library/resolver"
    at "../resolver/m-lib-uri-resolution.xquery";

declare namespace openMDR = "http://www.cagrid.org/schema/openMDR";
declare namespace ISO11179= "http://www.cagrid.org/schema/ISO11179";
declare namespace session="http://exist-db.org/xquery/session";
declare namespace response="http://exist-db.org/xquery/response";
declare namespace exist = "http://exist.sourceforge.net/NS/exist";
declare namespace util="http://exist-db.org/xquery/util";

declare function local:conceptual-domain(
   $id as xs:string,
   $reg-auth as xs:string,
   $administrative-note as xs:string,
   $administrative-status as xs:string,
   $administered-by as xs:string,
   $submitted-by as xs:string,
   $registered-by as xs:string,
   $context-ids as xs:string*,
   $country-identifiers as xs:string*,
   $language-identifiers as xs:string*,
   $names as xs:string*,
   $definitions as xs:string*,
   $sources as xs:string*,
   $preferred as xs:string?,
   $value_meaning_begin_date as xs:string?,
   $meanings as xs:string*
   ) as xs:boolean
{
   let $version := lib-forms:substring-after-last($id,'-')
   let $vmid := substring-after(lib-forms:substring-before-last($id,'-'),'-')
   let $data-identifier := substring-after(lib-forms:substring-before-last($id,'-'),'-')

   let $doc-name := concat($id,'.xml')

   let $content := (
                    lib-make-admin-item:administration-record($administrative-note,$administrative-status,'Recorded'),
                    lib-make-admin-item:custodians($administered-by,$registered-by,$submitted-by),
                    lib-make-admin-item:havings(
                    $context-ids,
                    $country-identifiers,
                    $language-identifiers,
                    $names,
                    $definitions,
                    $preferred,
                    $sources),
                    for $meaning at $pos in $meanings
                    return
                    if($meaning >'') then
                       element openMDR:Value_Meaning
                       {
                        element openMDR:value_meaning_begin_date {$value_meaning_begin_date},
                        element openMDR:value_meaning_description {$meaning},
                        element openMDR:value_meaning_identifier {$vmid}
                       }
                       else()
                    )

   (: compose the document :)
   let $document := (
       if($meanings > '') then (
          element openMDR:Enumerated_Conceptual_Domain {
                attribute item_registration_authority_identifier {$reg-auth},
                attribute data_identifier {$data-identifier},
                attribute version {$version},
                $content
               }
      ) else (
          element openMDR:Non_Enumerated_Conceptual_Domain {
                attribute item_registration_authority_identifier {$reg-auth},
                attribute data_identifier {$data-identifier},
                attribute version {$version},
                $content
               }
      )
   )

   let $collection := 'conceptual-domain'
   let $message := lib-forms:store-document($document)
   return
      if ($message='stored')
      then true()
      else response:redirect-to(xs:anyURI(concat("../web/login.xquery?calling_page=editConceptualDomain.xquery&",$message)))
};

declare function local:input-page(
   $message as xs:string?,
   $id as xs:string?,
   $reg-auth as xs:string?,
   $administrative-note  as xs:string?,
   $administrative-status  as xs:string?,
   $administered-by  as xs:string?,
   $submitted-by  as xs:string?,
   $registered-by  as xs:string?,
   $context-ids  as xs:string*,
   $country-identifiers as xs:string*,
   $language-identifiers as xs:string*,
   $names as xs:string*,
   $definitions as xs:string*,
   $sources as xs:string*,
   $action as xs:string?,
   $preferred as xs:string?,
   $value_meaning_begin_date as xs:string?,
   $meanings as xs:string*
   )
   {
       let $skip-name := substring-after($action,'delete naming entry')
       let $skip-name-index := if ($skip-name>'') then xs:int($skip-name) else 0

       let $skip-uri := substring-after($action,'delete value meaning')
       let $skip-uri-index := if ($skip-uri>'') then xs:int($skip-uri) else 0

    return

                This form will allow you to Edit Conceptual Domain in the metadata repository

          <form name="edit_conceptual_domain" action="editConceptualDomain.xquery" method="post" class="cagridForm" enctype="multipart/form-data">

             {lib-forms:hidden-element('id',$id)}
             {lib-forms:hidden-element('updating','updating')}
             {lib-forms:edit-admin-item($reg-auth,
                     $administrative-note,
                     $administrative-status,
                     $administered-by,
                     $submitted-by,
                     $registered-by,
                     $context-ids,
                     $country-identifiers,
                     $language-identifiers,
                     $names,
                     $definitions,
                     $sources,
                     $preferred,
                     $action)}

Conceptual Domain

                {

                    if(exists($meanings))
                    then (

Enumerated Conceptual Domain?
                      <input type="radio" name="conceptual-domain-type" value="enumerated" checked="checked">enumerated</input>
                      <input type="radio" name="conceptual-domain-type" value="non-enumerated">non-enumerated</input>
                      {lib-forms:action-button('update', 'action' ,'')}

,

Conceptual Domain Meanings
,

                      Value Domain Meanings	meaning

,

                       for $meaning  at $pos in $meanings
                       let $location := if($pos > $skip-uri-index and $skip-uri-index > 0) then (util:eval($pos - 1)) else ($pos)
                        where $pos != $skip-uri-index and $meaning > ""
                        return (

                              Value {$location} Meaning
                              {lib-forms:input-element('meanings', 60, $meaning)}
                              {lib-forms:action-button(concat('delete value meaning ',$location), 'action' ,'')}

                           ),

                              New Value Meaning
                              {lib-forms:input-element('meanings', 60, '')}
                              {lib-forms:action-button('add new value meaning', 'action' ,'')}

                    )
                    else
                    (

Enumerated Conceptual Domain?
                           <input type="radio" name="conceptual-domain-type" value="enumerated" >enumerated</input>
                           <input type="radio" name="conceptual-domain-type" value="non-enumerated" checked="checked">non-enumerated</input>
                           {lib-forms:action-button('update', 'action' ,'')}

                    )
              }

Store

                         <input type="submit" name="update" value="Store Changes"/>	<input type="submit" name="update" value="Clear"/>

          </form>

{$message}

   };

declare function local:success-page()
{
   let $calling-page := request:get-parameter("calling-page","")
   return

Conceptual Domain modified

Return to maintenance menu

Create another Conceptual Domain

};

declare option exist:serialize "media-type=text/html method=xhtml doctype-public=-//W3C//DTD XHTML 1.0 Transitional//EN doctype-system=http://www.w3.org/TR/2002/REC-xhtml1-20020801/DTD/xhtml1-transitional.dtd";

   session:create(),
   let $id := request:get-parameter('id','')
   let $updating := request:get-parameter('updating','')
   let $title as xs:string := concat("Editing Conceptual Domain ", $id)
   let $element := lib-util:mdrElement("conceptual_domain",$id)
   let $action := request:get-parameter('update','')

   let $ireg-auth := string($element/@item_registration_authority_identifier)
   let $iadministrative-note := string($element//openMDR:administrative_note)
   let $iadministrative-status := string($element//openMDR:administrative_status)
   let $iadministered-by := string($element//openMDR:administered_by)
   let $isubmitted-by := string($element//openMDR:submitted_by)
   let $iregistered-by := string($element//openMDR:registered_by)
   let $icontext-ids := $element//openMDR:context_identifier
   let $icountry-identifiers := $element//openMDR:country_identifier
   let $ilanguage-identifiers := $element//openMDR:language_identifier
   let $inames := $element//openMDR:name
   let $idefinitions := $element//openMDR:definition_text
   let $isources := $element//openMDR:definition_source_reference
   let $ipreferred := string(fn:index-of($element//openMDR:preferred_designation,'true'))
   let $imeanings := $element//openMDR:value_meaning_description
   let $log := util:log-system-err($imeanings)

   let $begins := $element//openMDR:value_meaning_begin_date/text()
   let $log := util:log-system-err($begins)

   let $ends := $element//openMDR:value_meaning_end_date/text()
   let $ivalue_meaning_begin_date := $element//openMDR:ivalue_meaning_begin_date

   let $reg-auth := request:get-parameter('registration-authority','')
   let $administrative-note := request:get-parameter('administrative-note','')
   let $administrative-status := request:get-parameter('administrative-status','')
   let $administered-by := request:get-parameter('administered-by','')
   let $submitted-by := request:get-parameter('submitted-by','')
   let $registered-by := request:get-parameter('registered-by','')
   let $context-ids := request:get-parameter('context-ids',())
   let $country-identifiers := request:get-parameter('country-identifiers',())
   let $language-identifiers := request:get-parameter('language-identifiers',())
   let $names := request:get-parameter('names',())
   let $definitions := request:get-parameter('definitions',())
   let $sources := request:get-parameter('sources',())
   let $preferred := request:get-parameter('preferred','')
   let $value_meaning_begin_date := request:get-parameter('value_meaning_begin_date','')
   let $meanings := request:get-parameter('meanings','')
   return

      lib-rendering:txfrm-webpage(
      $title,
      if ($action='Store Changes')
      then
         (
         if (
               local:conceptual-domain
                  (
                     $id,
                     $reg-auth,
                     $administrative-note,
                     $administrative-status,
                     $administered-by,
                     $submitted-by,
                     $registered-by,
                     $context-ids,
                     $country-identifiers,
                     $language-identifiers,
                     $names,
                     $definitions,
                     $sources,
                     $preferred,
                     $value_meaning_begin_date,
                     $meanings
                  )
            )
         then (local:success-page())
         else (local:input-page(
            'could not store document',
                     $id,
                     $reg-auth,
                     $administrative-note,
                     $administrative-status,
                     $administered-by,
                     $submitted-by,
                     $registered-by,
                     $context-ids,
                     $country-identifiers,
                     $language-identifiers,
                     $names,
                     $definitions,
                     $sources,
                     $action,
                     $preferred,
                     $value_meaning_begin_date,
                     $meanings
                  )
               )
         )
      else (
         if ($updating ='updating')
         then (
            local:input-page
               (
               '',
               $id,
               $reg-auth,
               $administrative-note,
               $administrative-status,
               $administered-by,
               $submitted-by,
               $registered-by,
               $context-ids,
               $country-identifiers,
               $language-identifiers,
               $names,
               $definitions,
               $sources,
               $action,
               $preferred,
               $value_meaning_begin_date,
               $meanings
               )
         ) else (
               local:input-page
               (
               '',
               $id,
               $ireg-auth,
               $iadministrative-note,
               $iadministrative-status,
               $iadministered-by,
               $isubmitted-by,
               $iregistered-by,
               $icontext-ids,
               $icountry-identifiers,
               $ilanguage-identifiers,
               $inames,
               $idefinitions,
               $isources,
               $action,
               $ipreferred,
               $ivalue_meaning_begin_date,
               $imeanings
               )
         )
       )
    )

xquery version "1.0";

(: ~
 : Module Name:             new property webpage and XQuery
 :
 : Module Version           2.0
 :
 : Date                     31st July 2007
 :
 : Copyright                The cagrid consortium
 :
 : Module overview          Creates and property and displays list
 :
 :)

(:~
 :    @author Steve Harris
 :    @version 0.1
 :
 :    @author Steve Harris
 :    @version 2.0
 :     now allows searching for concept terms
~ :)

  import module namespace
  lib-forms="http://www.cagrid.org/xquery/library/forms"
  at "../edit/m-lib-forms.xquery";

  import module namespace
  lib-util="http://www.cagrid.org/xquery/library/util"
  at "../library/m-lib-util.xquery";

  import module namespace
  lib-rendering="http://www.cagrid.org/xquery/library/rendering"
  at "../web/m-lib-rendering.xquery";

  import module namespace
  lib-make-admin-item="http://www.cagrid.org/xquery/library/make-admin-item"
  at "../edit/m-lib-make-admin-item.xquery";

import module namespace
   administered-item="http://www.cagrid.org/xquery/library/administered-item"
   at "../library/m-administered-item.xquery";

import module namespace
    lib-uri-resolution="http://www.cagrid.org/xquery/library/resolver"
    at "../resolver/m-lib-uri-resolution.xquery";

declare namespace openMDR = "http://www.cagrid.org/schema/openMDR";
declare namespace ISO11179= "http://www.cagrid.org/schema/ISO11179";
declare namespace session="http://exist-db.org/xquery/session";
declare namespace response="http://exist-db.org/xquery/response";
declare namespace exist = "http://exist.sourceforge.net/NS/exist";
declare namespace util="http://exist-db.org/xquery/util";

declare function local:conceptual_domain(
   $id as xs:string,
   $reg-auth as xs:string,
   $administrative-note as xs:string,
   $administrative-status as xs:string,
   $administered-by as xs:string,
   $submitted-by as xs:string,
   $registered-by as xs:string,
   $context-ids as xs:string*,
   $country-identifiers as xs:string*,
   $language-identifiers as xs:string*,
   $names as xs:string*,
   $definitions as xs:string*,
   $sources as xs:string*,
   $preferred as xs:string?,
   $meanings as xs:string*
   ) as xs:boolean
{
   let $version := lib-forms:substring-after-last($id,'-')
   let $vmid := substring-after(lib-forms:substring-before-last($id,'-'),'-')
   let $data-identifier := substring-after(lib-forms:substring-before-last($id,'-'),'-')

   let $doc-name := concat($id,'.xml')

   let $content := (
                    lib-make-admin-item:administration-record($administrative-note,$administrative-status,'Recorded'),
                    lib-make-admin-item:custodians($administered-by,$registered-by,$submitted-by),
                    lib-make-admin-item:havings(
                    $context-ids,
                    $country-identifiers,
                    $language-identifiers,
                    $names,
                    $definitions,
                    $preferred,
                    $sources),
                    for $meaning at $pos in $meanings
                    return
                    element openMDR:Value_Meaning
                       {
                       element openMDR:value_meaning_begin_date {current-date()},
                       element openMDR:value_meaning_description {$meaning},
                       element openMDR:value_meaning_identifier {$vmid}
                       }
                    )

   (: compose the document :)
   let $document := (
       if($meanings > '') then (
          element openMDR:Enumerated_Conceptual_Domain {
                attribute item_registration_authority_identifier {$reg-auth},
                attribute data_identifier {$data-identifier},
                attribute version {$version},
                $content
               }
      ) else (
          element openMDR:Non_Enumerated_Conceptual_Domain {
                attribute item_registration_authority_identifier {$reg-auth},
                attribute data_identifier {$data-identifier},
                attribute version {$version},
                $content
               }
      )
   )

   let $collection := 'conceptual_domain'
   let $message := lib-forms:store-document($document)
   return
      if ($message='stored')
      then true()
      else response:redirect-to(xs:anyURI(concat("../web/login.xquery?calling_page=editConceptualDomain.xquery&",$message)))
};

declare function local:input-page(
   $message as xs:string?,
   $id as xs:string?,
   $reg-auth as xs:string?,
   $administrative-note  as xs:string?,
   $administrative-status  as xs:string?,
   $administered-by  as xs:string?,
   $submitted-by  as xs:string?,
   $registered-by  as xs:string?,
   $context-ids  as xs:string*,
   $country-identifiers as xs:string*,
   $language-identifiers as xs:string*,
   $names as xs:string*,
   $definitions as xs:string*,
   $sources as xs:string*,
   $action as xs:string?,
   $preferred as xs:string?,
   $meanings as xs:string*
   ) {
   let $skip-name := substring-after($action,'delete naming entry')
   let $skip-name-index := if ($skip-name>'') then xs:int($skip-name) else 0

   return

                This form will allow you to Edit Conceptual Domain in the metadata repository

          <form name="edit_conceptual_domain" action="editConceptualDomain.xquery" method="post" class="cagridForm" enctype="multipart/form-data">

             {lib-forms:hidden-element('id',$id)}
             {lib-forms:hidden-element('updating','updating')}
             {lib-forms:edit-admin-item($reg-auth,
                     $administrative-note,
                     $administrative-status,
                     $administered-by,
                     $submitted-by,
                     $registered-by,
                     $context-ids,
                     $country-identifiers,
                     $language-identifiers,
                     $names,
                     $definitions,
                     $sources,
                     $preferred,
                     $action)}

Conceptual Domain

                {
                if(exists($meanings))
                    then (

Enumerated Conceptual Domain?
                      <input type="radio" name="conceptual-domain-type" value="enumerated" checked="checked">enumerated</input>
                      <input type="radio" name="conceptual-domain-type" value="non-enumerated">non-enumerated</input>
                      {lib-forms:action-button('update', 'action' ,'')}

,

Conceptual Domain Meanings
,

                      Value Domain Meanings	meaning

,
                       for $value_meaning  at $pos in $meanings
                        (:let $meaning := $value_meaning/text():)
                        let $meaning := $value_meaning
                        let $location := if($pos > $skip-name-index and $skip-name-index > 0) then (util:eval($pos - 1)) else ($pos)
                        where $pos != $skip-name-index and $value_meaning > ""
                        return (

                              Value {$location} Meaning
                              {lib-forms:input-element('meanings', 60, $meaning)}
                              {lib-forms:action-button(concat('delete value meaning ',$location), 'action' ,'')}

                           ),

                              New Value Meaning
                              {lib-forms:input-element('meanings', 60, '')}
                              {lib-forms:action-button('add new value meaning', 'action' ,'')}

                    )
                    else
                    (

Enumerated Conceptual Domain?
                           <input type="radio" name="conceptual-domain-type" value="enumerated" >enumerated</input>
                           <input type="radio" name="conceptual-domain-type" value="non-enumerated" checked="checked">non-enumerated</input>
                           {lib-forms:action-button('update', 'action' ,'')}

                    )

              }

Store

                         <input type="submit" name="update" value="Store Changes"/>	<input type="submit" name="update" value="Clear"/>

          </form>

{$message}

   };

declare function local:success-page()
{
   let $calling-page := request:get-parameter("calling-page","")
   return

Conceptual Domain modified

Return to maintenance menu

Create another Conceptual Domain

};

declare option exist:serialize "media-type=text/html method=xhtml doctype-public=-//W3C//DTD XHTML 1.0 Transitional//EN doctype-system=http://www.w3.org/TR/2002/REC-xhtml1-20020801/DTD/xhtml1-transitional.dtd";

   session:create(),
   let $id := request:get-parameter('id','')
   let $updating := request:get-parameter('updating','')
   let $title as xs:string := concat("Editing Conceptual Domain ", $id)
   let $element := lib-util:mdrElement("conceptual_domain",$id)
   let $action := request:get-parameter('update','')

   let $ireg-auth := string($element/@item_registration_authority_identifier)
   let $iadministrative-note := string($element//openMDR:administrative_note)
   let $iadministrative-status := string($element//openMDR:administrative_status)
   let $iadministered-by := string($element//openMDR:administered_by)
   let $isubmitted-by := string($element//openMDR:submitted_by)
   let $iregistered-by := string($element//openMDR:registered_by)
   let $icontext-ids := $element//openMDR:context_identifier
   let $icountry-identifiers := $element//openMDR:country_identifier
   let $ilanguage-identifiers := $element//openMDR:language_identifier
   let $inames := $element//openMDR:name
   let $idefinitions := $element//openMDR:definition_text
   let $isources := $element//openMDR:definition_source_reference
   let $ipreferred := string(fn:index-of($element//openMDR:preferred_designation,'true'))
   let $imeanings := $element//openMDR:Value_Meaning

   let $reg-auth := request:get-parameter('registration-authority','')
   let $administrative-note := request:get-parameter('administrative-note','')
   let $administrative-status := request:get-parameter('administrative-status','')
   let $administered-by := request:get-parameter('administered-by','')
   let $submitted-by := request:get-parameter('submitted-by','')
   let $registered-by := request:get-parameter('registered-by','')
   let $context-ids := request:get-parameter('context-ids',())
   let $country-identifiers := request:get-parameter('country-identifiers',())
   let $language-identifiers := request:get-parameter('language-identifiers',())
   let $names := request:get-parameter('names',())
   let $definitions := request:get-parameter('definitions',())
   let $sources := request:get-parameter('sources',())
   let $preferred := request:get-parameter('preferred','')
   let $meanings := request:get-parameter('meanings','')

   return

      lib-rendering:txfrm-webpage(
      $title,
      if ($action='Store Changes')
      then
         (
         if (
               local:conceptual_domain
                  (
                     $id,
                     $reg-auth,
                     $administrative-note,
                     $administrative-status,
                     $administered-by,
                     $submitted-by,
                     $registered-by,
                     $context-ids,
                     $country-identifiers,
                     $language-identifiers,
                     $names,
                     $definitions,
                     $sources,
                     $preferred,
                     $meanings
                  )
            )
         then (local:success-page())
         else (local:input-page(
            'could not store document',
                     $id,
                     $reg-auth,
                     $administrative-note,
                     $administrative-status,
                     $administered-by,
                     $submitted-by,
                     $registered-by,
                     $context-ids,
                     $country-identifiers,
                     $language-identifiers,
                     $names,
                     $definitions,
                     $sources,
                     $action,
                     $preferred,
                     $meanings
                  )
               )
         )
      else (
         if ($updating ='updating')
         then (
      local:input-page
               (
               '',
               $id,
               $reg-auth,
               $administrative-note,
               $administrative-status,
               $administered-by,
               $submitted-by,
               $registered-by,
               $context-ids,
               $country-identifiers,
               $language-identifiers,
               $names,
               $definitions,
               $sources,
               $action,
               $preferred,
               $meanings
               )
         ) else (
               local:input-page
               (
               '',
               $id,
               $ireg-auth,
               $iadministrative-note,
               $iadministrative-status,
               $iadministered-by,
               $isubmitted-by,
               $iregistered-by,
               $icontext-ids,
               $icountry-identifiers,
               $ilanguage-identifiers,
               $inames,
               $idefinitions,
               $isources,
               $action,
               $ipreferred,
               $imeanings
               )
         )
       )
    )


disabled the static typing feature for W3C test submissions

(: Schema for results :)
import schema default element namespace "http://www.w3.org/2005/02/query-test-XQTSResult" at "w3c_reportingresults/XQTSResult.xsd";

(: Test.xml file from ctest :)
declare variable $ctests as document-node() external;

if(fn:empty($ctests)) then
  fn:error()
else
  validate {
    <test-suite-result>
       <implementation name="Zorba"
         version='1.0.0 (svn rev. 8152)'
         anonymous-result-column="false">

         <organization
            name='FLWOR Foundation'
            website="http://zorba-xquery.com/"
            anonymous="false" />

         <submittor
            name="Zorba Team"
            email="contact@zorba-xquery.com" />

         <description>

Zorba is a general purpose XQuery processor implementing in C++
            the W3C family of specifications. It is not an XML database.
            The query processor has been designed to be embeddable in a
            variety of environments such as other programming languages
            extended with XML processing capabilities, browsers,
            database servers, XML message dispatchers, or smartphones.
            Its architecture employes a modular design, which allows customizing
            the Zorba query processor to the environment’s needs.
            In particular the architecture of the query processor allows a
            pluggable XML store (e.g. main memory, DOM stores, persistent
            disk-based large stores, S3 stores). Zorba runs on most platforms
            and is available under the Apache license v2. Currently, Zorba
            implements the following W3C specifications: XQuery 1.0, XQuery Update
            Facility 1.0, XQuery Scripting Extension 1.0, and XSLT 2.0 and XQuery 1.0
            Serialization.

         </description>

         <implementation-defined-items>
           <implementation-defined-item
              name="The revalidation modes that are supported by this implementation."
              value="lax, skip, strict" />

          <implementation-defined-item
             name="The default revalidation mode for this implementation."
             value="lax" />

         </implementation-defined-items>

         <features>
            <feature name='Minimum Conformance' supported='true' />
            <feature name='Schema Import Feature' supported='true' />
            <feature name='Schema Validation Feature' supported='true' />
            <feature name='Static Typing Feature' supported='false' />
            <feature name='Full Axis Feature' supported='true' />
            <feature name='Module Feature' supported='true' />
            <feature name='Serialization Feature' supported='true' />
         </features>

         <context-properties>
            <context-property name="Boundary-space policy" context-type="static" value="strip"/>
            <context-property name="Ordering mode" context-type="static" value="ordered"/>
            <context-property name="Context item static type" context-type="static" value="item()"/>
            <context-property name="Default element/type namespace" context-type="static" value=""/>
            <context-property name="Default function namespace" context-type="static" value="http://www.w3.org/2005/xpath-functions"/>

            <context-property name="Default collation" context-type="static" value="http://www.w3.org/2005/xpath-functions/collation/codepoint"/>
            <context-property name="Construction mode" context-type="static" value="preserve"/>

            <context-property name="Default order for empty sequences" context-type="static" value="empty greatest"/>

            <context-property name="Copy-namespaces mode" context-type="static" value="inherit preserve"/>

         </context-properties>

       </implementation>

       <syntax>XQuery</syntax>

       <test-run dateRun="2010-04-28">
          <test-suite version="1.0.2"/>
          <transformation>
Standard
</transformation>
          <comparison>
Standard
</comparison>
          <otherComments>
None
</otherComments>
       </test-run>

       {
         for $test in $ctests/*:Site/*:Testing/*:Test
         let $testname := fn:tokenize(fn:data($test/*:Name), "/")[last()]
         return
           <test-case
             name="{$testname}"
             result="{fn:substring(fn:data($test/@Status), 0, 5)}"
           />
       }
    </test-suite-result>
  }

(: Schema for results :)
import schema default element namespace "http://www.w3.org/2005/02/query-test-XQTSResult" at "w3c_reportingresults/XQTSResult.xsd";

(: Test.xml file from ctest :)
declare variable $ctests as document-node() external;

if(fn:empty($ctests)) then
  fn:error()
else
  validate {
    <test-suite-result>
       <implementation name="Zorba"
         version='1.0.0 (svn rev. 8152)'
         anonymous-result-column="false">

         <organization
            name='FLWOR Foundation'
            website="http://zorba-xquery.com/"
            anonymous="false" />

         <submittor
            name="Zorba Team"
            email="contact@zorba-xquery.com" />

         <description>

Zorba is a general purpose XQuery processor implementing in C++
            the W3C family of specifications. It is not an XML database.
            The query processor has been designed to be embeddable in a
            variety of environments such as other programming languages
            extended with XML processing capabilities, browsers,
            database servers, XML message dispatchers, or smartphones.
            Its architecture employes a modular design, which allows customizing
            the Zorba query processor to the environment’s needs.
            In particular the architecture of the query processor allows a
            pluggable XML store (e.g. main memory, DOM stores, persistent
            disk-based large stores, S3 stores). Zorba runs on most platforms
            and is available under the Apache license v2. Currently, Zorba
            implements the following W3C specifications: XQuery 1.0, XQuery Update
            Facility 1.0, XQuery Scripting Extension 1.0, and XSLT 2.0 and XQuery 1.0
            Serialization.

         </description>

         <implementation-defined-items>
           <implementation-defined-item
              name="The revalidation modes that are supported by this implementation."
              value="lax, skip, strict" />

          <implementation-defined-item
             name="The default revalidation mode for this implementation."
             value="lax" />

         </implementation-defined-items>

         <features>
            <feature name='Minimum Conformance' supported='true' />
            <feature name='Schema Import Feature' supported='true' />
            <feature name='Schema Validation Feature' supported='true' />
            <feature name='Static Typing Feature' supported='true' />
            <feature name='Full Axis Feature' supported='true' />
            <feature name='Module Feature' supported='true' />
            <feature name='Serialization Feature' supported='true' />
         </features>

         <context-properties>
            <context-property name="Boundary-space policy" context-type="static" value="strip"/>
            <context-property name="Ordering mode" context-type="static" value="ordered"/>
            <context-property name="Context item static type" context-type="static" value="item()"/>
            <context-property name="Default element/type namespace" context-type="static" value=""/>
            <context-property name="Default function namespace" context-type="static" value="http://www.w3.org/2005/xpath-functions"/>

            <context-property name="Default collation" context-type="static" value="http://www.w3.org/2005/xpath-functions/collation/codepoint"/>
            <context-property name="Construction mode" context-type="static" value="preserve"/>

            <context-property name="Default order for empty sequences" context-type="static" value="empty greatest"/>

            <context-property name="Copy-namespaces mode" context-type="static" value="inherit preserve"/>

         </context-properties>

       </implementation>

       <syntax>XQuery</syntax>

       <test-run dateRun="2010-04-28">
          <test-suite version="1.0.2"/>
          <transformation>
Standard
</transformation>
          <comparison>
Standard
</comparison>
          <otherComments>
None
</otherComments>
       </test-run>

       {
         for $test in $ctests/*:Site/*:Testing/*:Test
         let $testname := fn:tokenize(fn:data($test/*:Name), "/")[last()]
         return
           <test-case
             name="{$testname}"
             result="{fn:substring(fn:data($test/@Status), 0, 5)}"
           />
       }
    </test-suite-result>
  }


Corrected the expected error mentioned in the test.


[ignore] bibliographic demo: added view XML source button to detail view.

svn path=/trunk/eXist/; revision=13083

xquery version "1.0";

(:~
    Handles the actual display of the search result. The pagination jQuery plugin in jquery-utils.js
    will call this query to retrieve the next page of search results.

    The query returns a simple table with four columns:
    1) the number of the current record,
    2) a link to save the current record in "My Lists",
    3) the type of resource (represented by an icon), and
    4) the data to display.
:)

import module namespace mods="http://www.loc.gov/mods/v3" at "retrieve-mods.xql";
import module namespace jquery="http://exist-db.org/xquery/jquery" at "resource:org/exist/xquery/lib/jquery.xql";
import module namespace security="http://exist-db.org/mods/security" at "security.xqm";
import module namespace sharing="http://exist-db.org/mods/sharing" at "sharing.xqm";
import module namespace clean="http:/exist-db.org/xquery/mods/cleanup" at "cleanup.xql";

declare namespace bs="http://exist-db.org/xquery/biblio/session";

declare option exist:serialize "media-type=application/xhtml+xml";

declare variable $bs:USER := security:get-user-credential-from-session()[1];

declare function bs:collection-is-writable($collection as xs:string) {
    if ($collection eq $sharing:groups-collection) then
        false()
    else
        security:can-write-collection($bs:USER, $collection)
};

declare function bs:retrieve($start as xs:int, $count as xs:int) {
    let $cached := session:get-attribute("mods:cached")
    let $stored := session:get-attribute("mods-personal-list")
    let $total := count($cached)
    let $available :=
        if ($start + $count gt $total) then
            $total - $start + 1
        else
            $count
    let $home := security:get-home-collection-uri($bs:USER)
    return

        {
            for $item at $pos in subsequence($cached, $start, $available)
            let $currentPos := $start + $pos - 1
            let $id := concat(document-uri(root($item)), '#', util:node-id($item))
            let $saved := $stored//*[@id = $id]
            return

                    {$currentPos}
                    {
                        if ($count gt 1) then

                        else
                            ()
                    }

                    {
                        if ($count eq 1) then
                            let $isWritable := bs:collection-is-writable(util:collection-name($item))
                            return

                                        {
                                            (: if the item's collection is writable, display edit/delete and move buttons :)
                                            if ($isWritable) then (

                                                ,
                                               ,

                                            ) else
                                                ()
                                        }
                                        {
                                            (: button to add a related item :)
                                            if ($bs:USER ne "guest") then

                                            else
                                                ()
                                        }

                                    {
                                        let $clean := clean:cleanup($item)
                                        return
                                            mods:format-full(string($currentPos), $clean, $item)
                                    }

                        else
                            {mods:format-short(string($currentPos), $item)}
                    }

        }

};

session:create(),
let $start0 := request:get-parameter("start", ())
let $start := xs:int(if ($start0) then $start0 else 1)
let $count0 := request:get-parameter("count", ())
let $count := xs:int(if ($count0) then $count0 else 10)
return
    bs:retrieve($start, $count)


Use the full XSD version in the xs constructor function since annotations.

xquery version "3.1";

(:~
 : XPath and XQuery Functions and Operators: Constructor Functions
 :
 : @see https://www.w3.org/TR/2007/REC-xpath-functions-20070123/
 : @see https://www.w3.org/TR/2010/REC-xpath-functions-20101214/
 : @see https://www.w3.org/TR/2014/REC-xpath-functions-30-20140408/
 : @see https://www.w3.org/TR/2016/CR-xpath-functions-31-20170321/
 :)
module  namespace xs = "http://www.w3.org/2001/XMLSchema";
declare namespace a  = "http://reecedunn.co.uk/xquery/annotations";

declare %a:since("xsd", "1.0-20010502") function xs:ENTITY($arg as xs:anyAtomicType?) as xs:ENTITY? external;
declare %a:since("xsd", "1.0-20010502") function xs:ID($arg as xs:anyAtomicType?) as xs:ID? external;
declare %a:since("xsd", "1.0-20010502") function xs:IDREF($arg as xs:anyAtomicType?) as xs:IDREF? external;
declare %a:since("xsd", "1.0-20010502") function xs:NCName($arg as xs:anyAtomicType?) as xs:NCName? external;
declare %a:since("xsd", "1.0-20010502") function xs:NMTOKEN($arg as xs:anyAtomicType?) as xs:NMTOKEN? external;
declare %a:since("xsd", "1.0-20010502") function xs:Name($arg as xs:anyAtomicType?) as xs:Name? external;
(: NOTE: $arg is required in XQuery 1.0 :)
declare %a:since("xsd", "1.0-20010502") function xs:QName($arg as xs:anyAtomicType?) as xs:QName? external;

declare %a:since("xsd", "1.0-20010502") function xs:anyURI($arg as xs:anyAtomicType?) as xs:anyURI? external;
declare %a:since("xsd", "1.0-20010502") function xs:base64Binary($arg as xs:anyAtomicType?) as xs:base64Binary? external;
declare %a:since("xsd", "1.0-20010502") function xs:boolean($arg as xs:anyAtomicType?) as xs:boolean? external;
declare %a:since("xsd", "1.0-20010502") function xs:byte($arg as xs:anyAtomicType?) as xs:byte? external;
declare %a:since("xsd", "1.0-20010502") function xs:date($arg as xs:anyAtomicType?) as xs:date? external;
declare %a:since("xsd", "1.0-20010502") function xs:dateTime($arg as xs:anyAtomicType?) as xs:dateTime? external;
declare %a:since("xsd", "1.0-20010502") function xs:dayTimeDuration($arg as xs:anyAtomicType?) as xs:dayTimeDuration? external;
declare %a:since("xsd", "1.0-20010502") function xs:decimal($arg as xs:anyAtomicType?) as xs:decimal? external;
declare %a:since("xsd", "1.0-20010502") function xs:double($arg as xs:anyAtomicType?) as xs:double? external;
declare %a:since("xsd", "1.0-20010502") function xs:duration($arg as xs:anyAtomicType?) as xs:duration? external;
declare %a:since("xsd", "1.0-20010502") function xs:float($arg as xs:anyAtomicType?) as xs:float? external;
declare %a:since("xsd", "1.0-20010502") function xs:gDay($arg as xs:anyAtomicType?) as xs:gDay? external;
declare %a:since("xsd", "1.0-20010502") function xs:gMonth($arg as xs:anyAtomicType?) as xs:gMonth? external;
declare %a:since("xsd", "1.0-20010502") function xs:gMonthDay($arg as xs:anyAtomicType?) as xs:gMonthDay? external;
declare %a:since("xsd", "1.0-20010502") function xs:gYear($arg as xs:anyAtomicType?) as xs:gYear? external;
declare %a:since("xsd", "1.0-20010502") function xs:gYearMonth($arg as xs:anyAtomicType?) as xs:gYearMonth? external;
declare %a:since("xsd", "1.0-20010502") function xs:hexBinary($arg as xs:anyAtomicType?) as xs:hexBinary? external;
declare %a:since("xsd", "1.0-20010502") function xs:int($arg as xs:anyAtomicType?) as xs:int? external;
declare %a:since("xsd", "1.0-20010502") function xs:integer($arg as xs:anyAtomicType?) as xs:integer? external;
declare %a:since("xsd", "1.0-20010502") function xs:language($arg as xs:anyAtomicType?) as xs:language? external;
declare %a:since("xsd", "1.0-20010502") function xs:long($arg as xs:anyAtomicType?) as xs:long? external;
declare %a:since("xsd", "1.0-20010502") function xs:negativeInteger($arg as xs:anyAtomicType?) as xs:negativeInteger? external;
declare %a:since("xsd", "1.0-20010502") function xs:nonNegativeInteger($arg as xs:anyAtomicType?) as xs:nonNegativeInteger? external;
declare %a:since("xsd", "1.0-20010502") function xs:nonPositiveInteger($arg as xs:anyAtomicType?) as xs:nonPositiveInteger? external;
declare %a:since("xsd", "1.0-20010502") function xs:normalizedString($arg as xs:anyAtomicType?) as xs:normalizedString? external;
declare %a:since("xsd", "1.0-20010502") function xs:positiveInteger($arg as xs:anyAtomicType?) as xs:positiveInteger? external;
declare %a:since("xsd", "1.0-20010502") function xs:short($arg as xs:anyAtomicType?) as xs:short? external;
declare %a:since("xsd", "1.0-20010502") function xs:string($arg as xs:anyAtomicType?) as xs:string? external;
declare %a:since("xsd", "1.0-20010502") function xs:time($arg as xs:anyAtomicType?) as xs:time? external;
declare %a:since("xsd", "1.0-20010502") function xs:token($arg as xs:anyAtomicType?) as xs:token? external;
declare %a:since("xsd", "1.0-20010502") function xs:unsignedByte($arg as xs:anyAtomicType?) as xs:unsignedByte? external;
declare %a:since("xsd", "1.0-20010502") function xs:unsignedInt($arg as xs:anyAtomicType?) as xs:unsignedInt? external;
declare %a:since("xsd", "1.0-20010502") function xs:unsignedLong($arg as xs:anyAtomicType?) as xs:unsignedLong? external;
declare %a:since("xsd", "1.0-20010502") function xs:unsignedShort($arg as xs:anyAtomicType?) as xs:unsignedShort? external;
declare %a:since("xsd", "1.0-20010502") function xs:untypedAtomic($arg as xs:anyAtomicType?) as xs:untypedAtomic? external;
declare %a:since("xsd", "1.0-20010502") function xs:yearMonthDuration($arg as xs:anyAtomicType?) as xs:yearMonthDuration? external;
declare %a:since("xsd", "1.1-20120405") function xs:dateTimeStamp($arg as xs:anyAtomicType?) as xs:dateTimeStamp? external;

xquery version "3.1";

(:~
 : XPath and XQuery Functions and Operators: Constructor Functions
 :
 : @see https://www.w3.org/TR/2007/REC-xpath-functions-20070123/
 : @see https://www.w3.org/TR/2010/REC-xpath-functions-20101214/
 : @see https://www.w3.org/TR/2014/REC-xpath-functions-30-20140408/
 : @see https://www.w3.org/TR/2016/CR-xpath-functions-31-20170321/
 :)
module  namespace xs = "http://www.w3.org/2001/XMLSchema";
declare namespace a  = "http://reecedunn.co.uk/xquery/annotations";

declare %a:since("xsd", "1.0") function xs:ENTITY($arg as xs:anyAtomicType?) as xs:ENTITY? external;
declare %a:since("xsd", "1.0") function xs:ID($arg as xs:anyAtomicType?) as xs:ID? external;
declare %a:since("xsd", "1.0") function xs:IDREF($arg as xs:anyAtomicType?) as xs:IDREF? external;
declare %a:since("xsd", "1.0") function xs:NCName($arg as xs:anyAtomicType?) as xs:NCName? external;
declare %a:since("xsd", "1.0") function xs:NMTOKEN($arg as xs:anyAtomicType?) as xs:NMTOKEN? external;
declare %a:since("xsd", "1.0") function xs:Name($arg as xs:anyAtomicType?) as xs:Name? external;
(: NOTE: $arg is required in XQuery 1.0 :)
declare %a:since("xsd", "1.0") function xs:QName($arg as xs:anyAtomicType?) as xs:QName? external;

declare %a:since("xsd", "1.0") function xs:anyURI($arg as xs:anyAtomicType?) as xs:anyURI? external;
declare %a:since("xsd", "1.0") function xs:base64Binary($arg as xs:anyAtomicType?) as xs:base64Binary? external;
declare %a:since("xsd", "1.0") function xs:boolean($arg as xs:anyAtomicType?) as xs:boolean? external;
declare %a:since("xsd", "1.0") function xs:byte($arg as xs:anyAtomicType?) as xs:byte? external;
declare %a:since("xsd", "1.0") function xs:date($arg as xs:anyAtomicType?) as xs:date? external;
declare %a:since("xsd", "1.0") function xs:dateTime($arg as xs:anyAtomicType?) as xs:dateTime? external;
declare %a:since("xsd", "1.0") function xs:dayTimeDuration($arg as xs:anyAtomicType?) as xs:dayTimeDuration? external;
declare %a:since("xsd", "1.0") function xs:decimal($arg as xs:anyAtomicType?) as xs:decimal? external;
declare %a:since("xsd", "1.0") function xs:double($arg as xs:anyAtomicType?) as xs:double? external;
declare %a:since("xsd", "1.0") function xs:duration($arg as xs:anyAtomicType?) as xs:duration? external;
declare %a:since("xsd", "1.0") function xs:float($arg as xs:anyAtomicType?) as xs:float? external;
declare %a:since("xsd", "1.0") function xs:gDay($arg as xs:anyAtomicType?) as xs:gDay? external;
declare %a:since("xsd", "1.0") function xs:gMonth($arg as xs:anyAtomicType?) as xs:gMonth? external;
declare %a:since("xsd", "1.0") function xs:gMonthDay($arg as xs:anyAtomicType?) as xs:gMonthDay? external;
declare %a:since("xsd", "1.0") function xs:gYear($arg as xs:anyAtomicType?) as xs:gYear? external;
declare %a:since("xsd", "1.0") function xs:gYearMonth($arg as xs:anyAtomicType?) as xs:gYearMonth? external;
declare %a:since("xsd", "1.0") function xs:hexBinary($arg as xs:anyAtomicType?) as xs:hexBinary? external;
declare %a:since("xsd", "1.0") function xs:int($arg as xs:anyAtomicType?) as xs:int? external;
declare %a:since("xsd", "1.0") function xs:integer($arg as xs:anyAtomicType?) as xs:integer? external;
declare %a:since("xsd", "1.0") function xs:language($arg as xs:anyAtomicType?) as xs:language? external;
declare %a:since("xsd", "1.0") function xs:long($arg as xs:anyAtomicType?) as xs:long? external;
declare %a:since("xsd", "1.0") function xs:negativeInteger($arg as xs:anyAtomicType?) as xs:negativeInteger? external;
declare %a:since("xsd", "1.0") function xs:nonNegativeInteger($arg as xs:anyAtomicType?) as xs:nonNegativeInteger? external;
declare %a:since("xsd", "1.0") function xs:nonPositiveInteger($arg as xs:anyAtomicType?) as xs:nonPositiveInteger? external;
declare %a:since("xsd", "1.0") function xs:normalizedString($arg as xs:anyAtomicType?) as xs:normalizedString? external;
declare %a:since("xsd", "1.0") function xs:positiveInteger($arg as xs:anyAtomicType?) as xs:positiveInteger? external;
declare %a:since("xsd", "1.0") function xs:short($arg as xs:anyAtomicType?) as xs:short? external;
declare %a:since("xsd", "1.0") function xs:string($arg as xs:anyAtomicType?) as xs:string? external;
declare %a:since("xsd", "1.0") function xs:time($arg as xs:anyAtomicType?) as xs:time? external;
declare %a:since("xsd", "1.0") function xs:token($arg as xs:anyAtomicType?) as xs:token? external;
declare %a:since("xsd", "1.0") function xs:unsignedByte($arg as xs:anyAtomicType?) as xs:unsignedByte? external;
declare %a:since("xsd", "1.0") function xs:unsignedInt($arg as xs:anyAtomicType?) as xs:unsignedInt? external;
declare %a:since("xsd", "1.0") function xs:unsignedLong($arg as xs:anyAtomicType?) as xs:unsignedLong? external;
declare %a:since("xsd", "1.0") function xs:unsignedShort($arg as xs:anyAtomicType?) as xs:unsignedShort? external;
declare %a:since("xsd", "1.0") function xs:untypedAtomic($arg as xs:anyAtomicType?) as xs:untypedAtomic? external;
declare %a:since("xsd", "1.0") function xs:yearMonthDuration($arg as xs:anyAtomicType?) as xs:yearMonthDuration? external;
declare %a:since("xsd", "1.1") function xs:dateTimeStamp($arg as xs:anyAtomicType?) as xs:dateTimeStamp? external;


Annotate the BaseX web functions with versioned type restrictions.

xquery version "3.1";
(:~
 : BaseX Web Module functions
 :
 : @see http://docs.basex.org/wiki/Web_Module
 :)
module namespace web = "http://basex.org/modules/web";

declare namespace a = "http://reecedunn.co.uk/xquery/annotations";
declare namespace o = "http://reecedunn.co.uk/xquery/options";

declare namespace rest = "http://exquery.org/ns/restxq";

declare option o:requires "basex/8.1";

declare %a:since("basex", "8.1") function web:content-type($path as xs:string) as xs:string external;
declare %a:restrict-until("$parameters", "basex", "8.2", "map(*)")
        %a:restrict-until("$parameters", "basex", "9.0", "map(item(), item()*)")
        %a:restrict-since("$parameters", "basex", "8.5", "map(*)")
        %a:since("basex", "8.1") function web:create-url($url as xs:string, $parameters as map(*)) as xs:string external;
declare %a:since("basex", "8.2") function web:encode-url($string as xs:string) as xs:string external;
declare %a:since("basex", "8.2") function web:decode-url($string as xs:string) as xs:string external;
declare %a:since("basex", "8.1") function web:redirect($location as xs:string) as element(rest:response) external;
declare %a:since("basex", "8.1") function web:redirect($location as xs:string, $parameters as map(*)) as element(rest:response) external;
declare %a:since("basex", "8.1") function web:response-header() as element(rest:response) external;
declare %a:restrict-until("$output", "basex", "9.0", "map(*)")
        %a:since("basex", "8.1") function web:response-header($output as map(*)?) as element(rest:response) external;
declare %a:restrict-until("$output", "basex", "9.0", "map(*)")
        %a:restrict-until("$headers", "basex", "8.2", "map(*)")
        %a:restrict-until("$headers", "basex", "9.0", "map(xs:string, xs:string)")
        %a:since("basex", "8.1") function web:response-header($output as map(*)?, $headers as map(*)?) as element(rest:response) external;
declare %a:since("basex", "9.0") function web:response-header($output as map(*)?, $headers as map(*)?, $atts as map(*)?) as element(rest:response) external;

xquery version "3.1";
(:~
 : BaseX Web Module functions
 :
 : @see http://docs.basex.org/wiki/Web_Module
 :)
module namespace web = "http://basex.org/modules/web";

declare namespace a = "http://reecedunn.co.uk/xquery/annotations";
declare namespace o = "http://reecedunn.co.uk/xquery/options";

declare namespace rest = "http://exquery.org/ns/restxq";

declare option o:requires "basex/8.1";

declare %a:since("basex", "8.1") function web:content-type($path as xs:string) as xs:string external;
declare %a:since("basex", "8.1") function web:create-url($url as xs:string, $parameters as map(*) (: [8.1] as map(*) [8.2] as map(item(), item()*) [9.0] as map(*) :)) as xs:string external;
declare %a:since("basex", "8.2") function web:encode-url($string as xs:string) as xs:string external;
declare %a:since("basex", "8.2") function web:decode-url($string as xs:string) as xs:string external;
declare %a:since("basex", "8.1") function web:redirect($location as xs:string) as element(rest:response) external;
declare %a:since("basex", "8.1") function web:redirect($location as xs:string, $parameters as map(*)) as element(rest:response) external;
declare %a:since("basex", "8.1") function web:response-header() as element(rest:response) external;
declare %a:since("basex", "8.1") function web:response-header($output as map(*)? (: [8.1] as map(*) [9.0] as map(*)? :)) as element(rest:response) external;
declare %a:since("basex", "8.1") function web:response-header($output as map(*)? (: [8.1] as map(*) [9.0] as map(*)? :), $headers as map(*)? (: [8.1] as map(*) [8.2] as map(xs:string, xs:string) [9.0] as map(*)? :)) as element(rest:response) external;
declare %a:since("basex", "9.0") function web:response-header($output as map(*)?, $headers as map(*)?, $atts as map(*)?) as element(rest:response) external;


[ignore] forgot to commit one file. admin webapp was broken.

svn path=/trunk/eXist/; revision=8512

module namespace rev="http://exist-db.org/xquery/admin-interface/revisions";

import module namespace v="http://exist-db.org/versioning"
at "resource:org/exist/versioning/xquery/versioning.xqm";
import module namespace date="http://exist-db.org/xquery/admin-interface/date" at "dates.xqm";

declare function rev:main() as element()
{
	let $resource := request:get-parameter("resource", ())
	return

Revisions for resource {$resource}

					Revision
					Date
					User
					Actions

				{rev:display-revisions($resource)}

};

declare function rev:display-revisions($resource as xs:string) {
	let $doc := doc($resource)
	for $version in v:versions($doc)
	let $rev := $version/v:properties/v:revision/text()
	return (

			{$rev}
			{date:format-dateTime($version/v:properties/v:date)}
			{$version/v:properties/v:user/text()}

					Restore

				Diff

			    Annotate

,

	)
};

module namespace rev="http://exist-db.org/xquery/admin-interface/revisions";

import module namespace v="http://exist-db.org/versioning"
at "resource:org/exist/versioning/xquery/versioning.xqm";
import module namespace date="http://exist-db.org/xquery/admin-interface/date" at "dates.xqm";

declare function rev:main() as element()
{
	let $resource := request:get-parameter("resource", ())
	return

Revisions for resource {$resource}

					Revision
					Date
					User
					Actions

				{rev:display-revisions($resource)}

};

declare function rev:display-revisions($resource as xs:string) {
	let $doc := doc($resource)
	for $version in v:list-versions($doc)
	let $rev := $version/v:properties/v:revision/text()
	return (

			{$rev}
			{date:format-dateTime($version/v:properties/v:date)}
			{$version/v:properties/v:user/text()}

					Restore

				Diff

			    Annotate

,

	)
};


improved the documentation of the JSON module

(:
  : Copyright 2006-2009 The FLWOR Foundation.
  :
  : Licensed under the Apache License, Version 2.0 (the "License");
  : you may not use this file except in compliance with the License.
  : You may obtain a copy of the License at
  :
  : http://www.apache.org/licenses/LICENSE-2.0
  :
  : Unless required by applicable law or agreed to in writing, software
  : distributed under the License is distributed on an "AS IS" BASIS,
  : WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  : See the License for the specific language governing permissions and
  : limitations under the License.
  :)

 (:~
  :
In the XQuery specification, XQuery is described as a language
  : capable of expressing queries on XML data.
  : This makes XQuery the perfect choice for data processing on the
  : Web because XML is widely used there. However, there are also some
  : other data formats present on the Web.
  : For example, JSON
  : (JavaScript Object Notation) is the most common data format for
  : applications which are written in JavaScript.
  : JSON is a lightweight hierarchical data-interchange format. Like XML,
  : it is easy for humans to read and write. Moreover, it is easy for
  : machines to parse and generate.

  :
  :
In order to enable JSON processing with XQuery, Zorba implements a set
  : of functions that open XQuery developers the door to process JSON
  : data. Specifically, this module provides two types of functions. Functions
  : to
  :

  :
parse JSON and convert it to XDM and

  :
serialize XDM in order to output JSON.

  :

  :

  :
  :
Both types of functions are available to parse and serialize two
  : types of XDM-JSON mappings, respectively. The first mapping has been
  :
  : proposed by John Snelson. The second mapping is called
  : JsonML. In the following, we
  : briefly describe both mappings.

  :
  :
Simple XDM-JSON Mapping

  :
In order to process JSON with XQuery, Zorba implements a mapping between
  : JSON and XML that was initially proposed by John Snelson in his article
  : Parsing JSON into XQuery.
  : In this article, he describes the following recursive mapping declarations.
  :

  :

  :

  :     JSON 	type(JSON) 	toXML(JSON)

  :

  :     JSON
  :     N/A
  :     <json type="type(JSON)">toXML(JSON)</json>
  :

  :

  :     { "key1": value1, "key2": value2 }
  :     object
  :     <pair name="key1" type="type(value1)">toXML(value1)</pair><pair name="key2" type="type(value2)">toXML(value2)</pair>
  :

  :

  :     [ value1, value2 ]
  :     array
  :     <item type="type(value1)">toXML(value1)</item><item type="type(value2)">toXML(value2)</item>
  :

  :

  :     "value"
  :     string
  :     value
  :

  :

  :     number
  :     number
  :     number
  :

  :

  :     true/false
  :     boolean
  :     true/false
  :

  :

  :     null
  :     null
  :     empty
  :

  :

  :
  :
Zorba implements the simple mapping in two functions:
  :

  :
the parse function is used for parsing a
  :      sequence of JSON strings into a sequence of elements

  :
the serialize function implements the
  :      reverse process, i.e. serializing a sequence of elements into a
  :      sequence of valid JSON strings.

  :

  :
  :
JsonML Mapping

  :

  : JSonML (JSON Markup Language)
  : is an application of the JSON format.
  : The purpose of JSonML is to provide a compact format for transporting
  : XML-based markup as JSon. In contrast to the simple JSON mapping described above
  : JsonML allows a lossless conversion back and forth.

  :
  :
Zorba implements the JsonML-XDM mapping in two functions:
  :

  :
the parse-ml function is used for parsing a
  :      sequence of JsonML strings into a sequence of elements

  :
the serialize-ml function implements the
  :      reverse process, i.e. serializing a sequence of elements into a
  :      sequence of valid JsonML strings.

  :

  :
  : @author Sorin Nasoi
  :
  :)
module namespace json = "http://www.zorba-xquery.com/modules/json";

(:~
 : This function parses a JSON string and returns an XDM instance according
 : to the simple JSON-XDM mapping described above.
 :
 :
Query:

 :

 : json:parse('{
 :      "firstName": "John",
 :      "lastName": "Smith",
 :      "address": {
 :          "streetAddress": "21 2nd Street",
 :          "city": "New York",
 :      },
 :      "phoneNumbers": [
 :          "646 123-4567"
 :      ]
 :  }')

 :
 :
Result:

 :

 : <json type="object">
 :   <pair name="firstName" type="string">John</pair>
 :   <pair name="lastName" type="string">Smith</pair>
 :   <pair name="address" type="object">
 :     <pair name="streetAddress" type="string">21 2nd Street</pair>
 :     <pair name="city" type="string">New York</pair>
 :   </pair>
 :   <pair name="phoneNumbers" type="array">
 :     <item type="string">212 732-1234</item>
 :   </pair>
 : </json>

 :
 : @param $text a sequence of valid JSON strings
 : @return  a sequence of nodes according to the simple JSON-XDM mapping
 : @error API0060 if any of the strings passed as parameter is not valid JSON.
 :)
declare function json:parse(
  $text as xs:string*
) as node()* external;

(:~
 : The serialize function takes a sequence of nodes as parameter and
 : transforms each element into a valid JSON string according to the
 : simple mapping described above.
 :
 :
Query:

 :

 : json:serialize(
 :   <json type="object">
 :     <pair name="firstName" type="string">John</pair>
 :     <pair name="lastName" type="string">Smith</pair>
 :     <pair name="address" type="object">
 :       <pair name="streetAddress" type="string">21 2nd Street</pair>
 :       <pair name="city" type="string">New York</pair>
 :     </pair>
 :     <pair name="phoneNumbers" type="array">
 :       <item type="string">212 732-1234</item>
 :     </pair>
 :   </json>
 : )

 :
 :
Result:

 :

 : {
 :   "firstName": "John",
 :   "lastName": "Smith",
 :   "address": {
 :    "streetAddress": "21 2nd Street",
 :    "city": "New York",
 :   },
 :   "phoneNumbers": [
 :     "212 732-1234"
 :   ]
 : }

 :
 : @param $xml a sequence of nodes conformant to the simple mapping described above
 : @return a sequence of JSON strings
 : @error API0061 if the passed elements do not have a valid JSON structure
 :)
declare function json:serialize(
  $xml as node()*
) as xs:string* external;

(:~
 : This function parses JSON and returns an XDM instances according
 : to the JsonML mapping described above.
 :
 :
Query:

 :

 : json:parse-ml(
 :   '["table", {"class":"maintable"},
 :      ["tr", {"class":"odd"},
 :        ["th", {}, "Situation"],
 :        ["th", "Result"] ],
 :      ["tr", {"class":"even"},
 :        ["td", ["a",  {"href" : "driving.html", "title" : "Driving"}, "Driving"]],
 :        ["td", "Busy"] ]
 :    ]'
 : )

 :
 :
Result:

 :

 : <table class="maintable">
 :   <tr class="odd">
 :     <th>Situation</th>
 :     <th>Result</th>
 :   </tr>
 :   <tr class="even">
 :     <td><a href="driving.html" title="Driving">Driving</a></td>
 :     <td>Busy</td>
 :   </tr>
 : </table>

 :
 : @param $text a sequence of valid JSON strings
 : @return a sequence of nodes that result from parsing the given
 :         JSON strings according to the JsonML mapping
 : @error API0063 if the string representation of the value passed
 :        was empty or any of the passed strings are not valid JSON
 :)
declare function json:parse-ml(
  $text as xs:string*
) as node()* external;

(:~
 : This function serializes a sequence of elements by
 : transforming each element into a valid JSON string according to the JsonML
 : mapping described above.
 :
 :
Query:

 :

 : json:serialize-ml(
 :   <ul>
 :     <li>true</li>
 :     <li href="driving.html" title="Driving">Second item</li>
 :     <li/>
 :     <li>-1.4</li>
 :   </ul>
 : )

 :
 :
Result:

 :

 : ["ul",
 :   ["li", "true"],
 :   ["li", {"href":"driving.html"}, {"title":"Driving"}, "Second item"],
 :   ["li"],
 :   ["li", "-1.4"]
 : ]

 :
 : @param $xml the sequence of nodes that should be converted to JsonML
 : @return a sequence of JSON strings resulting from transforming the
 :         given parameter to JSON according to the XDM-JsonML mapping
 :)
declare function json:serialize-ml(
  $xml as node()*
) as xs:string* external;

(:
  : Copyright 2006-2009 The FLWOR Foundation.
  :
  : Licensed under the Apache License, Version 2.0 (the "License");
  : you may not use this file except in compliance with the License.
  : You may obtain a copy of the License at
  :
  : http://www.apache.org/licenses/LICENSE-2.0
  :
  : Unless required by applicable law or agreed to in writing, software
  : distributed under the License is distributed on an "AS IS" BASIS,
  : WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  : See the License for the specific language governing permissions and
  : limitations under the License.
  :)

 (:~
  : In the XQuery specification, XQuery is described as a language capable of
  : expressing queries on XML data.
  : This makes XQuery the perfect choice for a data processing language on the
  : Web because XML is widely used there. However, there are also some other
  : data formats present on the Web.
  : For example, JSON
  : (JavaScript Object Notation) is the most common data format for applications
  : which are written in JavaScript.
  : Zorba implements a set of functions that opens XQuery developers the door to
  : processing other data formats (like JSon).
  : This module provides functions that allow to process JSON data. That is,
  : it provides functions to convert JSON to XDM and to serialize XDM
  : to JSON.
  :
  : @author Sorin Nasoi
  : @version 1.0
  :
  :
1 JSon Functions

  : JSON is a lightweight hierarchical data-interchange format. Like XML, it is
  : easy for humans to read and write. Moreover, it is easy for machines to parse
  : and generate.

  : In order to process JSON with XQuery, Zorba implements a mapping between JSON
  : and XML that was proposed by John Snelson in his article
  : Parsing JSON into XQuery.

  : In this article, he describes the following recursive mapping declarations.

  :

  :

  : JSON 	type(JSON) 	toXML(JSON)

  :

  : JSON 	N/A 	<json type="type(JSON)">toXML(JSON)</json>

  :

  : { "key1": value1, "key2": value2 } 	object 	<pair name="key1" type="type(value1)">toXML(value1)</pair><pair name="key2" type="type(value2)">toXML(value2)</pair>

  :

  : [ value1, value2 ] 	array 	<item type="type(value1)">toXML(value1)</item><item type="type(value2)">toXML(value2)</item>

  :

  : "value" 	string 	value

  :

  : number 	number 	number

  :

  : true / false 	boolean 	true / false

  :

  : null 	null 	empty

  :

  :

  : Zorba implements this mapping in two functions: the parse
  : function is used for parsing a sequence of JSON strings into a sequence of
  : elements, the serialize function implements the
  : reverse process, i.e. serializing a sequence of elements into a sequence of
  : valid JSon strings.

  :
  :
2 JSonML Functions

  : JSonML (JSON Markup Language)
  :  is an application of the JSON
  :  (JavaScript Object Notation) format.

  : The purpose of JSonML is to provide a compact format for transporting
  : XML-based markup as JSon. In contrast to the JSon mapping depicted above (see
  :  1 JSON Functions), JSonML allows a lossless
  :  conversion back and forth.

  : Zorba implements the JSonML
  : structure defined in this article
  : Get to know JSonML

  : Analogoulsy to the JSON conversion, this functionality is implemented in a
  : parse-ml and serialize-ml
  : function, respectively.

  : Note:

  : Calling json:serialize-ml(json:parse-ml($some_string)) will not
  : always produce $some_string.

  : This is caused by the fact that json:serialize-ml does dot know the exact type
  :  of the JSON value (true, false, null, numbers) and treats them all as strings.

  :
  :)
module namespace json = "http://www.zorba-xquery.com/modules/json";

 (:~
  : Parsing JSON into the XQuery Data Model (XDM) according to the mapping
  : described above.
  :
  : @param $text a sequence of valid JSON strings
  : @return  a sequence of nodes
  : @error API0060 if any of the strings passed as parameter are not a valid JSON
  :)
declare function json:parse(
  $text as xs:string*
) as node()* external;

(:~
 : The serialize function takes a sequence of nodes as parameter and
 : transforms each element into a valid JSON string according to the mapping
 : depicted in John Snelson's article.
 :
 : @param $xml a sequence of nodes conformant to the mapping described above
 : @return a sequence of JSON strings representation of the passed sequence of nodes
 : @error API0061 if the passed elements do not have a valid JSon structure
 : @error API0062 if the passed parameters are not nodes
 :)
declare function json:serialize(
  $xml as node()*
) as xs:string* external;

 (:~
  : This function parses JSON into the XQuery Data Model (XDM)
  : according to the JSonML mapping.
  :
  : @param $text a sequence of valid JSON string
  : @return a sequence of nodes
  : @error API0063 if the string representation of the value passed was empty or
  : any of the passed strings does not represend a valid JSon string
  :)
declare function json:parse-ml(
  $text as xs:string*
) as node()* external;

 (:~
  : The serialize function takes a sequence of elements as parameter and
  : transforms each element into a valid JSon string according to the JSonML
  : mapping
  :
  : @param $xml valid JSon string according to JSonML mapping
  : @return a sequence of JSon strings representation of the passed sequence of nodes
  : @error API0064 if the passed elements do not have a valid JSon structure
  : @error API0065 if any of the passed parameters are not elements
  :)
declare function json:serialize-ml(
  $xml as node()*
) as xs:string* external;


MarkLogic: Return 'App-Services' if there are no associated servers.

(:
 : Copyright (C) 2019, 2021 Reece H. Dunn
 :
 : Licensed under the Apache License, Version 2.0 (the "License");
 : you may not use this file except in compliance with the License.
 : You may obtain a copy of the License at
 :
 : http://www.apache.org/licenses/LICENSE-2.0
 :
 : Unless required by applicable law or agreed to in writing, software
 : distributed under the License is distributed on an "AS IS" BASIS,
 : WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 : See the License for the specific language governing permissions and
 : limitations under the License.
 :)
xquery version "1.0-ml";
declare namespace o = "http://reecedunn.co.uk/xquery/options";
declare option o:implementation "marklogic/6.0";

declare variable $database as xs:string external := "emerald-test";

(: Return the servers on the MarkLogic server. :)

let $database :=
    try {
        if (string-length($database) eq 0) then
            ()
        else
            xdmp:database($database)
    } catch ($e) {
        ()
    }
let $servers :=
    for $server in xdmp:servers()
    where empty($database) or $database eq xdmp:server-database($server)
    return $server
return if (exists($servers)) then
    for $server in $servers
    let $name := xdmp:server-name($server)
    order by $name
    return $name
else
    "App-Services"

(:
 : Copyright (C) 2019, 2021 Reece H. Dunn
 :
 : Licensed under the Apache License, Version 2.0 (the "License");
 : you may not use this file except in compliance with the License.
 : You may obtain a copy of the License at
 :
 : http://www.apache.org/licenses/LICENSE-2.0
 :
 : Unless required by applicable law or agreed to in writing, software
 : distributed under the License is distributed on an "AS IS" BASIS,
 : WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 : See the License for the specific language governing permissions and
 : limitations under the License.
 :)
xquery version "1.0-ml";
declare namespace o = "http://reecedunn.co.uk/xquery/options";
declare option o:implementation "marklogic/6.0";

declare variable $database as xs:string external := "emerald-test";

(: Return the servers on the MarkLogic server. :)

let $database :=
    try {
        if (string-length($database) eq 0) then
            ()
        else
            xdmp:database($database)
    } catch ($e) {
        ()
    }
for $server in xdmp:servers()
let $name := xdmp:server-name($server)
where empty($database) or $database eq xdmp:server-database($server)
order by $name
return $name


Added join for all stations.

Added join for all stations.

(: XQuery Join Aggregate Query :)
(: Find the lowest recorded temperature (TMIN) for each station on 2000-01-01.:)
let $station_collection := "/tmp/1.0_partition_ghcnd_all_xml/stations"
for $s in collection($station_collection)/stationCollection/station

let $sensor_collection := "/tmp/1.0_partition_ghcnd_all_xml/sensors"
for $r in collection($sensor_collection)/dataCollection/data

let $date := xs:date(fn:substring(xs:string(fn:data($r/date)), 0, 11))
where $s/id eq $r/station
    and $r/dataType eq "TMAX"
    and $date eq xs:date("2000-01-01")
return ($s/displayName, $r/value)

(: XQuery Join Aggregate Query :)
(: Find the lowest recorded temperature (TMIN) for each station 2001.         :)
let $station_collection := "/tmp/1.0_partition_ghcnd_all_xml/stations"
for $s in collection($station_collection)/stationCollection/stations

return fn:min(
    let $sensor_collection := "/tmp/1.0_partition_ghcnd_all_xml/sensors"
    for $r in collection($sensor_collection)/dataCollection/data

    let $date := xs:date(fn:substring(xs:string(fn:data($r/date)), 0, 11))
    where $s/id eq $r/station
        and $r/dataType eq "TMIN"
        and fn:year-from-date($date) eq 2001
    return $r/value
) div 10