Alternative fix for http://sourceforge.net/tracker/index.php?func=detail&aid=1535514&group_id=17691&atid=317691 ([ 1535514 ] decoding resources names in webadmin interface)
Gev please could you verify?

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

(:
    Module: display and browse collections.
:)
module namespace browse="http://exist-db.org/xquery/admin-interface/browse";

declare namespace request="http://exist-db.org/xquery/request";
declare namespace xdb="http://exist-db.org/xquery/xmldb";
declare namespace util="http://exist-db.org/xquery/util";

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

(:
    Main function: outputs the page.
:)
declare function browse:main($user as xs:string, $passwd as xs:string) as element() {
    let $colName := request:get-parameter("collection", "/db"),
        $collection := xdb:collection($colName, $user, $passwd)
    return

            { browse:process-action($collection) }

Browsing Collection: {xdb:decode-uri(xs:anyURI($colName))}

            <form method="POST" enctype="multipart/form-data">
                {
                    browse:display-collection($collection)
                }

<input type="submit" name="action" value="Remove Selected"/>

                        <input type="submit" name="action" value="Create Collection"/>
                        New collection:

                        <input type="text" name="create" size="40"/>

                        <input type="submit" name="action" value="Upload"/>
                        <input type="file" size="30" name="upload"/>
                        Store as:

                        <input type="text" name="name" size="20"/>

                <input type="hidden" name="collection" value="{$colName}"/>
                <input type="hidden" name="panel" value="browse"/>
            </form>

};

(:
    Process an action.
:)
declare function browse:process-action($collection as object) as element()* {
    let $action := request:get-parameter("action", ())
    return
        util:catch("java.lang.Exception",
            if($action eq "Remove Selected") then
                browse:remove()
            else if($action eq "Create Collection") then
                browse:create-collection($collection)
            else if($action eq "Store") then
                browse:store($collection)
            else if($action eq "Upload") then
                browse:upload($collection)
            else
                (),

                An error occurred while processing the action:

                {$util:exception-message}

        )
};

(:
    Store uploaded content.
:)
declare function browse:upload($collection as object) as element() {
    let $name := request:get-parameter("name", ()),
        $docName :=
            if($name) then $name
            else request:get-uploaded-file-name("upload"),
        $file := request:get-uploaded-file("upload")
    return

Actions:

Storing uploaded content to: {$docName}

                {
                    xdb:store($collection, $docName, $file)
                }

};

(:
    Store files from an URI.

    Allowing this opens a security whole as a user can
    upload arbitrary files on the server if the process is running
    as root.
:)
declare function browse:store($collection as object) as element() {
    let $uri := request:get-parameter("uri", ()),
        $path := if(starts-with($uri, "file:")) then $uri
            else concat("file:", $uri),
        $docName := request:get-parameter("name", ())
    return

Actions:

Storing resources from URI: {$path}

                {
                    xdb:store($collection, $docName, xs:anyURI($path))
                }

};

(:
    Remove a set of resources.
:)
declare function browse:remove() as element() {
    let $resources := request:get-parameter("resource", ())
    return

Actions:

                {
                    for $resource in $resources
                    return
                        browse:remove-resource($resource)
                }

};

(:
    Remove a resource.
:)
declare function browse:remove-resource($resource as xs:string) as element()* {
    let $isBinary := util:binary-doc-available($resource)
    let $doc := if ($isBinary) then $resource else doc($resource)
    return
        if($doc) then (

Removing document: {$resource} ...
,
            xdb:remove(util:collection-name($doc), util:document-name($doc))
        ) else (

Removing collection: {$resource} ...
,
            xdb:remove($resource)
        )
};

(:
    Create a collection.
:)
declare function browse:create-collection($parent as object) as element() {
    let $newcol := request:get-parameter("create", ())
    return

Actions:

            {
                if($newcol) then
                    let $col := xdb:create-collection($parent, $newcol)
                    return

Created collection: {util:collection-name($col)}.

                else

No name specified for new collection!

            }

};

(:
    Display the contents of a collection in a table view.
:)
declare function browse:display-collection($collection as object)
as element() {
    let $colName := util:collection-name($collection)
    return

                Name
                Permissions
                Owner
                Group
                Created
                Modified
                Size (KB)

                Up

            {
                browse:display-child-collections($collection),
                browse:display-child-resources($collection)
            }

};

declare function browse:display-child-collections($collection as object)
as element()* {
    let $parent := util:collection-name($collection)
    for $child in xdb:get-child-collections($collection)
    let $path := concat($parent, '/', $child),
        $created := xdb:created($path)
    order by $child
    return

            <input type="checkbox" name="resource" value="{$path}"/>
            {xdb:decode-uri(xs:anyURI($child))}
            {xdb:permissions-to-string(xdb:get-permissions($path))}
            {xdb:get-owner($path)}
            {xdb:get-group($path)}
            {date:format-dateTime($created)}

};

declare function browse:display-child-resources($collection as object)
as element()* {
    let $parent := util:collection-name($collection)
    for $child in xdb:get-child-resources($collection)
    order by $child
    return

            <input type="checkbox" name="resource" value="{$parent}/{$child}"/>
            {xdb:decode-uri(xs:anyURI($child))}
            {xdb:permissions-to-string(xdb:get-permissions($collection, $child))}
            {xdb:get-owner($collection, $child)}
            {xdb:get-group($collection, $child)}
            {date:format-dateTime(xdb:created($collection, $child))}
            {date:format-dateTime(xdb:last-modified($collection, $child))}
            {fn:ceiling(xdb:size($collection, $child) div 1024)}

};

(:
    Get the name of the parent collection from a specified collection path.
:)
declare function browse:get-parent-collection($path as xs:string) as xs:string {
    if($path eq "/db") then
        $path
    else
        replace($path, "/[^/]*$", "")
};

(:
    Module: display and browse collections.
:)
module namespace browse="http://exist-db.org/xquery/admin-interface/browse";

declare namespace request="http://exist-db.org/xquery/request";
declare namespace xdb="http://exist-db.org/xquery/xmldb";
declare namespace util="http://exist-db.org/xquery/util";

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

(:
    Main function: outputs the page.
:)
declare function browse:main($user as xs:string, $passwd as xs:string) as element() {
    let $colName := request:get-parameter("collection", "/db"),
        $collection := xdb:collection($colName, $user, $passwd)
    return

            { browse:process-action($collection) }

Browsing Collection: {$colName}

            <form method="POST" enctype="multipart/form-data">
                {
                    browse:display-collection($collection)
                }

<input type="submit" name="action" value="Remove Selected"/>

                        <input type="submit" name="action" value="Create Collection"/>
                        New collection:

                        <input type="text" name="create" size="40"/>

                        <input type="submit" name="action" value="Upload"/>
                        <input type="file" size="30" name="upload"/>
                        Store as:

                        <input type="text" name="name" size="20"/>

                <input type="hidden" name="collection" value="{$colName}"/>
                <input type="hidden" name="panel" value="browse"/>
            </form>

};

(:
    Process an action.
:)
declare function browse:process-action($collection as object) as element()* {
    let $action := request:get-parameter("action", ())
    return
        util:catch("java.lang.Exception",
            if($action eq "Remove Selected") then
                browse:remove()
            else if($action eq "Create Collection") then
                browse:create-collection($collection)
            else if($action eq "Store") then
                browse:store($collection)
            else if($action eq "Upload") then
                browse:upload($collection)
            else
                (),

                An error occurred while processing the action:

                {$util:exception-message}

        )
};

(:
    Store uploaded content.
:)
declare function browse:upload($collection as object) as element() {
    let $name := request:get-parameter("name", ()),
        $docName :=
            if($name) then $name
            else request:get-uploaded-file-name("upload"),
        $file := request:get-uploaded-file("upload")
    return

Actions:

Storing uploaded content to: {$docName}

                {
                    xdb:store($collection, $docName, $file)
                }

};

(:
    Store files from an URI.

    Allowing this opens a security whole as a user can
    upload arbitrary files on the server if the process is running
    as root.
:)
declare function browse:store($collection as object) as element() {
    let $uri := request:get-parameter("uri", ()),
        $path := if(starts-with($uri, "file:")) then $uri
            else concat("file:", $uri),
        $docName := request:get-parameter("name", ())
    return

Actions:

Storing resources from URI: {$path}

                {
                    xdb:store($collection, $docName, xs:anyURI($path))
                }

};

(:
    Remove a set of resources.
:)
declare function browse:remove() as element() {
    let $resources := request:get-parameter("resource", ())
    return

Actions:

                {
                    for $resource in $resources
                    return
                        browse:remove-resource($resource)
                }

};

(:
    Remove a resource.
:)
declare function browse:remove-resource($resource as xs:string) as element()* {
    let $isBinary := util:binary-doc-available($resource)
    let $doc := if ($isBinary) then $resource else doc($resource)
    return
        if($doc) then (

Removing document: {$resource} ...
,
            xdb:remove(util:collection-name($doc), util:document-name($doc))
        ) else (

Removing collection: {$resource} ...
,
            xdb:remove($resource)
        )
};

(:
    Create a collection.
:)
declare function browse:create-collection($parent as object) as element() {
    let $newcol := request:get-parameter("create", ())
    return

Actions:

            {
                if($newcol) then
                    let $col := xdb:create-collection($parent, $newcol)
                    return

Created collection: {util:collection-name($col)}.

                else

No name specified for new collection!

            }

};

(:
    Display the contents of a collection in a table view.
:)
declare function browse:display-collection($collection as object)
as element() {
    let $colName := util:collection-name($collection)
    return

                Name
                Permissions
                Owner
                Group
                Created
                Modified
                Size (KB)

                Up

            {
                browse:display-child-collections($collection),
                browse:display-child-resources($collection)
            }

};

declare function browse:display-child-collections($collection as object)
as element()* {
    let $parent := util:collection-name($collection)
    for $child in xdb:get-child-collections($collection)
    let $path := concat($parent, '/', $child),
        $created := xdb:created($path)
    order by $child
    return

            <input type="checkbox" name="resource" value="{$path}"/>
            {$child}
            {xdb:permissions-to-string(xdb:get-permissions($path))}
            {xdb:get-owner($path)}
            {xdb:get-group($path)}
            {date:format-dateTime($created)}

};

declare function browse:display-child-resources($collection as object)
as element()* {
    let $parent := util:collection-name($collection)
    for $child in xdb:get-child-resources($collection)
    order by $child
    return

            <input type="checkbox" name="resource" value="{$parent}/{$child}"/>
            {$child}
            {xdb:permissions-to-string(xdb:get-permissions($collection, $child))}
            {xdb:get-owner($collection, $child)}
            {xdb:get-group($collection, $child)}
            {date:format-dateTime(xdb:created($collection, $child))}
            {date:format-dateTime(xdb:last-modified($collection, $child))}
            {fn:ceiling(xdb:size($collection, $child) div 1024)}

};

(:
    Get the name of the parent collection from a specified collection path.
:)
declare function browse:get-parent-collection($path as xs:string) as xs:string {
    if($path eq "/db") then
        $path
    else
        replace($path, "/[^/]*$", "")
};


Added stubs for remaining map views

Added stubs for remaining map views

(:~
 : DITA for Small Teams
 :
 : Link management application RESTXQ implementation.
 :
 : Copyright (c) 2015 DITA for Small Teams (dita-for-small-teams.org)
 :
 : See the BaseX RESTXQ documentation for details on how the RESTXQ
 : mechanism works.
 :
 :)
module namespace linkmgr='http://basex.org/modules/linkmgr';

import module namespace bxutil="http://dita-for-small-teams.org/xquery/modules/basex-utils";
import module namespace linkutil="http://dita-for-small-teams.org/xquery/modules/linkmgmt-utils";
import module namespace df="http://dita-for-small-teams.org/xquery/modules/dita-utils";

declare
  %rest:path("/linkmgr/maptreeView/{$docURI=.+}")
  %output:method("xhtml")
  %output:omit-xml-declaration("no")
  %output:doctype-public("-//W3C//DTD XHTML 1.0 Transitional//EN")
  %output:doctype-system("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd")
  function linkmgr:maptreeView($docURI as xs:string)
  as element(Q{http://www.w3.org/1999/xhtml}html)
{
   let $map := doc($docURI)
   let $tree := df:getMapTree($map)
   return

      <title>Map Tree for {df:getTitleText($map/*)}</title>
      <link rel="stylesheet" type="text/css" href="/static/style.css"/>

Map Tree for "{df:getTitleText($map/*)}"

      {linkmgr:reportDocDetails($map)}

       {
        linkmgr:treeToHtml($tree)
       }

};

(:~
 : Document source view
 :)
declare
  %rest:path("/linkmgr/docview/{$docURI=.+}/src")
  %output:method("xhtml")
  %output:omit-xml-declaration("no")
  %output:doctype-public("-//W3C//DTD XHTML 1.0 Transitional//EN")
  %output:doctype-system("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd")
  function linkmgr:docViewSource($docURI as xs:string)
  as element(Q{http://www.w3.org/1999/xhtml}html)
{
   let $doc := doc($docURI)
   let $title := df:getTitleText($doc/*)
   return

      <title>Source for Document {$title}</title>
      <link rel="stylesheet" type="text/css" href="/static/style.css"/>

Source for Document "{$title}"

      {linkmgr:reportDocDetails($doc)}

        {serialize($doc)}

};

(:~
 : Document dependency view
 :)
declare
  %rest:path("/linkmgr/dependencyView/{$docURI=.+}")
  %output:method("xhtml")
  %output:omit-xml-declaration("no")
  %output:doctype-public("-//W3C//DTD XHTML 1.0 Transitional//EN")
  %output:doctype-system("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd")
  function linkmgr:docViewDependencies($docURI as xs:string)
  as element(Q{http://www.w3.org/1999/xhtml}html)
{
   let $doc := doc($docURI)
   let $title := df:getTitleText($doc/*)
   return

      <title>Dependencies for Document {$title}</title>
      <link rel="stylesheet" type="text/css" href="/static/style.css"/>

Dependencies for Document "{$title}"

      {linkmgr:reportDocDetails($doc)}

Content references

List of content references goes here

Cross references

List of cross references goes here

Related Links

List of related links goes here

};

(:~
 : Document relationship table view
 :)
declare
  %rest:path("/linkmgr/reltableView/{$docURI=.+}")
  %output:method("xhtml")
  %output:omit-xml-declaration("no")
  %output:doctype-public("-//W3C//DTD XHTML 1.0 Transitional//EN")
  %output:doctype-system("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd")
  function linkmgr:docViewReltables($docURI as xs:string)
  as element(Q{http://www.w3.org/1999/xhtml}html)
{
   let $doc := doc($docURI)
   let $title := df:getTitleText($doc/*)
   return

      <title>Relationship Tables for Map {$title}</title>
      <link rel="stylesheet" type="text/css" href="/static/style.css"/>

Relationship Tables for Map "{$title}"

      {linkmgr:reportDocDetails($doc)}

Reltables

Relationship tables go here

};

(:~
 : Document relationship table view
 :)
declare
  %rest:path("/linkmgr/keyspaceView/{$docURI=.+}")
  %output:method("xhtml")
  %output:omit-xml-declaration("no")
  %output:doctype-public("-//W3C//DTD XHTML 1.0 Transitional//EN")
  %output:doctype-system("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd")
  function linkmgr:docViewKeyspaces($docURI as xs:string)
  as element(Q{http://www.w3.org/1999/xhtml}html)
{
   let $doc := doc($docURI)
   let $title := df:getTitleText($doc/*)
   return

      <title>Key Spaces for Map {$title}</title>
      <link rel="stylesheet" type="text/css" href="/static/style.css"/>

Key Spaces for Map "{$title}"

      {linkmgr:reportDocDetails($doc)}

Key Spaces

Key spaces go here

};

(:~
 : Constructs an HTML report of the details about a document
 :)
declare function linkmgr:reportDocDetails($doc as document-node()) as node()* {
   let $docURI := bxutil:getPathForDoc($doc)
   let $repo as xs:string := bxutil:getGitRepoForDoc($doc)
   let $branch as xs:string := bxutil:getGitBranchForDoc($doc)
   let $isDITA as xs:boolean := df:isDitaDoc($doc)
   return

URI: {linkmgr:makeLinkToDocSource(document-uri($doc))}

Branch: {$repo}/{$branch}

Is DITA: {$isDITA}

};

(:~
 : Takes a generic tree XML structure and generates appropriate HTML
 : markup for it.
 :
 : A tree consists of a sequence of <treeItem> elements, where each tree item
 : has the structure:
 :
 : <treeItem>
 :   label text
 :   <properties>
 :    <prop name="name">value</prop>
 :   </properties>
 :   <children>
 :    <treeItem>
 :   </children>
 : </treeItem>
 :)
declare function linkmgr:treeToHtml($tree as element(mapTree)) as node()* {

{
      for $treeItem in $tree/*
          return linkmgr:treeItemToHtml($treeItem)
    }

};

declare function linkmgr:makeLinkToDocSource($docURI as xs:string) as node()* {
     {bxutil:getPathForDocURI($docURI)}
};

declare function linkmgr:treeItemToHtml($treeItem as element()) as node()* {
    let $docURI := string($treeItem/properties/property[@name = 'uri'])
    return

      {string($treeItem/label)}
      [linkmgr:makeLinkToDocSource($docURI)]
      {if ($treeItem/children)
          then

{
             for $child in $treeItem/children/treeItem
                   return linkmgr:treeItemToHtml($child)
             }

          else ()
      }

};

(:~
 : DITA for Small Teams
 :
 : Link management application RESTXQ implementation.
 :
 : Copyright (c) 2015 DITA for Small Teams (dita-for-small-teams.org)
 :
 : See the BaseX RESTXQ documentation for details on how the RESTXQ
 : mechanism works.
 :
 :)
module namespace linkmgr='http://basex.org/modules/linkmgr';

import module namespace bxutil="http://dita-for-small-teams.org/xquery/modules/basex-utils";
import module namespace linkutil="http://dita-for-small-teams.org/xquery/modules/linkmgmt-utils";
import module namespace df="http://dita-for-small-teams.org/xquery/modules/dita-utils";

declare
  %rest:path("/linkmgr/maptreeView/{$docURI=.+}")
  %output:method("xhtml")
  %output:omit-xml-declaration("no")
  %output:doctype-public("-//W3C//DTD XHTML 1.0 Transitional//EN")
  %output:doctype-system("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd")
  function linkmgr:maptreeView($docURI as xs:string)
  as element(Q{http://www.w3.org/1999/xhtml}html)
{
   let $map := doc($docURI)
   let $tree := df:getMapTree($map)
   return

      <title>Map Tree for {df:getTitleText($map/*)}</title>
      <link rel="stylesheet" type="text/css" href="/static/style.css"/>

Map Tree for "{df:getTitleText($map/*)}"

      {linkmgr:reportDocDetails($map)}

       {
        linkmgr:treeToHtml($tree)
       }

};

(:~
 : Document source view
 :)
declare
  %rest:path("/linkmgr/docview/{$docURI=.+}/src")
  %output:method("xhtml")
  %output:omit-xml-declaration("no")
  %output:doctype-public("-//W3C//DTD XHTML 1.0 Transitional//EN")
  %output:doctype-system("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd")
  function linkmgr:docViewSource($docURI as xs:string)
  as element(Q{http://www.w3.org/1999/xhtml}html)
{
   let $doc := doc($docURI)
   let $title := df:getTitleText($doc/*)
   return

      <title>Source for Document {$title}</title>
      <link rel="stylesheet" type="text/css" href="/static/style.css"/>

Source for Document "{$title}"

      {linkmgr:reportDocDetails($doc)}

        {serialize($doc)}

};

(:~
 : Document source view
 :)
declare
  %rest:path("/linkmgr/dependencyView/{$docURI=.+}")
  %output:method("xhtml")
  %output:omit-xml-declaration("no")
  %output:doctype-public("-//W3C//DTD XHTML 1.0 Transitional//EN")
  %output:doctype-system("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd")
  function linkmgr:docViewDependencies($docURI as xs:string)
  as element(Q{http://www.w3.org/1999/xhtml}html)
{
   let $doc := doc($docURI)
   let $title := df:getTitleText($doc/*)
   return

      <title>Dependencies for Document {$title}</title>
      <link rel="stylesheet" type="text/css" href="/static/style.css"/>

Dependencies for Document "{$title}"

      {linkmgr:reportDocDetails($doc)}

Content references

List of content references goes here

Cross references

List of cross references goes here

Related Links

List of related links goes here

};

(:~
 : Constructs an HTML report of the details about a document
 :)
declare function linkmgr:reportDocDetails($doc as document-node()) as node()* {
   let $docURI := bxutil:getPathForDoc($doc)
   let $repo as xs:string := bxutil:getGitRepoForDoc($doc)
   let $branch as xs:string := bxutil:getGitBranchForDoc($doc)
   let $isDITA as xs:boolean := df:isDitaDoc($doc)
   return

URI: {linkmgr:makeLinkToDocSource(document-uri($doc))}

Branch: {$repo}/{$branch}

Is DITA: {$isDITA}

};

(:~
 : Takes a generic tree XML structure and generates appropriate HTML
 : markup for it.
 :
 : A tree consists of a sequence of <treeItem> elements, where each tree item
 : has the structure:
 :
 : <treeItem>
 :   label text
 :   <properties>
 :    <prop name="name">value</prop>
 :   </properties>
 :   <children>
 :    <treeItem>
 :   </children>
 : </treeItem>
 :)
declare function linkmgr:treeToHtml($tree as element(mapTree)) as node()* {

{
      for $treeItem in $tree/*
          return linkmgr:treeItemToHtml($treeItem)
    }

};

declare function linkmgr:makeLinkToDocSource($docURI as xs:string) as node()* {
     {bxutil:getPathForDocURI($docURI)}
};

declare function linkmgr:treeItemToHtml($treeItem as element()) as node()* {
    let $docURI := string($treeItem/properties/property[@name = 'uri'])
    return

      {string($treeItem/label)}
      [linkmgr:makeLinkToDocSource($docURI)]
      {if ($treeItem/children)
          then

{
             for $child in $treeItem/children/treeItem
                   return linkmgr:treeItemToHtml($child)
             }

          else ()
      }

};


[testsuite] Add testcase for query rewrite failure

xquery version "3.0";

(:~
 : Test query rewriting for range index.
 :
 : Expressions use the @test:stats annotation to retrieve execution statistics
 : for each test function. All comparisons should be fully optimized.
 :)
module namespace ot="http://exist-db.org/xquery/range/optimizer/test";

import module namespace range="http://exist-db.org/xquery/range" at "java:org.exist.xquery.modules.range.RangeIndexModule";
import module namespace test="http://exist-db.org/xquery/xqsuite" at "resource:org/exist/xquery/lib/xqsuite/xqsuite.xql";

declare namespace tei="http://www.tei-c.org/ns/1.0";
declare namespace stats="http://exist-db.org/xquery/profiling";

declare variable $ot:COLLECTION_CONFIG :=
    <collection xmlns="http://exist-db.org/collection-config/1.0">
        <index xmlns:xs="http://www.w3.org/2001/XMLSchema"
            xmlns:tei="http://www.tei-c.org/ns/1.0">
            <lucene>
                <text field="lucene-name" qname="name"/>
            </lucene>
            <range>
                <create match="//tei:placeName">
                    <field name="name" type="xs:string" nested="no"/>
                    <field name="type" match="@type" type="xs:string"/>
                    <field name="subtype" match="@subtype" type="xs:string"/>
                </create>
                <create qname="tei:orth" type="xs:string" collation="?lang=sr&strength=primary" case="no"/>
                <create match="//address">
                    <filter class="org.apache.lucene.analysis.core.LowerCaseFilter"/>
                    <field name="address-city" match="city" type="xs:string"/>
                    <field name="address-street" match="street" type="xs:string"/>
                    <field name="address-email" match="contact/email" type="xs:string"/>
                    <field name="address-name" match="name3" type="xs:string"/>
                </create>
                <create match="/test/address/name"/>
                <create match="/test/address/name2">
                    <filter class="org.apache.lucene.analysis.core.LowerCaseFilter"/>
                    <filter class="org.apache.lucene.analysis.miscellaneous.ASCIIFoldingFilter"/>
                </create>
                <create match="/test/address/city/@code" type="xs:integer"/>
                <create qname="@id" type="xs:string"/>
            </range>
        </index>
    </collection>;

declare variable $ot:DATA_NESTED :=
    <place xmlns="http://www.tei-c.org/ns/1.0">
        <placeName xml:id="ODB_S00004004_NAM001" xml:lang="de-DE" type="ref" subtype="inofficial">Hofthiergarten<note type="source">
                <date ana="#notBefore">1750</date>
                <date ana="#notAfter">1820</date>
            </note>
        </placeName>
        <placeName xml:id="ODB_S00004004_NAM002" xml:lang="de-DE" type="main" subtype="official">Hofthiergarten<note type="source">
                <date ana="#when">2011-08-24</date>
            </note>
        </placeName>
        <placeName xml:id="ODB_A00000393_NAM001" xml:lang="de-DE" type="main" subtype="official">Dorfprozelten<note type="source">
                <date ana="#when">2001-04-07</date>
                <bibl>
                    <ptr target="#HAB/Laube"/>
                </bibl>
            </note>
        </placeName>
    </place>;

declare variable $ot:DATA :=
    <test>
        <address id="muh">
            <name>Berta Muh</name>
            <name2>Berta Muh</name2>
            <name3>Berta Muh</name3>
            <street>Wiesenweg 14</street>
            <city code="65463">Almweide</city>
            <contact>
                <email>berta@milchvieh.org</email>
            </contact>
        </address>
        <address id="rüssel">
            <name>Rudi Rüssel</name>
            <name2>Rudi Rüssel</name2>
            <name3>Rudi Rüssel</name3>
            <street>Elefantenweg 67</street>
            <city code="65428">Rüsselsheim</city>
            <contact>
                <email>rudi@trompeter.de</email>
            </contact>
        </address>
        <address id="amsel">
            <name>Albert Amsel</name>
            <name2>Albert Amsel</name2>
            <name3>Albert Amsel</name3>
            <street>Birkenstraße 77</street>
            <city code="76878">Waldstadt</city>
            <contact>
                <email>albert@zwitschern.de</email>
            </contact>
        </address>
        <address id="reh">
            <name>Pü Reh</name>
            <name2>Pü Reh</name2>
            <name3>Pü Reh</name3>
            <street>Am Waldrand 4</street>
            <city code="89283">Wiesental</city>
            <contact>
                <email>pü@wildsau.net</email>
            </contact>
        </address>
    </test>;

declare variable $ot:DATA_SR_WITH_DIACRITICS :=
    <TEI xmlns="http://www.tei-c.org/ns/1.0">
        <teiHeader>
            <fileDesc>
                <titleStmt><title>sr with diacritics</title></titleStmt>
                <publicationStmt><distributor>sr with diacritics</distributor></publicationStmt>
                <sourceDesc><listOrg><org><name>test</name></org></listOrg></sourceDesc>
            </fileDesc>
        </teiHeader>
        <text>
            <body>
                <div>
                    <entryFree>
                        <form type="lemma">
                            <orth>Мла̀тишума</orth>
                        </form>
                        <form type="lemma">
                            <orth>Млатишума</orth>
                        </form>
                    </entryFree>
                </div>
            </body>
        </text>
    </TEI>;

declare variable $ot:COLLECTION_NAME := "optimizertest";
declare variable $ot:COLLECTION := "/db/" || $ot:COLLECTION_NAME;

declare
    %test:setUp
function ot:setup() {
    xmldb:create-collection("/db/system/config/db", $ot:COLLECTION_NAME),
    xmldb:store("/db/system/config/db/" || $ot:COLLECTION_NAME, "collection.xconf", $ot:COLLECTION_CONFIG),
    xmldb:create-collection("/db", $ot:COLLECTION_NAME),
    xmldb:store($ot:COLLECTION, "test.xml", $ot:DATA),
    xmldb:store($ot:COLLECTION, "nested.xml", $ot:DATA_NESTED),
    xmldb:store($ot:COLLECTION, "diacritics.xml", $ot:DATA_SR_WITH_DIACRITICS)
};

declare
    %test:tearDown
function ot:cleanup() {
    xmldb:remove($ot:COLLECTION),
    xmldb:remove("/db/system/config/db/" || $ot:COLLECTION_NAME)
};

declare
    %test:stats
    %test:args("Rudi Rüssel")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-eq-string($name as xs:string) {
    collection($ot:COLLECTION)//address[name = $name]
};

declare
    %test:stats
    %test:args("Rudi Rüssel")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-ne-string($name as xs:string) {
    collection($ot:COLLECTION)//address[name != $name]
};

declare
    %test:stats
    %test:args("Rudi Rüssel")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-ne-string2($name as xs:string) {
    collection($ot:COLLECTION)//address[name ne $name]
};

declare
    %test:stats
    %test:args("Rudi Rüssel")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-ne-string-self($name as xs:string) {
    collection($ot:COLLECTION)//address/name[. ne $name]
};

declare
    %test:stats
    %test:args("Rudi")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-starts-with-string($name as xs:string) {
    collection($ot:COLLECTION)//address[starts-with(name, $name)]
};

declare
    %test:stats
    %test:args("Rüssel")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-ends-with-string($name as xs:string) {
    collection($ot:COLLECTION)//address[ends-with(name, $name)]
};

declare
    %test:stats
    %test:args("udi ")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-contains-string($name as xs:string) {
    collection($ot:COLLECTION)//address[contains(name, $name)]
};

declare
    %test:stats
    %test:args("[rR]udi .*")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-matches-string($name as xs:string) {
    collection($ot:COLLECTION)//address[range:matches(name, $name)]
};

declare
    %test:stats
    %test:args("[rR]udi .*")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 1]")
function ot:optimize-matches-string-filtered($name as xs:string) {
    let $address := collection($ot:COLLECTION)//address
    return
        $address[range:matches(name, $name)]
};

declare
    %test:stats
    %test:args("Rudi Rüssel")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-eq-string-self($name as xs:string) {
    collection($ot:COLLECTION)//address/name[. = $name]
};

declare
    %test:args("Rudi Rüssel")
function ot:eq-string-self-filtered($name as xs:string) {
    let $n := collection($ot:COLLECTION)//address/name
    return
        $n[. = $name]
};

declare
    %test:stats
    %test:args(65428)
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-eq-int-attribute($code as xs:integer) {
    collection($ot:COLLECTION)//address/city[@code = $code]
};

declare
    %test:stats
    %test:args("Rudi Rüssel")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-lt-string($name as xs:string) {
    collection($ot:COLLECTION)//address[name < $name]
};

declare
    %test:args("Rudi Rüssel")
    %test:assertEquals(3)
function ot:ne-string($name as xs:string) {
    count(collection($ot:COLLECTION)//address[name != $name])
};

declare
    %test:args("Rudi Rüssel")
    %test:assertEquals(3)
function ot:ne-string-self($name as xs:string) {
    count(collection($ot:COLLECTION)//address/name[. != $name])
};

declare
    %test:args("Berta Muh")
    %test:assertEquals(1)
function ot:lt-string($name as xs:string) {
    count(collection($ot:COLLECTION)//address[name < $name])
};

declare
    %test:stats
    %test:args("Rudi Rüssel")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-le-string($name as xs:string) {
    collection($ot:COLLECTION)//address[name <= $name]
};

declare
    %test:args("Berta Muh")
    %test:assertEquals(2)
function ot:le-string($name as xs:string) {
    count(collection($ot:COLLECTION)//address[name <= $name])
};

declare
    %test:stats
    %test:args("Rudi Rüssel")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-gt-string($name as xs:string) {
    collection($ot:COLLECTION)//address[name > $name]
};

declare
    %test:args("Pü Reh")
    %test:assertEquals(1)
function ot:gt-string($name as xs:string) {
    count(collection($ot:COLLECTION)//address[name > $name])
};

declare
    %test:stats
    %test:args("Rudi Rüssel")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-ge-string($name as xs:string) {
    collection($ot:COLLECTION)//address[name > $name]
};

declare
    %test:args("Pü Reh")
    %test:assertEquals(2)
function ot:ge-string($name as xs:string) {
    count(collection($ot:COLLECTION)//address[name >= $name])
};

declare
    %test:stats
    %test:args("Rüsselsheim")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-eq-field($city as xs:string) {
    collection($ot:COLLECTION)//address[city = $city]
};

declare
    %test:args("Rüsselsheim")
    %test:assertEquals(1)
function ot:eq-field($city as xs:string) {
    count(collection($ot:COLLECTION)//address[city = $city])
};

declare
    %test:stats
    %test:args("Rüsselsheim")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-ne-field($city as xs:string) {
    collection($ot:COLLECTION)//address[city != $city]
};

declare
    %test:args("Rüsselsheim")
    %test:assertEquals(3)
function ot:ne-field($city as xs:string) {
    count(collection($ot:COLLECTION)//address[city != $city])
};

declare
    %test:stats
    %test:args("Rüsselsheim")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-gt-field($city as xs:string) {
    collection($ot:COLLECTION)//address[city > $city]
};

declare
    %test:args("Rüsselsheim")
    %test:assertEquals(2)
function ot:gt-field($city as xs:string) {
    count(collection($ot:COLLECTION)//address[city > $city])
};

declare
    %test:stats
    %test:args("Rüsselsheim")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-ge-field($city as xs:string) {
    collection($ot:COLLECTION)//address[city >= $city]
};

declare
    %test:args("Rüsselsheim")
    %test:assertEquals(3)
function ot:ge-field($city as xs:string) {
    count(collection($ot:COLLECTION)//address[city >= $city])
};

declare
    %test:stats
    %test:args("Rüsselsheim")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-lt-field($city as xs:string) {
    collection($ot:COLLECTION)//address[city < $city]
};

declare
    %test:args("Rüsselsheim")
    %test:assertEquals(1)
function ot:lt-field($city as xs:string) {
    count(collection($ot:COLLECTION)//address[city < $city])
};

declare
    %test:stats
    %test:args("Rüsselsheim")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-le-field($city as xs:string) {
    collection($ot:COLLECTION)//address[city <= $city]
};

declare
    %test:args("Rüsselsheim")
    %test:assertEquals(2)
function ot:le-field($city as xs:string) {
    count(collection($ot:COLLECTION)//address[city <= $city])
};

declare
    %test:stats
    %test:args("Rüssel")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-starts-with-field($city as xs:string) {
    collection($ot:COLLECTION)//address[starts-with(city, $city)]
};

declare
    %test:stats
    %test:args("heim")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-ends-with-field($city as xs:string) {
    collection($ot:COLLECTION)//address[ends-with(city, $city)]
};

declare
    %test:stats
    %test:args("üssel")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-contains-field($city as xs:string) {
    collection($ot:COLLECTION)//address[contains(city, $city)]
};

declare
    %test:stats
    %test:args("[rR]üssel.*")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-matches-field($city as xs:string) {
    collection($ot:COLLECTION)//address[range:matches(city, $city)]
};

declare
    %test:args("[rR]üssel.*")
function ot:matches-field-filtered($city as xs:string) {
    let $address := collection($ot:COLLECTION)//address
    return
        $address[range:matches(city, $city)]
};

declare
    %test:stats
    %test:args("Rüsselsheim", "Elefantenweg 67")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-eq-field-multi($city as xs:string, $street as xs:string) {
    collection($ot:COLLECTION)//address[city = $city][street = $street]
};

declare
    %test:args("Rüsselsheim", "Elefantenweg 67")
    %test:assertEquals(1)
function ot:eq-field-multi($city as xs:string, $street as xs:string) {
    count(collection($ot:COLLECTION)//address[city = $city][street = $street])
};

declare
    %test:args("Rüsselsheim", "Elefantenweg 67")
    %test:assertEquals(1)
function ot:eq-field-multi-filtered($city as xs:string, $street as xs:string) {
    let $address := collection($ot:COLLECTION)//address
    return
        count($address[city = $city][street = $street])
};

declare
    %test:stats
    %test:args("Rüsselsheim", "Elefantenweg 67")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-mixed-op-field($city as xs:string, $street as xs:string) {
    collection($ot:COLLECTION)//address[city > $city][street = $street]
};

declare
    %test:args("rüsselsheim", "Elefantenweg 67")
    %test:assertEquals(0)
function ot:mixed-op-field1($city as xs:string, $street as xs:string) {
    count(collection($ot:COLLECTION)//address[city > $city][street = $street])
};

declare
    %test:args("rüsselsheim", "Elefantenweg 67")
    %test:assertEquals(1)
function ot:mixed-op-field2($city as xs:string, $street as xs:string) {
    count(collection($ot:COLLECTION)//address[city >= $city][street = $street])
};

declare
    %test:stats
    %test:args("Rüsselsheim", "Elefantenweg 67")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:no-optimize-field-multi($city as xs:string, $street as xs:string) {
    collection($ot:COLLECTION)//address[street = $street][1]
};

declare
    %test:stats
    %test:args("berta@milchview.org")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-eq-field-nested($email as xs:string) {
    collection($ot:COLLECTION)//address[contact/email = $email]
};

declare
    %test:stats
    %test:args("berta@milchview.org")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-lt-field-nested($email as xs:string) {
    collection($ot:COLLECTION)//address[contact/email < $email]
};

declare
    %test:args("main", "official", "Hofthiergarten")
    %test:assertEquals("Hofthiergarten")
    %test:args("ref", "inofficial", "Hofthiergarten")
    %test:assertEquals("Hofthiergarten")
    %test:args("main", "official", "Dorfprozelten")
    %test:assertEquals("Dorfprozelten")
function ot:equality-field-nested($type as xs:string, $subtype as xs:string, $name as xs:string) {
    collection($ot:COLLECTION)//tei:placeName[@type = $type][@subtype = $subtype][. = $name]/text()
};

declare
    %test:stats
    %test:args("main", "official", "Hofthiergarten")
    %test:assertXPath("$result//stats:index[@type = 'new-range'][@optimization = 2]")
function ot:optimize-field-self($type as xs:string, $subtype as xs:string, $name as xs:string) {
    collection($ot:COLLECTION)//tei:placeName[@type = $type][@subtype = $subtype][. = $name]/text()
};

declare
    %test:assertEquals("Rudi Rüssel")
function ot:parent-attr-equals() {
    collection($ot:COLLECTION)//name[parent::address/@id = "rüssel"]/text()
};

declare
    %test:stats
    %test:assertXPath("$result//stats:index[@type = 'range'][@optimization = 0]")
function ot:optimize-parent-attr-equals() {
    collection($ot:COLLECTION)//name[parent::address/@id = "rüssel"]/text()
};

declare
    %test:assertEquals("Rudi Rüssel")
function ot:parent-nested-attr-equals() {
    collection($ot:COLLECTION)//name[parent::address[@id = "rüssel"]]/text()
};

declare
    %test:stats
    %test:assertXPath("$result//stats:index[@type = 'range'][@optimization = 0]")
function ot:optimize-parent-nested-attr-equals() {
    collection($ot:COLLECTION)//name[parent::address[@id = "rüssel"]]/text()
};

declare
    %test:assertEquals("Rudi Rüssel")
function ot:self-parent-attr-equals() {
    collection($ot:COLLECTION)//name[./parent::address/@id = "rüssel"]/text()
};

declare
    %test:assertEquals("Rudi Rüssel")
function ot:self-parent-nested-attr-equals() {
    collection($ot:COLLECTION)//name[./parent::address[@id = "rüssel"]]/text()
};

(: Filters :)

declare
    %test:args("rudi russel")
    %test:assertEquals("Rudi Rüssel")
    %test:args("rudi rüssel")
    %test:assertEquals("Rudi Rüssel")
function ot:eq-string-filtered($name as xs:string) {
    collection($ot:COLLECTION)//address[name2 = $name]/name2/text()
};

declare
    %test:args("Rudi Russel")
    %test:assertEquals(3)
function ot:ne-string-filtered($name as xs:string) {
    count(collection($ot:COLLECTION)//address[name2 != $name])
};

declare
    %test:args("russel")
    %test:assertEquals("Rudi Rüssel")
function ot:contains-string-filtered($name as xs:string) {
    collection($ot:COLLECTION)//address[contains(name2, $name)]/name2/text()
};

declare
    %test:args("Rudi Rus")
    %test:assertEquals("Rudi Rüssel")
function ot:starts-with-string-filtered($name as xs:string) {
    collection($ot:COLLECTION)//address[starts-with(name2, $name)]/name2/text()
};

declare
    %test:args("ussel")
    %test:assertEquals("Rudi Rüssel")
function ot:ends-with-string-filtered($name as xs:string) {
    collection($ot:COLLECTION)//address[ends-with(name2, $name)]/name2/text()
};

declare
    %test:args("Rudi rüssel")
    %test:assertEquals("Rudi Rüssel")
    %test:args("rudi rüssel")
    %test:assertEquals("Rudi Rüssel")
function ot:eq-field-string-filtered($name as xs:string) {
    collection($ot:COLLECTION)//address[name3 = $name]/name3/text()
};

declare
    %test:args("rudi rüssel")
    %test:assertEquals(3)
function ot:ne-field-string-filtered($name as xs:string) {
    count(collection($ot:COLLECTION)//address[name3 != $name])
};

declare
    %test:args("rüssel")
    %test:assertEquals("Rudi Rüssel")
function ot:contains-field-string-filtered($name as xs:string) {
    collection($ot:COLLECTION)//address[contains(name3, $name)]/name3/text()
};

declare
    %test:args("rudi rüs")
    %test:assertEquals("Rudi Rüssel")
function ot:starts-with-field-string-filtered($name as xs:string) {
    collection($ot:COLLECTION)//address[starts-with(name3, $name)]/name3/text()
};

declare
    %test:args("üssel")
    %test:assertEquals("Rudi Rüssel")
function ot:ends-with-field-string-filtered($name as xs:string) {
    collection($ot:COLLECTION)//address[ends-with(name3, $name)]/name3/text()
};

(: Collations :)

declare
    %test:args("Мла̀тишума")
    %test:assertEquals(2)
    %test:args("Млатишума")
    %test:assertEquals(2)
function ot:eq-string-collation-with-diacritics($name) {
    count(//tei:form[tei:orth = $name])
};

declare
    %test:args("Мла̀тишума")
    %test:assertError("range:EXXQDYFT0001")
    %test:args("Млатишума")
    %test:assertError("range:EXXQDYFT0001")
function ot:contains-string-collation-with-diacritics($name) {
    count(//tei:form[contains(tei:orth, $name)])
};

declare
    %test:args("Мла̀тишума")
    %test:assertEquals(0)
    %test:args("Млатишума")
    %test:assertEquals(0)
function ot:ne-string-collation-with-diacritics($name) {
    count(//tei:form[tei:orth != $name])
};

(:~ See XPath general comparison optimisation bug #2786 :)
declare
    %test:assertEquals(1)
function ot:nested-element-rewrite-bug() {
    let $dita :=
        <dita>
            <topic>
                <prolog>
                    <metadata>
                        <data name="topicType" value="topicValue"/>
                    </metadata>
                </prolog>
                <topic>
                    <prolog>
                        <metadata>
                            <data name="topicType" value="topicValue"/>
                        </metadata>
                    </prolog>
                </topic>
            </topic>
        </dita>
    return
      count($dita/topic/prolog//data[@name eq 'topicType']/@value)
};


Annotate MarkLogic map functions available since MarkLogic 5.0.

xquery version "1.0-ml";

(:~
 : MarkLogic map functions
 :
 : @see https://docs.marklogic.com/map
 :)
module  namespace map = "http://marklogic.com/xdmp/map";
declare namespace xs  = "http://www.w3.org/2001/XMLSchema";
declare namespace a   = "http://reecedunn.co.uk/xquery/annotations";

declare %a:since("marklogic", "5.0") function map:clear($map as map:map) as empty-sequence() external;
declare %a:since("marklogic", "6.0") function map:contains($map as map:map, $key as xs:string) as xs:boolean external;
declare %a:since("marklogic", "5.0") function map:count($map as map:map) as xs:unsignedInt external;
declare %a:since("marklogic", "5.0") function map:delete($map as map:map, $key as xs:string) as empty-sequence() external;
declare %a:since("marklogic", "7.0") function map:entry($key as xs:string, $value as item()*) as map:map external;
declare %a:since("marklogic", "5.0") function map:get($map as map:map, $key as xs:string) as item()* external;
declare %a:since("marklogic", "5.0") function map:keys($map as map:map) as xs:string* external;
declare %a:since("marklogic", "5.0") function map:map() as map:map external;
declare %a:since("marklogic", "5.0") function map:map($map as element(map:map)) as map:map external;
declare %a:since("marklogic", "7.0") function map:new() as map:map external;
declare %a:since("marklogic", "7.0") function map:new($map as element(map:map)) as map:map external;
declare %a:since("marklogic", "5.0") function map:put($map as map:map, $key as xs:string, $value as item()*) as empty-sequence() external;
declare %a:since("marklogic", "9.0") function map:set-javascript-by-ref($map as map:map, $key as xs:boolean) as empty-sequence() external;
declare %a:since("marklogic", "9.0") function map:with($map as map:map, $key as xs:string, $value as item()*) as map:map external;

xquery version "1.0-ml";

(:~
 : MarkLogic map functions
 :
 : @see https://docs.marklogic.com/6.0/map
 :)
module  namespace map = "http://marklogic.com/xdmp/map";
declare namespace xs  = "http://www.w3.org/2001/XMLSchema";
declare namespace a   = "http://reecedunn.co.uk/xquery/annotations";

declare %a:since("marklogic", "6.0") function map:clear($map as map:map) as empty-sequence() external;
declare %a:since("marklogic", "6.0") function map:contains($map as map:map, $key as xs:string) as xs:boolean external;
declare %a:since("marklogic", "6.0") function map:count($map as map:map) as xs:unsignedInt external;
declare %a:since("marklogic", "6.0") function map:delete($map as map:map, $key as xs:string) as empty-sequence() external;
declare %a:since("marklogic", "7.0") function map:entry($key as xs:string, $value as item()*) as map:map external;
declare %a:since("marklogic", "6.0") function map:get($map as map:map, $key as xs:string) as item()* external;
declare %a:since("marklogic", "6.0") function map:keys($map as map:map) as xs:string* external;
declare %a:since("marklogic", "6.0") function map:map() as map:map external;
declare %a:since("marklogic", "6.0") function map:map($map as element(map:map)) as map:map external;
declare %a:since("marklogic", "7.0") function map:new() as map:map external;
declare %a:since("marklogic", "7.0") function map:new($map as element(map:map)) as map:map external;
declare %a:since("marklogic", "6.0") function map:put($map as map:map, $key as xs:string, $value as item()*) as empty-sequence() external;
declare %a:since("marklogic", "9.0") function map:set-javascript-by-ref($map as map:map, $key as xs:boolean) as empty-sequence() external;
declare %a:since("marklogic", "9.0") function map:with($map as map:map, $key as xs:string, $value as item()*) as map:map external;


[testsuite] Extend tests on array functions

(:~
 : Tests for the array datatype and associated functions.
 :)
module namespace arr="http://exist-db.org/test/arrays";

declare namespace test="http://exist-db.org/xquery/xqsuite";

declare
    %test:args(1)
    %test:assertEquals(13)
    %test:args(3)
    %test:assertEquals(14)
function arr:function-item($pos as xs:int) {
    [13, 10, 14]($pos)
};

declare
    %test:args(1)
    %test:assertEquals(13)
    %test:args(3)
    %test:assertEquals(14)
function arr:function-item2($pos as xs:int) {
    let $a := [13, 10, 14]
    return
        $a($pos)
};

declare
    %test:args(1)
    %test:assertEquals(13)
    %test:args(3)
    %test:assertEquals(14)
function arr:function-item3($pos as xs:int) {
    let $a := [13, 10, 14]
    let $f := function($array as function(*), $position as xs:int) {
        $array($position)
    }
    return
        $f($a, $pos)
};

declare
    %test:assertError("FOAY0001")
function arr:function-item-out-of-bounds() {
    let $a := [13, 10, 14]
    return
        $a(22)
};

declare
    %test:assertError("err:XPTY0004")
function arr:function-item-invalid() {
    let $a := [13, 10, 14]
    return
        $a("x")
};

declare
    %test:args(1)
    %test:assertEmpty
    %test:args(2)
    %test:assertEquals(27, 17, 0)
function arr:square-constructor1($pos as xs:int) {
    let $a := [(), (27, 17, 0)]
    return $a($pos)
};

declare
    %test:args(1)
    %test:assertEquals("
test
")
    %test:args(2)
    %test:assertEquals(55)
function arr:square-constructor2($pos as xs:int) {
    let $a := [
test
, 55]
    return $a($pos)
};

declare
    %test:assertEquals(0)
function arr:square-constructor3() {
    let $a := []
    return array:size($a)
};

declare
    %test:args(1)
    %test:assertEquals(27)
    %test:args(2)
    %test:assertEquals(17)
function arr:curly-constructor1($pos as xs:int) {
    let $x := (27, 17, 0)
    let $a := array { $x }
    return $a($pos)
};

declare
    %test:args(1)
    %test:assertEquals(27)
    %test:args(2)
    %test:assertEquals(17)
function arr:curly-constructor2($pos as xs:int) {
    let $a := array { (), (27, 17, 0) }
    return $a($pos)
};

declare
    %test:assertEquals(2)
function arr:with-map1() {
    let $a := [ map { "a": 1, "b": 2 } ]
    return $a(1)("b")
};

declare
    %test:assertEquals(3)
function arr:with-map2() {
    let $a := map { "a": 1, "b": [2, 3, 4] }
    return $a("b")(2)
};

declare
    %test:assertEquals(5)
function arr:nested1() {
    let $a := [ [1, 2, 3], [4, 5, 6] ]
    return $a(2)(2)
};

declare
    %test:assertEquals(5)
function arr:nested2() {
    let $a := array { [1, 2, 3], [4, 5, 6] }
    return $a(2)(2)
};

declare
    %test:args(2)
function arr:size1() {
    array:size([
test
, 55])
};

declare
    %test:args(1)
function arr:size2() {
    array:size([[]])
};

declare
    %test:assertEquals(3, 4, 5)
function arr:append1() {
    array:append([1, 2], (3, 4, 5))(3)
};

declare
    %test:assertEmpty
function arr:append2() {
    array:append([1, 2], ())(3)
};

declare
    %test:assertEquals("a")
function arr:head1() {
    array:head(["a", "b"])
};

declare
    %test:assertEquals(2)
function arr:head2() {
    array:head([[1, 2], 3, 4, 5])(2)
};

declare
    %test:assertError("FOAY0001")
function arr:head-empty() {
    array:head([])
};

declare
    %test:assertEquals(2)
function arr:tail1() {
    array:tail([1, 2, 3])(1)
};

declare
    %test:assertEquals(2)
function arr:tail2() {
    array:tail([1, [2, 3]])(1)
};

declare
    %test:assertEquals(0)
function arr:tail3() {
    array:size(array:tail([1]))
};

declare
    %test:assertError("FOAY0001")
function arr:tail-empty() {
    array:tail([])
};

declare
    %test:args(2)
    %test:assertEquals("b", "c", "d")
    %test:args(5)
    %test:assertEmpty
function arr:subarray1($start as xs:int) {
    let $a := array:subarray(["a", "b", "c", "d"], $start)
    return
        $a?*
};

declare
    %test:args(5, 0)
    %test:assertEmpty
    %test:args(2, 0)
    %test:assertEmpty
    %test:args(2, 1)
    %test:assertEquals("b")
    %test:args(2, 2)
    %test:assertEquals("b", "c")
    %test:args(4, 1)
    %test:assertEquals("d")
    %test:args(1, 2)
    %test:assertEquals("a", "b")
    %test:args(1, 5)
    %test:assertError("FOAY0001")
    %test:args(0, 1)
    %test:assertError("FOAY0001")
    %test:args(1, "-1")
    %test:assertError("FOAY0002")
function arr:subarray2($start as xs:int, $length as xs:int) {
    let $a := array:subarray(["a", "b", "c", "d"], $start, $length)
    return
        $a?*
};

declare
    %test:args(1)
    %test:assertEquals("b", "c", "d")
    %test:args(2)
    %test:assertEquals("a", "c", "d")
    %test:args(4)
    %test:assertEquals("a", "b", "c")
    %test:args(0)
    %test:assertError("FOAY0001")
    %test:args(5)
    %test:assertError("FOAY0001")
function arr:remove1($pos as xs:int) {
    array:remove(["a", "b", "c", "d"], $pos)?*
};

declare
    %test:assertEmpty
function arr:remove2() {
    array:remove(["a"], 1)?*
};

declare
    %test:assertEquals("d", "c", "b", "a")
function arr:reverse1() {
    array:reverse(["a", "b", "c", "d"])?*
};

declare
    %test:assertEquals("c", "d", "a", "b")
function arr:reverse2() {
    array:reverse([("a", "b"), ("c", "d")])?*
};

declare
    %test:assertEquals("1", "2", "3", "4", "5")
function arr:reverse3() {
    array:reverse([(1 to 5)])?*
};

declare
    %test:assertEmpty
function arr:reverse4() {
    array:reverse([])?*
};

declare
    %test:assertEmpty
function arr:join1() {
    array:join(())?*
};

declare
    %test:assertEquals("a", "b", "c", "d")
function arr:join2() {
    array:join((["a", "b"], ["c", "d"], []))?*
};

declare
    %test:assertEquals(5)
function arr:join3() {
    array:size(array:join((["a", "b"], ["c", "d"], [["e", "f"]])))
};

declare
    %test:assertEquals("A", "B", "C", "D")
function arr:for-each1() {
    array:for-each(["a", "b", "c", "d"], upper-case#1)?*
};

declare
    %test:assertEquals("false", "false", "true", "true")
function arr:for-each2() {
    array:for-each(["a", "b", 1, 2], function($z) { $z instance of xs:integer })?*
};

declare
    %test:assertEquals("1", "2")
function arr:filter1() {
    array:filter(["a", "b", 1, 2], function($z) { $z instance of xs:integer })?*
};

declare
    %test:assertEquals("a", "b", 1)
function arr:filter2() {
    array:filter(["a", "b", "", 0, 1], boolean#1)?*
};

declare
    %test:assertEquals("the cat", "on the mat")
function arr:filter3() {
    array:filter(["the cat", "sat", "on the mat"], function($s) { count(tokenize($s, " ")) gt 1 })?*
};

declare
    %test:assertFalse
function arr:fold-left1() {
    array:fold-left([true(), true(), false()], true(), function($x, $y) { $x and $y })
};

declare
    %test:assertTrue
function arr:fold-left2() {
    array:fold-left([true(), true(), false()], false(), function($x, $y) { $x or $y })
};

declare
    %test:assertEquals(1)
function arr:fold-left3() {
    array:fold-left([], 1, function($x, $y) { $x + $y })
};

declare
    %test:assertEquals(8)
function arr:fold-left4() {
    array:fold-left(["abc", "def", "gh"], 0, function($x, $y) { $x + string-length($y) })
};

declare
    %test:assertEquals("abcdefgh")
    %test:pending
function arr:fold-left5() {
    array:fold-left(["abc", "def", "gh"], "a", function($x, $y) { $x || $y })
};

declare
    %test:assertEquals(1)
function arr:fold-left6() {
    array:fold-left([1, 2], (), function($x, $y) { [$x, $y] })?1?2
};

declare
    %test:assertFalse
function arr:fold-right1() {
    array:fold-right([true(), true(), false()], true(), function($x, $y) { $x and $y })
};

declare
    %test:assertTrue
function arr:fold-right2() {
    array:fold-right([true(), true(), false()], false(), function($x, $y) { $x or $y })
};

declare
    %test:assertEquals(2)
function arr:fold-right3() {
    array:fold-right([1, 2, 3], (), function($x, $y) { [$x, $y] })?2?1
};

declare
    %test:assertEquals(5, 4, 3, 2, 1)
function arr:fold-right4() {
    array:fold-right(
        array { 1 to 5 },
        (),
        function($a, $b) { $b, $a }
    )
};

declare
    %test:assertEquals("AB", "BC", "CD")
function arr:for-each-pair1() {
    let $a := ["A", "B", "C", "D"]
    return
        array:for-each-pair($a, array:tail($a), concat#2)?*
};

declare
    %test:assertEquals(5, 7, 9)
function arr:for-each-pair2() {
    array:for-each-pair(
        array { 1 to 3 },
        array { 4 to 6 },
        function($a, $b) { $a + $b }
    )?*
};

declare
    %test:assertEmpty
function arr:for-each-pair3() {
    array:for-each-pair(
        [],
        array { 4 to 6 },
        function($a, $b) { $a + $b }
    )?*
};

declare
    %test:assertEquals(1, 4, 6, 5, 3)
function arr:flatten1() {
    array:flatten([1, 4, 6, 5, 3])
};

declare
    %test:assertEquals(1, 2, 5, 10, 11, 12, 13)
function arr:flatten2() {
    array:flatten(([1, 2, 5], [[10, 11], 12], [], 13))
};

declare
    %test:assertEquals(1, 1, 0, 1, 1)
function arr:flatten3() {
    array:flatten((1, [(1, 0), (1, 1)]))
};

declare
    %test:assertEmpty
function arr:flatten4() {
    array:flatten(())
};

declare
    %test:assertEquals("a", "b", "x", "c", "d")
function arr:insert-before1() {
    array:insert-before(["a", "b", "c", "d"], 3, "x")?*
};

declare
    %test:assertEquals("x", "y")
function arr:insert-before2() {
    array:insert-before(["a", "b", "c", "d"], 3, ("x", "y"))?3
};

declare
    %test:assertEquals("a", "b", "c", "d", "x")
function arr:insert-before3() {
    array:insert-before(["a", "b", "c", "d"], 5, "x")?*
};

declare
    %test:assertEquals("array")
function arr:array-type1() {
    let $a := [1, 2]
    return
        typeswitch($a)
            case array(*) return
                "array"
            default return
                "no array"
};

(:~
 : Tests for the array datatype and associated functions.
 :)
module namespace arr="http://exist-db.org/test/arrays";

declare namespace test="http://exist-db.org/xquery/xqsuite";

declare
    %test:args(1)
    %test:assertEquals(13)
    %test:args(3)
    %test:assertEquals(14)
function arr:function-item($pos as xs:int) {
    [13, 10, 14]($pos)
};

declare
    %test:args(1)
    %test:assertEquals(13)
    %test:args(3)
    %test:assertEquals(14)
function arr:function-item2($pos as xs:int) {
    let $a := [13, 10, 14]
    return
        $a($pos)
};

declare
    %test:args(1)
    %test:assertEquals(13)
    %test:args(3)
    %test:assertEquals(14)
function arr:function-item3($pos as xs:int) {
    let $a := [13, 10, 14]
    let $f := function($array as function(*), $position as xs:int) {
        $array($position)
    }
    return
        $f($a, $pos)
};

declare
    %test:assertError("FOAY0001")
function arr:function-item-out-of-bounds() {
    let $a := [13, 10, 14]
    return
        $a(22)
};

declare
    %test:assertError("err:XPTY0004")
function arr:function-item-invalid() {
    let $a := [13, 10, 14]
    return
        $a("x")
};

declare
    %test:args(1)
    %test:assertEmpty
    %test:args(2)
    %test:assertEquals(27, 17, 0)
function arr:square-constructor1($pos as xs:int) {
    let $a := [(), (27, 17, 0)]
    return $a($pos)
};

declare
    %test:args(1)
    %test:assertEquals("
test
")
    %test:args(2)
    %test:assertEquals(55)
function arr:square-constructor2($pos as xs:int) {
    let $a := [
test
, 55]
    return $a($pos)
};

declare
    %test:assertEquals(0)
function arr:square-constructor3() {
    let $a := []
    return array:size($a)
};

declare
    %test:args(1)
    %test:assertEquals(27)
    %test:args(2)
    %test:assertEquals(17)
function arr:curly-constructor1($pos as xs:int) {
    let $x := (27, 17, 0)
    let $a := array { $x }
    return $a($pos)
};

declare
    %test:args(1)
    %test:assertEquals(27)
    %test:args(2)
    %test:assertEquals(17)
function arr:curly-constructor2($pos as xs:int) {
    let $a := array { (), (27, 17, 0) }
    return $a($pos)
};

declare
    %test:assertEquals(2)
function arr:with-map1() {
    let $a := [ map { "a": 1, "b": 2 } ]
    return $a(1)("b")
};

declare
    %test:assertEquals(3)
function arr:with-map2() {
    let $a := map { "a": 1, "b": [2, 3, 4] }
    return $a("b")(2)
};

declare
    %test:assertEquals(5)
function arr:nested1() {
    let $a := [ [1, 2, 3], [4, 5, 6] ]
    return $a(2)(2)
};

declare
    %test:assertEquals(5)
function arr:nested2() {
    let $a := array { [1, 2, 3], [4, 5, 6] }
    return $a(2)(2)
};

declare
    %test:args(2)
function arr:size() {
    array:size([
test
, 55])
};

declare
    %test:assertEquals(3, 4, 5)
function arr:append1() {
    array:append([1, 2], (3, 4, 5))(3)
};

declare
    %test:assertEmpty
function arr:append2() {
    array:append([1, 2], ())(3)
};

declare
    %test:assertEquals("a")
function arr:head1() {
    array:head(["a", "b"])
};

declare
    %test:assertEquals(2)
function arr:head2() {
    array:head([[1, 2], 3, 4, 5])(2)
};

declare
    %test:assertError("FOAY0001")
function arr:head-empty() {
    array:head([])
};

declare
    %test:assertEquals(2)
function arr:tail1() {
    array:tail([1, 2, 3])(1)
};

declare
    %test:assertEquals(2)
function arr:tail2() {
    array:tail([1, [2, 3]])(1)
};

declare
    %test:assertEquals(0)
function arr:tail3() {
    array:size(array:tail([1]))
};

declare
    %test:assertError("FOAY0001")
function arr:tail-empty() {
    array:tail([])
};

declare
    %test:args(2)
    %test:assertEquals("b", 3)
function arr:subarray1($start as xs:int) {
    let $a := array:subarray(["a", "b", "c", "d"], $start)
    return
        ($a(1), array:size($a))
};

declare
    %test:assertEquals("array")
function arr:array-type1() {
    let $a := [1, 2]
    return
        typeswitch($a)
            case array(*) return
                "array"
            default return
                "no array"
};


missed this file in last checkin  minor changes: Adding validation for "Name" while creating new entities Adding "required" indicator "*" mark on registration authority tab Modifying name and adding description to config tasks in mdrQuery and DomainModelGenerator Making preferred radio button selected for this release eliminating new concept relationships

declare namespace openMDR = "http://www.cagrid.org/schema/openMDR";
declare namespace ISO11179= "http://www.cagrid.org/schema/ISO11179";

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";

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";

let $data-elements := lib-util:mdrElements('data_element')[.//openMDR:registration_status ne 'Superseded'][.//openMDR:registration_status ne 'Retired']
let $data-element-concepts := lib-util:mdrElements('data_element_concept')[.//openMDR:registration_status ne 'Superseded'][.//openMDR:registration_status ne 'Retired']
let $value-domains := lib-util:mdrElements('value_domain')[.//openMDR:registration_status ne 'Superseded'][.//openMDR:registration_status ne 'Retired']
return
   lib-rendering:txfrm-webpage('broken references',
         <broken-refs>
            {
            (:
            for $data-element in $data-elements
            let $id := lib-util:mdrElementId($data-element)
            where empty(lib-util:mdrElement('representation_class',$data-element//openMDR:typed_by)//openMDR:administered_item_administration_record)
            return
               element broken-ref {
                  attribute from {'data_element'},
                  attribute to {'representation_class'},
                  attribute id {$id},
                  xs:string($data-element//openMDR:typed_by)
                  },

            :)
            for $data-element in $data-elements
            let $id := lib-util:mdrElementId($data-element)
            where empty(lib-util:mdrElement('value_domain',$data-element//openMDR:representing)//openMDR:administered_item_administration_record)
            return
               element broken-ref {
                  attribute from {'data_element'},
                  attribute to {'value_domain'},
                  attribute id {$id},
                  xs:string($data-element//openMDR:representing)
                  },
            for $data-element in $data-elements
            let $id := lib-util:mdrElementId($data-element)
            where empty(lib-util:mdrElement('data_element_concept',$data-element//openMDR:expressing)//openMDR:administered_item_administration_record)
            return
               element broken-ref {
                  attribute from {'data_element'},
                  attribute to {'data_element_concept'},
                  attribute id {$id},
                  xs:string($data-element//openMDR:expressing)
                  },
            for $data-element in $data-elements
            let $id := lib-util:mdrElementId($data-element)
            where exists($data-element//@deriving)
            return
               for $deriving in $data-element//@deriving
               where empty(lib-util:mdrElement('data_element',xs:string($deriving))//openMDR:administered_item_administration_record)
               return
                  element broken-ref {
                     attribute from {'data_element'},
                     attribute to {'data_element'},
                     attribute id {$id},
                     xs:string($deriving)
                     },
            for $data-element-concept in $data-element-concepts
            let $id := lib-util:mdrElementId($data-element-concept)
            where empty(lib-util:mdrElement('object_class',$data-element-concept//openMDR:data_element_concept_object_class)//openMDR:administered_item_administration_record)
            return
                  element broken-ref {
                     attribute from {'data_element_concept'},
                     attribute to {'object-class'},
                     attribute id {$id},
                     xs:string($data-element-concept//openMDR:data_element_concept_object_class)
                     },
            for $data-element-concept in $data-element-concepts
            let $id := lib-util:mdrElementId($data-element-concept)
            where empty(lib-util:mdrElement('property',$data-element-concept//openMDR:data_element_concept_property)//openMDR:administered_item_administration_record)
            return
                  element broken-ref {
                     attribute from {'data_element_concept'},
                     attribute to {'property'},
                     attribute id {$id},
                     xs:string($data-element-concept//openMDR:data_element_concept_property)
                     },
            for $data-element-concept in $data-element-concepts
            let $id := lib-util:mdrElementId($data-element-concept)
            where empty(lib-util:mdrElement('conceptual_domain',$data-element-concept//openMDR:data_element_concept_conceptual_domain)//openMDR:administered_item_administration_record)
            return
                  element broken-ref {
                     attribute from {'data_element_concept'},
                     attribute to {'conceptual_domain'},
                     attribute id {$id},
                     xs:string($data-element-concept//openMDR:data_element_concept_conceptual_domain)
                     },
            for $value-domain in $value-domains
            let $id := lib-util:mdrElementId($value-domain)
            where empty(lib-util:mdrElement('conceptual_domain',$value-domain//openMDR:representing[1])//openMDR:administered_item_administration_record)
            return
                  element broken-ref {
                     attribute from {'value_domain'},
                     attribute to {'conceptual_domain'},
                     attribute id {$id},
                     xs:string($value-domain//openMDR:representing)
                     },
            for $value-domain in $value-domains
            let $id := lib-util:mdrElementId($value-domain)
            where empty(lib-util:mdrElement('data_type',$value-domain//openMDR:value_domain_datatype))
            return
                  element broken-ref {
                     attribute from {'value_domain'},
                     attribute to {'datatype'},
                     attribute id {$id},
                     xs:string($value-domain//openMDR:value_domain_datatype)
                     }
            (:
                     ,
            for $value-domain in $value-domains
            let $id := lib-util:mdrElementId($value-domain)
            where empty(lib-util:mdrElement('representation_class',$value-domain//openMDR:typed_by)//openMDR:administered_item_administration_record)
            return
               element broken-ref {
                  attribute from {'value_domain'},
                  attribute to {'representation_class'},
                  attribute id {$id},
                  xs:string($value-domain//openMDR:typed_by)
                  },

            for $value-domain in $value-domains
            let $id := lib-util:mdrElementId($value-domain)
            where empty(lib-util:mdrElement('unit_of_measure', $value-domain//openMDR:value_domain_unit_of_measure))
            return
                  element broken-ref {
                     attribute from {'value_domain'},
                     attribute to {'unit_of_measure'},
                     attribute id {$id},
                     xs:string($value-domain//openMDR:value_domain_unit_of_measure)
                     }
          :)
            }
         </broken-refs>
         )

declare namespace openMDR = "http://www.cagrid.org/schema/openMDR";
declare namespace ISO11179= "http://www.cagrid.org/schema/ISO11179";

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";

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";

let $data-elements := lib-util:mdrElements('data_element')[.//openMDR:registration_status ne 'Superseded'][.//openMDR:registration_status ne 'Retired']
let $data-element-concepts := lib-util:mdrElements('data_element_concept')[.//openMDR:registration_status ne 'Superseded'][.//openMDR:registration_status ne 'Retired']
let $value-domains := lib-util:mdrElements('value_domain')[.//openMDR:registration_status ne 'Superseded'][.//openMDR:registration_status ne 'Retired']
return
   lib-rendering:txfrm-webpage('broken references',
         <broken-refs>
            {
            for $data-element in $data-elements
            let $id := lib-util:mdrElementId($data-element)
            where empty(lib-util:mdrElement('representation_class',$data-element//openMDR:typed_by)//openMDR:administered_item_administration_record)
            return
               element broken-ref {
                  attribute from {'data_element'},
                  attribute to {'representation_class'},
                  attribute id {$id},
                  xs:string($data-element//openMDR:typed_by)
                  },
            for $data-element in $data-elements
            let $id := lib-util:mdrElementId($data-element)
            where empty(lib-util:mdrElement('value_domain',$data-element//openMDR:representing)//openMDR:administered_item_administration_record)
            return
               element broken-ref {
                  attribute from {'data_element'},
                  attribute to {'value_domain'},
                  attribute id {$id},
                  xs:string($data-element//openMDR:representing)
                  },
            for $data-element in $data-elements
            let $id := lib-util:mdrElementId($data-element)
            where empty(lib-util:mdrElement('data_element_concept',$data-element//openMDR:expressing)//openMDR:administered_item_administration_record)
            return
               element broken-ref {
                  attribute from {'data_element'},
                  attribute to {'data_element_concept'},
                  attribute id {$id},
                  xs:string($data-element//openMDR:expressing)
                  },
            for $data-element in $data-elements
            let $id := lib-util:mdrElementId($data-element)
            where exists($data-element//@deriving)
            return
               for $deriving in $data-element//@deriving
               where empty(lib-util:mdrElement('data_element',xs:string($deriving))//openMDR:administered_item_administration_record)
               return
                  element broken-ref {
                     attribute from {'data_element'},
                     attribute to {'data_element'},
                     attribute id {$id},
                     xs:string($deriving)
                     },
            for $data-element-concept in $data-element-concepts
            let $id := lib-util:mdrElementId($data-element-concept)
            where empty(lib-util:mdrElement('object_class',$data-element-concept//openMDR:data_element_concept_object_class)//openMDR:administered_item_administration_record)
            return
                  element broken-ref {
                     attribute from {'data_element_concept'},
                     attribute to {'object-class'},
                     attribute id {$id},
                     xs:string($data-element-concept//openMDR:data_element_concept_object_class)
                     },
            for $data-element-concept in $data-element-concepts
            let $id := lib-util:mdrElementId($data-element-concept)
            where empty(lib-util:mdrElement('property',$data-element-concept//openMDR:data_element_concept_property)//openMDR:administered_item_administration_record)
            return
                  element broken-ref {
                     attribute from {'data_element_concept'},
                     attribute to {'property'},
                     attribute id {$id},
                     xs:string($data-element-concept//openMDR:data_element_concept_property)
                     },
            for $data-element-concept in $data-element-concepts
            let $id := lib-util:mdrElementId($data-element-concept)
            where empty(lib-util:mdrElement('conceptual_domain',$data-element-concept//openMDR:data_element_concept_conceptual_domain)//openMDR:administered_item_administration_record)
            return
                  element broken-ref {
                     attribute from {'data_element_concept'},
                     attribute to {'conceptual_domain'},
                     attribute id {$id},
                     xs:string($data-element-concept//openMDR:data_element_concept_conceptual_domain)
                     },
            for $value-domain in $value-domains
            let $id := lib-util:mdrElementId($value-domain)
            where empty(lib-util:mdrElement('conceptual_domain',$value-domain//openMDR:representing[1])//openMDR:administered_item_administration_record)
            return
                  element broken-ref {
                     attribute from {'value_domain'},
                     attribute to {'conceptual_domain'},
                     attribute id {$id},
                     xs:string($value-domain//openMDR:representing)
                     },
            for $value-domain in $value-domains
            let $id := lib-util:mdrElementId($value-domain)
            where empty(lib-util:mdrElement('data_type',$value-domain//openMDR:value_domain_datatype))
            return
                  element broken-ref {
                     attribute from {'value_domain'},
                     attribute to {'datatype'},
                     attribute id {$id},
                     xs:string($value-domain//openMDR:value_domain_datatype)
                     }
            (:
                     ,
            for $value-domain in $value-domains
            let $id := lib-util:mdrElementId($value-domain)
            where empty(lib-util:mdrElement('representation_class',$value-domain//openMDR:typed_by)//openMDR:administered_item_administration_record)
            return
               element broken-ref {
                  attribute from {'value_domain'},
                  attribute to {'representation_class'},
                  attribute id {$id},
                  xs:string($value-domain//openMDR:typed_by)
                  },

            for $value-domain in $value-domains
            let $id := lib-util:mdrElementId($value-domain)
            where empty(lib-util:mdrElement('unit_of_measure', $value-domain//openMDR:value_domain_unit_of_measure))
            return
                  element broken-ref {
                     attribute from {'value_domain'},
                     attribute to {'unit_of_measure'},
                     attribute id {$id},
                     xs:string($value-domain//openMDR:value_domain_unit_of_measure)
                     }
          :)
            }
         </broken-refs>
         )


Typo.

Typo.

jsoniq version "1.0";

(:
 : 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.
:)

(:~
 :
Base64 encoding and decoding.

 :
 : @author Matthias Brantner
 :
 : @project Zorba/Data Converters/Base 64
 :)
module namespace base64 = "http://zorba.io/modules/base64";

declare namespace zerr = "http://zorba.io/modules/zorba-errors";

declare namespace ver = "http://www.zorba-xquery.com/options/versioning";
declare option ver:module-version "1.0";

(:~
 :
Decode a base64Binary.

 :
 :
The function assumes that the content after decoding is valid
 : UTF-8.

 :
 : @param $base64 The base64Binary item to decode
 : @return the base64-decoded value as string
 : @error zerr:ZOSE0006 if $base64 contains invalid base-64 data.
 :)
declare function base64:decode($base64 as base64Binary)
as string external;

(:~
 :
Decode a base64Binary.

 :
 :
The function assumes that the content after decoding has
 : the given encoding.

 :
 : @param $base64 The base64Binary item to decode
 : @param $encoding The encoding of the string after base64-decoding it.
 : The encoding parameter is case insensitive.
 :
 : @return the base64-decoded value as a string
 :
 : @error zerr:ZXQP0006 if the given encoding is invalid or not supported.
 : "ASCII" and "UTF-8" are guaranteed to be supported; other encodings
 : may be supported depending on the installation.
 : @error zerr:ZOSE0006 if $base64 contains invalid base-64 data.
 :)
declare function base64:decode(
  $base64 as base64Binary,
  $encoding as string)
as string external;

(:~
 :
Encode a string as base64Binary.

 :
 : @param $string The item whose string-value should be encoded
 : @return the base64-encoded string-value of the item parameter
 :)
declare function base64:encode($string as string) as base64Binary external;

jsoniq version "1.0";

(:
 : 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.
:)

(:~
 :
Base64 encoding and decoding.

 :
 : @author Matthias Brantner
 :
 : @project Zorba/Data Converters/Base 64
 :)
module namespace base64 = "http://zorba.io/modules/base64";

declare namespace zerr = "http://zorba.io/modules/zorba-errors";

declare namespace ver = "http://www.zorba-xquery.com/options/versioning";
declare option ver:module-version "1.0";

(:~
 :
Decode a base64Binary.

 :
 :
The function assumes that the content after decoding is valid
 : UTF-8.

 :
 : @param $base64 The base64Binary item to decode
 : @return the base64-decoded value as string
 : @error zerr:ZOSE0006 if $base64 contains invalid base-64 data.
 :)
declare function base64:decode($base64 as base64Binary)
as string external;

(:~
 :
Decode a base64Binary.

 :
 : <>The function assumes that the content after decoding has
 : the given encoding.

 :
 : @param $base64 The base64Binary item to decode
 : @param $encoding The encoding of the string after base64-decoding it.
 : The encoding parameter is case insensitive.
 :
 : @return the base64-decoded value as a string
 :
 : @error zerr:ZXQP0006 if the given encoding is invalid or not supported.
 : "ASCII" and "UTF-8" are guaranteed to be supported; other encodings
 : may be supported depending on the installation.
 : @error zerr:ZOSE0006 if $base64 contains invalid base-64 data.
 :)
declare function base64:decode(
  $base64 as base64Binary,
  $encoding as string)
as string external;

(:~
 :
Encode a string as base64Binary.

 :
 : @param $string The item whose string-value should be encoded
 : @return the base64-encoded string-value of the item parameter
 :)
declare function base64:encode($string as string) as base64Binary external;


Experiments with simple queries on front page.

declare default element namespace "http://www.w3.org/1999/xhtml";

import module namespace logx="http://cefn.com/logx" at "lib/logx.xq";

logx:webpage(
    for $doc in $logx:collection
        let $textcount := count($doc//p//text())
        order by $textcount descending
        return
            <div>
        {$textcount} {logx:editor-link(($doc//h1[1]))}
    </div>
)

declare default element namespace "http://www.w3.org/1999/xhtml";

import module namespace logx="http://cefn.com/logx" at "lib/logx.xq";

logx:webpage(
    for $doc in $logx:collection
        return <div>
        {logx:editor-link(($doc//h1[1]))}
    </div>
)


Introduced richer separation handling for authors


Fixed bad character

Fixed bad character

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

xquery version "1.0";
(: $Id$ :)
(:
    Module: display and kill running xqueries
:)

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

declare namespace request="http://exist-db.org/xquery/request";
declare namespace xdb="http://exist-db.org/xquery/xmldb";
declare namespace util="http://exist-db.org/xquery/util";
declare namespace system="http://exist-db.org/xquery/system";

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

declare variable $xqueries:MAX-STRING-KEY-LENGTH					:= 1024;

(:
    Main function: outputs the page.
:)
declare function xqueries:main() as element()
{

        { xqueries:process-action() }

Running XQueries

        <form method="POST" enctype="multipart/form-data">

            {
                xqueries:display-xqueries()
            }

            <input type="submit" name="action" value="Kill Selected"/>
            <input type="hidden" name="panel" value="xqueries"/>
        </form>

Running Jobs

			{
				xqueries:display-processes()
			}

			<form>
				<input type="hidden" name="panel" value="xqueries"/>
				<input type="submit" value="Refresh"/>
			</form>

		{if (util:is-module-registered('http://exist-db.org/xquery/scheduler'))
		then

Scheduled Jobs

				{
					xqueries:display-scheduled-processes()
				}

		else ()
		}

};

declare function xqueries:display-processes() {
	let $processes := system:get-running-jobs()//system:job
	return
		if (empty($processes)) then

No long running jobs are active right now.

		else

					ID
					Action
					Info
					Running Since

				{
					for $proc in $processes
					return
						xqueries:display-process($proc)
				}

};

declare function xqueries:display-process($proc as element(system:job)) {

		{$proc/@id/string()}
		{$proc/@action/string()}
		{$proc/@info/string()}
		{$proc/@start/string()}

};

declare function xqueries:display-scheduled-processes() {
	let $processes := system:get-scheduled-jobs()//system:job
	return
		if (empty($processes)) then

No scheduled jobs are active right now.

		else

					Group
					Name
					Start
					End
					Current
					Next
					Final
					Expression
					State
					Running

				{
					for $proc in $processes
					return
						xqueries:display-scheduled-process($proc)
				}

};

declare function xqueries:display-scheduled-process($proc as element(system:job)) {

        {$proc/@group/string()}
        {$proc/@name/string()}
        {$proc/@startTime/string()}
        {$proc/@endTime/string()}
        {$proc/@fireTime/string()}
        {$proc/@nextFireTime/string()}
        {$proc/@finalFireTime/string()}
        {$proc/@triggerExpression/string()}
        {$proc/@triggerState/string()}
        {$proc/@running/string()}

};(:
    Process an action.
:)
declare function xqueries:process-action() as element()*
{
    let $action := request:get-parameter( "action", () )

    return
        util:catch("java.lang.Exception",
            if( $action eq "Kill Selected" ) then (
                xqueries:kill-xquery()
            ) else(),

                An error occurred while processing the action:

                { $util:exception-message }

        )
};

(:
    Kill a running XQuery
:)
declare function xqueries:kill-xquery() as element()*
{
     let $xqueryIDs := request:get-parameter( "xqueryID", () )

     return
	     for $xqueryID in $xqueryIDs
	     return system:kill-running-xquery( xs:integer( $xqueryID ) )

};

(:
    Display the running xqueries in a table view.
:)
declare function xqueries:display-xqueries() as element()
{

            ID
            Type
            Source
            Started
            Status

        {
            xqueries:display-xquery()
        }

};

declare function xqueries:display-xquery() as element()*
{
    for $xquery in system:get-running-xqueries()//system:xquery

    let $id 	:= $xquery/@id
    let $type 	:= $xquery/@sourceType
    let $key 	:= $xquery/system:sourceKey/text()
    let $src    := if( $type != "String" or string-length( $key ) < $xqueries:MAX-STRING-KEY-LENGTH ) then $key else concat( substring( $key, 0, $xqueries:MAX-STRING-KEY-LENGTH - 1 ), "..." )
    let $started  := $xquery/@started
    let $status := if( $xquery/@terminating = "true" ) then "terminating" else "running"

    order by $id
    return

            <input type="checkbox" name="xqueryID" value="{ $id }"/>
            { xs:string( $id ) }
            { xs:string( $type ) }
            { $src }
            { xs:string($started) }
            { $status }

};

xquery version "1.0";
(: $Id$ :)
(:
    Module: display and kill running xqueries
:)

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

declare namespace request="http://exist-db.org/xquery/request";
declare namespace xdb="http://exist-db.org/xquery/xmldb";
declare namespace util="http://exist-db.org/xquery/util";
declare namespace system="http://exist-db.org/xquery/system";

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

declare variable $xqueries:MAX-STRING-KEY-LENGTH					:= 1024;

(:
    Main function: outputs the page.
:)
declare function xqueries:main() as element()
{

        { xqueries:process-action() }

Running XQueries

        <form method="POST" enctype="multipart/form-data">

            {
                xqueries:display-xqueries()
            }

            <input type="submit" name="action" value="Kill Selected"/>
            <input type="hidden" name="panel" value="xqueries"/>
        </form>

Running Jobs

			{
				xqueries:display-processes()
			}

			<form>
				<input type="hidden" name="panel" value="xqueries"/>
				<input type="submit" value="Refresh"/>
			</form>

		{if (util:is-module-registered('http://exist-db.org/xquery/scheduler'))
		then

Scheduled Jobs

				{
					xqueries:display-scheduled-processes()
				}

		else ()
		}

};

declare function xqueries:display-processes() {
	let $processes := system:get-running-jobs()//system:job
	return
		if (empty($processes)) then

No long running jobs are active right now.

		else

					ID
					Action
					Info
					Running Since

				{
					for $proc in $processes
					return
						xqueries:display-process($proc)
				}

};

declare function xqueries:display-process($proc as element(system:job)) {

		{$proc/@id/string()}
		{$proc/@action/string()}
		{$proc/@info/string()}
		{$proc/@start/string()}

};

declare function xqueries:display-scheduled-processes() {
	let $processes := system:get-scheduled-jobs()//system:job
	return
		if (empty($processes)) then

No scheduled jobs are active right now.

		else

					Group
					Name
					Start
					End
					Current
					Next
					Final
					Expression
					State
					Running

				{
					for $proc in $processes
					return
						xqueries:display-scheduled-process($proc)
				}

};

declare function xqueries:display-scheduled-process($proc as element(system:job)) {

        {$proc/@group/string()}
        {$proc/@name/string()}
        {$proc/@startTime/string()}
        {$proc/@endTime/string()}
        {$proc/@fireTime/string()}
        {$proc/@nextFireTime/string()}
        {$proc/@finalFireTime/string()}
        {$proc/@triggerExpression/string()}
        {$proc/@triggerState/string()}
        {$proc/@running/string()}

};(:
    Process an action.
:)
declare function xqueries:process-action() as element()*
{
    let $action := request:get-parameter( "action", () )

    return
        util:catch("java.lang.Exception",
            if( $action eq "Kill Selected" ) then (
                xqueries:kill-xquery()
            ) else(),

                An error occurred while processing the action:

                { $util:exception-message }

        )
};

(:
    Kill a running XQuery
:)
declare function xqueries:kill-xquery() as element()*
{
     let $xqueryIDs := request:get-parameter( "xqueryID", () )

     return
	     for $xqueryID in $xqueryIDs
	     return system:kill-running-xquery( xs:integer( $xqueryID ) )

};

(:
    Display the running xqueries in a table view.
:)
declare function xqueries:display-xqueries() as element()
{

            ID
            Type
            Source
            Started</th˘
            Status

        {
            xqueries:display-xquery()
        }

};

declare function xqueries:display-xquery() as element()*
{
    for $xquery in system:get-running-xqueries()//system:xquery

    let $id 	:= $xquery/@id
    let $type 	:= $xquery/@sourceType
    let $key 	:= $xquery/system:sourceKey/text()
    let $src    := if( $type != "String" or string-length( $key ) < $xqueries:MAX-STRING-KEY-LENGTH ) then $key else concat( substring( $key, 0, $xqueries:MAX-STRING-KEY-LENGTH - 1 ), "..." )
    let $started  := $xquery/@started
    let $status := if( $xquery/@terminating = "true" ) then "terminating" else "running"

    order by $id
    return

            <input type="checkbox" name="xqueryID" value="{ $id }"/>
            { xs:string( $id ) }
            { xs:string( $type ) }
            { $src }
            { xs:string($started) }
            { $status }

};