[refactor] Add issue to pending annotation

xquery version "3.1";

(:~
 : these tests were created because of
 : https://github.com/eXist-db/exist/issues/1379
~:)

module namespace ct="http://exist-db.org/xquery/test/question-marks-in-contains-function";

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

declare variable $ct:test :=
    <root>
        <persName xmlns="http://www.tei-c.org/ns/1.0">
            <surname>Hering</surname>, <forename>S(amuel?)</forename>
        </persName>
        <persName xmlns="http://www.tei-c.org/ns/1.0">
            <surname>Hering</surname>, <forename>Samuel</forename>
        </persName>
    </root>;

declare variable $ct:xconf :=
    <collection xmlns="http://exist-db.org/collection-config/1.0">
        <index xmlns:tei="http://www.tei-c.org/ns/1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
            <range>
                <create qname="tei:surname" type="xs:string"/>
                <create qname="tei:forename" type="xs:string"/>
                <create qname="tei:persName" type="xs:string"/>
            </range>
        </index>
    </collection>;

declare %test:setUp function ct:setup() {
    xmldb:create-collection("/db/system/config/db", "test"),
    xmldb:store("/db/system/config/db/test", "collection.xconf", $ct:xconf),
    xmldb:create-collection("/db", "test"),
    xmldb:store("/db/test", "test.xml", $ct:test)
};

declare %test:tearDown function ct:teardown() {
    xmldb:remove("/db/test"),
    xmldb:remove("/db/system/config/db/test")
};

declare %test:assertEquals(1) %test:pending("https://github.com/eXist-db/exist/issues/1379") function ct:element-contains-question-mark() {
    let $hits := doc("/db/test/test.xml")//tei:forename[fn:contains(., "?")]
    return
        count($hits)
};

declare %test:assertEquals(0) %test:pending("https://github.com/eXist-db/exist/issues/1379") function ct:element-contains-escaped-question-mark() {
    let $hits := doc("/db/test/test.xml")//tei:forename[fn:contains(., "\?")]
    return
        count($hits)
};

declare %test:assertEquals(1) %test:pending("https://github.com/eXist-db/exist/issues/1379") function ct:parent-element-contains-question-mark() {
    let $hits := doc("/db/test/test.xml")//tei:persName[fn:contains(., "?")]
    return
        count($hits)
};

declare %test:assertEquals(0) function ct:parent-element-contains-escaped-question-mark() {
    let $hits := doc("/db/test/test.xml")//tei:persName[fn:contains(., "\?")]
    return
        count($hits)
};

xquery version "3.1";

(:~
 : these tests were created because of
 : https://github.com/eXist-db/exist/issues/1379
~:)

module namespace ct="http://exist-db.org/xquery/test/question-marks-in-contains-function";

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

declare variable $ct:test :=
    <root>
        <persName xmlns="http://www.tei-c.org/ns/1.0">
            <surname>Hering</surname>, <forename>S(amuel?)</forename>
        </persName>
        <persName xmlns="http://www.tei-c.org/ns/1.0">
            <surname>Hering</surname>, <forename>Samuel</forename>
        </persName>
    </root>;

declare variable $ct:xconf :=
    <collection xmlns="http://exist-db.org/collection-config/1.0">
        <index xmlns:tei="http://www.tei-c.org/ns/1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
            <range>
                <create qname="tei:surname" type="xs:string"/>
                <create qname="tei:forename" type="xs:string"/>
                <create qname="tei:persName" type="xs:string"/>
            </range>
        </index>
    </collection>;

declare %test:setUp function ct:setup() {
    xmldb:create-collection("/db/system/config/db", "test"),
    xmldb:store("/db/system/config/db/test", "collection.xconf", $ct:xconf),
    xmldb:create-collection("/db", "test"),
    xmldb:store("/db/test", "test.xml", $ct:test)
};

declare %test:tearDown function ct:teardown() {
    xmldb:remove("/db/test"),
    xmldb:remove("/db/system/config/db/test")
};

declare %test:assertEquals(1) %test:pending function ct:element-contains-question-mark() {
    let $hits := doc("/db/test/test.xml")//tei:forename[fn:contains(., "?")]
    return
        count($hits)
};

declare %test:assertEquals(0) %test:pending function ct:element-contains-escaped-question-mark() {
    let $hits := doc("/db/test/test.xml")//tei:forename[fn:contains(., "\?")]
    return
        count($hits)
};

declare %test:assertEquals(1) %test:pending function ct:parent-element-contains-question-mark() {
    let $hits := doc("/db/test/test.xml")//tei:persName[fn:contains(., "?")]
    return
        count($hits)
};

declare %test:assertEquals(0) function ct:parent-element-contains-escaped-question-mark() {
    let $hits := doc("/db/test/test.xml")//tei:persName[fn:contains(., "\?")]
    return
        count($hits)
};


[bugfix] package repository not working with changed web prefix.

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

xquery version "1.0";

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

declare namespace package="http://expath.org/ns/pkg";
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 variable $repomanager:coll := "/db/system/repo";
declare variable $repomanager:repo-uri :=
    if (request:get-parameter("repository-url", ())) then
        request:get-parameter("repository-url", ())
    else
        "http://demo.exist-db.org/exist/apps/public-repo/retrieve.html"
        (: "http://192.168.2.104:8080/exist/apps/public-repo/retrieve.html" :)
;

declare function local:entry-data($path as xs:anyURI, $type as xs:string, $data as item()?, $param as item()*) as item()?
{
    if (starts-with($path, "icon")) then
        <icon>{$path}</icon>
    else
    	<entry>
    		<path>{$path}</path>
    		<type>{$type}</type>
    		<data>{$data}</data>
    	</entry>
};

declare function local:entry-filter($path as xs:anyURI, $type as xs:string, $param as item()*) as xs:boolean
{
	starts-with($path, "icon") or $path = ("repo.xml", "expath-pkg.xml")
};

declare function repomanager:publicrepo() as element()
{
    let $package-url := request:get-parameter("package-url", ())
    return

Actions:

                {
                if (ends-with($package-url,'.xar')) then (

Downloaded package: {$package-url}
,

                    let $http-response := httpclient:get(xs:anyURI($package-url), false(), ())
                    let $name := tokenize($package-url, "/")[last()]
                    let $package-mimetype := "application/xar"
                    let $package-data := xs:base64Binary($http-response/httpclient:body/text())
                    let $stored := xmldb:store($repomanager:coll, $name, $package-data, $package-mimetype)
                    let $meta :=
                        compression:unzip(
                            util:binary-doc($stored), util:function(xs:QName("local:entry-filter"), 3),
                            (),  util:function(xs:QName("local:entry-data"), 4), ()
                        )
                    let $package := $meta//package:package/string(@name)
                    let $type := $meta//repo:meta//repo:type/string()
                    let $install :=
                        repo:install(concat('http://localhost:',request:get-server-port(), request:get-context-path(), '/rest',$stored))
                    let $deploy :=
                        if ($type eq "application") then
                            repo:deploy($package)
                        else
                            ()
                    return

Package installed.

                )
                else

Error uploading - Must be a valid Package archive (.xar file extension)

                }

            Important: installed XQuery library mappings will not become visible until eXist is restarted.

};

declare function repomanager:upload() as element()
{

Actions:

        {
            let $name := request:get-parameter("name", ())
            let $repocol :=  if (collection($repomanager:coll)) then () else xmldb:create-collection('/db/system','repo')
            let $docName := if($name) then $name else request:get-uploaded-file-name("upload")
            let $file := request:get-uploaded-file-data("upload")
            return
                if ($docName) then
                    let $stored := xdb:store($repomanager:coll, xdb:encode-uri($docName), $file)
                    let $meta :=
                        compression:unzip(
                            util:binary-doc($stored), util:function(xs:QName("local:entry-filter"), 3),
                            (),  util:function(xs:QName("local:entry-data"), 4), ()
                        )
                    let $package := $meta//package:package/string(@name)
                    let $type := $meta//repo:meta//repo:type/string()
                    let $install :=
                        repo:install(concat('http://localhost:',request:get-server-port(),request:get-context-path(), '/rest',$stored))
                    let $deployed :=
                        if ($type eq "application") then
                            repo:deploy($package)
                        else
                            ()
                    return

Package uploaded and installed: {$name}

                else

Error uploading - Must be a valid Package archive (.xar file extension)

        }

};

declare function repomanager:activate() as element()
{
    let $name := request:get-parameter("name", ())
    let $package := request:get-parameter("package", ())
    let $type := request:get-parameter("type", ())
    let $hostname := request:get-hostname()            (:  pkg-repo.jar needs http or file scheme :)
    let $port := request:get-server-port()
     return

Actions:

Installed package: {$name}

                {
                    repo:install(concat('http://localhost:',$port,request:get-context-path(), '/rest',$repomanager:coll,'/',$name,'.xar')),
                    if ($type eq "application") then
                        repo:deploy($package)
                    else
                        ()
                }

};

declare function repomanager:deactivate() as element()
{
    let $name := request:get-parameter("name", ())
    let $package := request:get-parameter("package", ())
    let $type := request:get-parameter("type", ())
    let $undeploy :=
        if ($type eq "application") then
            repo:undeploy($package)
        else
            ()
    let $remove := repo:remove($package)
    (: let $delete := xmldb:remove($repomanager:coll, $name) :)
    return

Actions:

Uninstalled package: {$name}

};

declare function repomanager:process-action() as element()*
{
    let $action := request:get-parameter("action", ()) return
        util:catch("java.lang.Exception",
            if($action eq "activate") then
            (
                repomanager:activate()
            )
            else if($action eq "deactivate") then
            (
                repomanager:deactivate()
            )
            else if($action eq "Upload Package") then
            (
                repomanager:upload()
            )
            else if($action eq "download") then
            (
                repomanager:publicrepo()
            )else(),

                An error occurred while processing the action:

                {$util:exception-message}

        )
};

declare function repomanager:all-packages() {
    for $repo in repo:list()
    return
        <package url="{$repo}">
        {
            for $r in ("repo.xml", "expath-pkg.xml")
            let $meta := repo:get-resource($repo, $r)
            let $data := if (exists($meta)) then util:binary-to-string($meta) else ()
            return
                if (exists($data)) then
                    util:parse($data)
                else
                    ()
        }
        {
            let $icon := repo:get-resource($repo, "icon.png")
            return
                if (exists($icon)) then
                    <icon>icon.png</icon>
                else
                    ()
        }
        </package>
};

declare function repomanager:view-installed() {
    let $packages := repomanager:all-packages()
    return

        {
            for $package in $packages
            let $iconURL :=
                if ($package/icon) then
                    concat("get-icon.xql?package=", $package/@url)
                else
                    "images/package.png"
            let $pkg-name := $package/package:package/string(@name)
            let $pkg-abbrev := $package/package:package/string(@abbrev)
            let $type := $package//repo:type/string()
            let $version := $package/package:package/@version/string()
            let $app-url :=
				if ($package//repo:target) then
                	concat(
                    	request:get-context-path(), "/apps",
                    	substring-after($package//repo:target, "/db"), "/"
                	)
				else
					()
            return

{$package//package:title/string()} ({$version})

                                Title:
                                { $package//package:title/text() }

							{
								if ($app-url) then

										Local URL:

											{$app-url}

								else
									()
							}

                                Author(s):

                                    {
                                        for $author in $package//repo:author
                                        return

{$author/text()}

                                    }

                                Version:
                                { $version }

                                Description:
                                { $package//repo:description/text() }

                                License:
                                { $package//repo:license/text() }

                                Website:
                                { $package//repo:website/text() }

                                    <form method="POST" action="admin.xql">
                                        <input type="hidden" name="panel" value="repo"/>
                                        <input type="hidden" name="name" value="{$pkg-abbrev}-{$version}.xar"/>
                                        <input type="hidden" name="package" value="{$pkg-name}"/>
                                        <input type="hidden" name="type" value="{$type}"/>
                                        <button type="submit" name="action" value="deactivate">

                                        </button>
                                    </form>

        }

};

declare function repomanager:show-public() {

        <input name="repository-url" size="60" value="{$repomanager:repo-uri}"/>
        <button name="retrieve-repo" id="retrieve-repo">Retrieve packages</button>

Retrieving packages ...

};

declare function repomanager:main() as element() {
    let $action := lower-case(request:get-parameter("action", "set repository"))
    let $repocol :=  if (collection($repomanager:coll)) then () else xmldb:create-collection('/db/system','repo')

    return

Package Repository

            { repomanager:process-action() }

Installed

Public Repo

Upload

                    { repomanager:view-installed() }

                    { repomanager:show-public() }

                    <form method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="panel" value="repo"/>

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

                        Note: You can upload example .xar packages located under webapp/repo/packages
                    </form>

};

xquery version "1.0";

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

declare namespace package="http://expath.org/ns/pkg";
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 variable $repomanager:coll := "/db/system/repo";
declare variable $repomanager:repo-uri :=
    if (request:get-parameter("repository-url", ())) then
        request:get-parameter("repository-url", ())
    else
        "http://demo.exist-db.org/exist/apps/public-repo/retrieve.html"
        (: "http://192.168.2.104:8080/exist/apps/public-repo/retrieve.html" :)
;

declare function local:entry-data($path as xs:anyURI, $type as xs:string, $data as item()?, $param as item()*) as item()?
{
    if (starts-with($path, "icon")) then
        <icon>{$path}</icon>
    else
    	<entry>
    		<path>{$path}</path>
    		<type>{$type}</type>
    		<data>{$data}</data>
    	</entry>
};

declare function local:entry-filter($path as xs:anyURI, $type as xs:string, $param as item()*) as xs:boolean
{
	starts-with($path, "icon") or $path = ("repo.xml", "expath-pkg.xml")
};

declare function repomanager:publicrepo() as element()
{
    let $package-url := request:get-parameter("package-url", ())
    return

Actions:

                {
                if (ends-with($package-url,'.xar')) then (

Downloaded package: {$package-url}
,

                    let $http-response := httpclient:get(xs:anyURI($package-url), false(), ())
                    let $name := tokenize($package-url, "/")[last()]
                    let $package-mimetype := "application/xar"
                    let $package-data := xs:base64Binary($http-response/httpclient:body/text())
                    let $stored := xmldb:store($repomanager:coll, $name, $package-data, $package-mimetype)
                    let $meta :=
                        compression:unzip(
                            util:binary-doc($stored), util:function(xs:QName("local:entry-filter"), 3),
                            (),  util:function(xs:QName("local:entry-data"), 4), ()
                        )
                    let $package := $meta//package:package/string(@name)
                    let $type := $meta//repo:meta//repo:type/string()
                    let $install :=
                        repo:install(concat('http://localhost:',request:get-server-port(),'/exist/rest',$stored))
                    let $deploy :=
                        if ($type eq "application") then
                            repo:deploy($package)
                        else
                            ()
                    return

Package installed.

                )
                else

Error uploading - Must be a valid Package archive (.xar file extension)

                }

            Important: installed XQuery library mappings will not become visible until eXist is restarted.

};

declare function repomanager:upload() as element()
{

Actions:

        {
            let $name := request:get-parameter("name", ())
            let $repocol :=  if (collection($repomanager:coll)) then () else xmldb:create-collection('/db/system','repo')
            let $docName := if($name) then $name else request:get-uploaded-file-name("upload")
            let $file := request:get-uploaded-file-data("upload")
            return
                if ($docName) then
                    let $stored := xdb:store($repomanager:coll, xdb:encode-uri($docName), $file)
                    let $meta :=
                        compression:unzip(
                            util:binary-doc($stored), util:function(xs:QName("local:entry-filter"), 3),
                            (),  util:function(xs:QName("local:entry-data"), 4), ()
                        )
                    let $package := $meta//package:package/string(@name)
                    let $type := $meta//repo:meta//repo:type/string()
                    let $install :=
                        repo:install(concat('http://localhost:',request:get-server-port(),'/exist/rest',$stored))
                    let $deployed :=
                        if ($type eq "application") then
                            repo:deploy($package)
                        else
                            ()
                    return

Package uploaded and installed: {$name}

                else

Error uploading - Must be a valid Package archive (.xar file extension)

        }

};

declare function repomanager:activate() as element()
{
    let $name := request:get-parameter("name", ())
    let $package := request:get-parameter("package", ())
    let $type := request:get-parameter("type", ())
    let $hostname := request:get-hostname()            (:  pkg-repo.jar needs http or file scheme :)
    let $port := request:get-server-port()
     return

Actions:

Installed package: {$name}

                {
                    repo:install(concat('http://localhost:',$port,'/exist/rest',$repomanager:coll,'/',$name,'.xar')),
                    if ($type eq "application") then
                        repo:deploy($package)
                    else
                        ()
                }

};

declare function repomanager:deactivate() as element()
{
    let $name := request:get-parameter("name", ())
    let $package := request:get-parameter("package", ())
    let $type := request:get-parameter("type", ())
    let $undeploy :=
        if ($type eq "application") then
            repo:undeploy($package)
        else
            ()
    let $remove := repo:remove($package)
    (: let $delete := xmldb:remove($repomanager:coll, $name) :)
    return

Actions:

Uninstalled package: {$name}

};

declare function repomanager:process-action() as element()*
{
    let $action := request:get-parameter("action", ()) return
        util:catch("java.lang.Exception",
            if($action eq "activate") then
            (
                repomanager:activate()
            )
            else if($action eq "deactivate") then
            (
                repomanager:deactivate()
            )
            else if($action eq "Upload Package") then
            (
                repomanager:upload()
            )
            else if($action eq "download") then
            (
                repomanager:publicrepo()
            )else(),

                An error occurred while processing the action:

                {$util:exception-message}

        )
};

declare function repomanager:all-packages() {
    for $repo in repo:list()
    return
        <package url="{$repo}">
        {
            for $r in ("repo.xml", "expath-pkg.xml")
            let $meta := repo:get-resource($repo, $r)
            let $data := if (exists($meta)) then util:binary-to-string($meta) else ()
            return
                if (exists($data)) then
                    util:parse($data)
                else
                    ()
        }
        {
            let $icon := repo:get-resource($repo, "icon.png")
            return
                if (exists($icon)) then
                    <icon>icon.png</icon>
                else
                    ()
        }
        </package>
};

declare function repomanager:view-installed() {
    let $packages := repomanager:all-packages()
    return

        {
            for $package in $packages
            let $iconURL :=
                if ($package/icon) then
                    concat("get-icon.xql?package=", $package/@url)
                else
                    "images/package.png"
            let $pkg-name := $package/package:package/string(@name)
            let $pkg-abbrev := $package/package:package/string(@abbrev)
            let $type := $package//repo:type/string()
            let $version := $package/package:package/@version/string()
            let $app-url :=
				if ($package//repo:target) then
                	concat(
                    	request:get-context-path(), "/apps",
                    	substring-after($package//repo:target, "/db"), "/"
                	)
				else
					()
            return

{$package//package:title/string()} ({$version})

                                Title:
                                { $package//package:title/text() }

							{
								if ($app-url) then

										Local URL:

											{$app-url}

								else
									()
							}

                                Author(s):

                                    {
                                        for $author in $package//repo:author
                                        return

{$author/text()}

                                    }

                                Version:
                                { $version }

                                Description:
                                { $package//repo:description/text() }

                                License:
                                { $package//repo:license/text() }

                                Website:
                                { $package//repo:website/text() }

                                    <form method="POST" action="admin.xql">
                                        <input type="hidden" name="panel" value="repo"/>
                                        <input type="hidden" name="name" value="{$pkg-abbrev}-{$version}.xar"/>
                                        <input type="hidden" name="package" value="{$pkg-name}"/>
                                        <input type="hidden" name="type" value="{$type}"/>
                                        <button type="submit" name="action" value="deactivate">

                                        </button>
                                    </form>

        }

};

declare function repomanager:show-public() {

        <input name="repository-url" size="60" value="{$repomanager:repo-uri}"/>
        <button name="retrieve-repo" id="retrieve-repo">Retrieve packages</button>

Retrieving packages ...

};

declare function repomanager:main() as element() {
    let $action := lower-case(request:get-parameter("action", "set repository"))
    let $repocol :=  if (collection($repomanager:coll)) then () else xmldb:create-collection('/db/system','repo')

    return

Package Repository

            { repomanager:process-action() }

Installed

Public Repo

Upload

                    { repomanager:view-installed() }

                    { repomanager:show-public() }

                    <form method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="panel" value="repo"/>

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

                        Note: You can upload example .xar packages located under webapp/repo/packages
                    </form>

};


Don't output invalid .xsd files that will trip up later "make doc" runs.

(:
 : 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.
:)
import module namespace file = "http://expath.org/ns/file";

import module namespace xqdoc       = "http://zorba.io/modules/xqdoc";
import module namespace batch       = "http://www.zorba-xquery.com/modules/xqdoc/batch";
import module namespace fetch = "http://zorba.io/modules/fetch";
import module namespace xqdoc-html  = "http://www.zorba-xquery.com/xqdoc-html" at "xqdoc-html.xqy";

declare namespace xqd = "http://www.xqdoc.org/1.0";
declare namespace z   = "http://zorba.io/manifest";
declare namespace xs  = "http://www.w3.org/2001/XMLSchema";

declare variable $zorbaManifestPath   as xs:string external;
declare variable $xhtmlRequisitesPath as xs:string external;
declare variable $xqdocBuildPath      as xs:string external;
declare variable $zorbaVersion        as xs:string external;

declare variable $slash := file:directory-separator();
declare variable $serXML:= <output:serialization-parameters xmlns:output="http://www.w3.org/2010/xslt-xquery-serialization">
                             <output:method   value="xml" />
                             <output:encoding value="UTF-8"/>
                           </output:serialization-parameters>;

declare %private function local:write-Doxygen(
  $content,
  $name as xs:string,
  $uri as xs:string?,
  $type as xs:string){
fn:serialize(<doxygen><compounddef id="{$name}-{$type}" kind="{$type}">
               <detaileddescription><para><h3>{concat("Content of ", $name, " " , $type)}</h3><programlisting type="{$type}">{fn:serialize($content,$serXML)}</programlisting></para></detaileddescription>
             </compounddef></doxygen>,$serXML)
};

(: Delete previous version of the documentation :)
if(file:exists($xqdocBuildPath))
then file:delete($xqdocBuildPath);
else ();

(: Copy Schemas :)
file:create-directory($xqdocBuildPath || $slash ||  "schemas");
file:create-directory($xqdocBuildPath || $slash || "xml");
let $base := $xhtmlRequisitesPath || $slash || ".." || $slash || ".." || $slash || ".." || $slash
let $dest := $xqdocBuildPath || $slash || "xml"
for $schema in file:list($base, true(), "*.xsd")
where not(ends-with($schema, ".ent.xsd"))
  and not(ends-with($schema, ".dtd.xsd"))
  and not(contains($schema, "URI_PATH"))
  and not(contains($schema, "QueryResults"))
let $schema-doc := doc($base || $slash || trace($schema, "schema"))
let $target-uri := $schema-doc/xs:schema/@targetNamespace/string()
let $name := replace(replace($target-uri, "http://", ""), "/", "_")
return {
  file:write-text($dest || $slash || replace(replace($target-uri, "http://", ""), "/", "_") || "-schema.xml",
                  local:write-Doxygen($schema-doc, $name, $target-uri, "schema"))
};

file:create-directory($xqdocBuildPath || $slash ||  "examples");
variable $manifest := parse-xml(file:read-text($zorbaManifestPath));
for $module in $manifest/z:manifest/z:module
let $uri := $module/z:uri/text()
let $xqdoc := xqdoc:xqdoc($uri)
let $module-name := tokenize($uri,"/")[last()]
return {
  (: Copy Examples :)
  for $example in $xqdoc//xqd:custom[@tag="example"]/text()
  let $source := $module/z:projectRoot/text() || $slash || $example
  let $test-name := trace(tokenize($source,"/")[last()], "example-name")
  let $destination := $xqdocBuildPath || $slash ||  "examples" || $slash || concat($module-name, "_", $test-name)
  let $dest := $xqdocBuildPath || $slash ||  "xml" || $slash || concat($module-name, "_", substring-before($test-name,".xq")) || "-example.xml"
  return {
    file:copy($source, $destination);
    file:write-text($dest,
                   local:write-Doxygen(file:read-text($source),$test-name, $uri, "example"));
  }
}

(: XQDoc Batch :)
let $static-folders := ("js", "css", "images")
let $static-folders := for $static in $static-folders return $xhtmlRequisitesPath || $slash || $static
let $template := parse-xml(file:read-text($xhtmlRequisitesPath || $slash || "template.xml"))/*
let $output-folder := $xqdocBuildPath
let $modules := xqdoc-html:modules($manifest)
return batch:build-xqdoc($output-folder, $static-folders, $template, $modules);

(: Copy modules :)
for $module in $manifest/z:manifest/z:module
let $uri := $module/z:uri/text()
let $module := fetch:content($uri, "MODULE")
return
  file:write-text($xqdocBuildPath || $slash || "xml" || $slash || replace(substring-after($uri, "http://"),"/","_") || "-module.xml",
                  local:write-Doxygen($module, tokenize($uri,"/")[last()], $uri, "module"));

trace("","XQDoc generated successfully!");

(:
 : 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.
:)
import module namespace file = "http://expath.org/ns/file";

import module namespace xqdoc       = "http://zorba.io/modules/xqdoc";
import module namespace batch       = "http://www.zorba-xquery.com/modules/xqdoc/batch";
import module namespace fetch = "http://zorba.io/modules/fetch";
import module namespace xqdoc-html  = "http://www.zorba-xquery.com/xqdoc-html" at "xqdoc-html.xqy";

declare namespace xqd = "http://www.xqdoc.org/1.0";
declare namespace z   = "http://zorba.io/manifest";
declare namespace xs  = "http://www.w3.org/2001/XMLSchema";

declare variable $zorbaManifestPath   as xs:string external;
declare variable $xhtmlRequisitesPath as xs:string external;
declare variable $xqdocBuildPath      as xs:string external;
declare variable $zorbaVersion        as xs:string external;

declare variable $slash := file:directory-separator();
declare variable $serXML:= <output:serialization-parameters xmlns:output="http://www.w3.org/2010/xslt-xquery-serialization">
                             <output:method   value="xml" />
                             <output:encoding value="UTF-8"/>
                           </output:serialization-parameters>;

declare %private function local:write-Doxygen(
  $content,
  $name as xs:string,
  $uri as xs:string?,
  $type as xs:string){
fn:serialize(<doxygen><compounddef id="{$name}-{$type}" kind="{$type}">
               <detaileddescription><para><h3>{concat("Content of ", $name, " " , $type)}</h3><programlisting type="{$type}">{fn:serialize($content,$serXML)}</programlisting></para></detaileddescription>
             </compounddef></doxygen>,$serXML)
};

(: Delete previous version of the documentation :)
if(file:exists($xqdocBuildPath))
then file:delete($xqdocBuildPath);
else ();

(: Copy Schemas :)
file:create-directory($xqdocBuildPath || $slash ||  "schemas");
file:create-directory($xqdocBuildPath || $slash || "xml");
let $base := $xhtmlRequisitesPath || $slash || ".." || $slash || ".." || $slash || ".." || $slash
let $dest := $xqdocBuildPath || $slash || "xml"
for $schema in file:list($base, true(), "*.xsd")
where not(ends-with($schema, ".ent.xsd"))
  and not(ends-with($schema, ".dtd.xsd"))
  and not(contains($schema, "URI_PATH"))
  and not(contains($schema, "rbkt"))
let $schema-doc := doc($base || $slash || trace($schema, "schema"))
let $target-uri := $schema-doc/xs:schema/@targetNamespace/string()
let $name := replace(replace($target-uri, "http://", ""), "/", "_")
return {
  (file:write-text($xqdocBuildPath || $slash || "schemas" || $slash || $name || ".xsd", $schema-doc),
  file:write-text($dest || $slash || replace(replace($target-uri, "http://", ""), "/", "_") || "-schema.xml",
                  local:write-Doxygen($schema-doc, $name, $target-uri, "schema"))
  )
};

file:create-directory($xqdocBuildPath || $slash ||  "examples");
variable $manifest := parse-xml(file:read-text($zorbaManifestPath));
for $module in $manifest/z:manifest/z:module
let $uri := $module/z:uri/text()
let $xqdoc := xqdoc:xqdoc($uri)
let $module-name := tokenize($uri,"/")[last()]
return {
  (: Copy Examples :)
  for $example in $xqdoc//xqd:custom[@tag="example"]/text()
  let $source := $module/z:projectRoot/text() || $slash || $example
  let $test-name := trace(tokenize($source,"/")[last()], "example-name")
  let $destination := $xqdocBuildPath || $slash ||  "examples" || $slash || concat($module-name, "_", $test-name)
  let $dest := $xqdocBuildPath || $slash ||  "xml" || $slash || concat($module-name, "_", substring-before($test-name,".xq")) || "-example.xml"
  return {
    file:copy($source, $destination);
    file:write-text($dest,
                   local:write-Doxygen(file:read-text($source),$test-name, $uri, "example"));
  }
}

(: XQDoc Batch :)
let $static-folders := ("js", "css", "images")
let $static-folders := for $static in $static-folders return $xhtmlRequisitesPath || $slash || $static
let $template := parse-xml(file:read-text($xhtmlRequisitesPath || $slash || "template.xml"))/*
let $output-folder := $xqdocBuildPath
let $modules := xqdoc-html:modules($manifest)
return batch:build-xqdoc($output-folder, $static-folders, $template, $modules);

(: Copy modules :)
for $module in $manifest/z:manifest/z:module
let $uri := $module/z:uri/text()
let $module := fetch:content($uri, "MODULE")
return
  file:write-text($xqdocBuildPath || $slash || "xml" || $slash || replace(substring-after($uri, "http://"),"/","_") || "-module.xml",
                  local:write-Doxygen($module, tokenize($uri,"/")[last()], $uri, "module"));

trace("","XQDoc generated successfully!");


[MIN] DBA, Files: suppress directories

[MIN] DBA, Files: suppress directories

(:~
 : Files page.
 :
 : @author Christian Grün, BaseX GmbH, 2014-15
 :)
module namespace _ = 'dba/files';

import module namespace Sessions = 'http://basex.org/modules/sessions';
import module namespace Session = 'http://basex.org/modules/session';
import module namespace cons = 'dba/cons' at '../modules/cons.xqm';
import module namespace html = 'dba/html' at '../modules/html.xqm';
import module namespace tmpl = 'dba/tmpl' at '../modules/tmpl.xqm';

(:~ Top category :)
declare variable $_:CAT := 'files';

(:~
 : Files page.
 : @param  $sort   table sort key
 : @param  $error  error message
 : @param  $info   info message
 : @return page
 :)
declare
  %rest:GET
  %rest:path("/dba/files")
  %rest:query-param("sort", "{$sort}", "")
  %rest:query-param("error", "{$error}")
  %rest:query-param("info",  "{$info}")
  %output:method("html")
function _:files(
  $sort   as xs:string,
  $error  as xs:string?,
  $info   as xs:string?
) as element() {
  cons:check(),

  (: request data in a single step :)
  let $files := file:children($cons:DBA-DIR)[file:is-file(.)]

  return tmpl:wrap(map { 'top': $_:CAT, 'info': $info, 'error': $error },

        <form action="{ $_:CAT }" method="post" class="update">

Files

        {
          let $entries :=
            for $file in $files
            let $date := file:last-modified($file)
            return <e name='{ file:name($file) }' date='{ $date }' size='{ file:size($file) }'/>
          let $headers := (
            <name>{ html:label($entries, ('File', 'Files')) }</name>,
            <date type='dateTime' order='desc'>Date</date>,
            <size type='bytes' order='desc'>Size</size>
          )
          let $buttons := html:button('delete-files', 'Delete', true())
          let $link := function($value) { 'file/' || $value }
          return html:table($entries, $headers, $buttons, map {}, $sort, $link)
        }
        </form>

Upload Files

        <form action="upload-files" method="post" enctype="multipart/form-data">
          <input type="file" name="files" multiple="multiple"/>
          <input type="submit" value='Send'/>
        </form>

          The files are located on the DBA system in the temporary directory
          { $cons:DBA-DIR }.

  )
};

(:~
 : Redirects to the specified action.
 : @param  $action  action to perform
 : @param  $names   names of files
 :)
declare
  %rest:POST
  %rest:path("/dba/files")
  %rest:query-param("action", "{$action}")
  %rest:query-param("name",   "{$names}")
  %output:method("html")
function _:action(
  $action  as xs:string,
  $names   as xs:string*
) {
  web:redirect($action, map { 'name': $names, 'redirect': $_:CAT })
};

(:~
 : Downloads a file.
 : @param  $name  name of file
 : @return file
 :)
declare
  %rest:GET
  %rest:path("/dba/file/{$name}")
function _:files(
  $name  as xs:string
) as item()+ {
  web:response-header(),
  file:read-binary($cons:DBA-DIR || $name)
};

(:~
 : Files page.
 :
 : @author Christian Grün, BaseX GmbH, 2014-15
 :)
module namespace _ = 'dba/files';

import module namespace Sessions = 'http://basex.org/modules/sessions';
import module namespace Session = 'http://basex.org/modules/session';
import module namespace cons = 'dba/cons' at '../modules/cons.xqm';
import module namespace html = 'dba/html' at '../modules/html.xqm';
import module namespace tmpl = 'dba/tmpl' at '../modules/tmpl.xqm';

(:~ Top category :)
declare variable $_:CAT := 'files';

(:~
 : Files page.
 : @param  $sort   table sort key
 : @param  $error  error message
 : @param  $info   info message
 : @return page
 :)
declare
  %rest:GET
  %rest:path("/dba/files")
  %rest:query-param("sort", "{$sort}", "")
  %rest:query-param("error", "{$error}")
  %rest:query-param("info",  "{$info}")
  %output:method("html")
function _:files(
  $sort   as xs:string,
  $error  as xs:string?,
  $info   as xs:string?
) as element() {
  cons:check(),

  (: request data in a single step :)
  let $files := file:children($cons:DBA-DIR)

  return tmpl:wrap(map { 'top': $_:CAT, 'info': $info, 'error': $error },

        <form action="{ $_:CAT }" method="post" class="update">

Files

        {
          let $entries :=
            for $file in $files
            let $date := file:last-modified($file)
            return <e name='{ file:name($file) }' date='{ $date }' size='{ file:size($file) }'/>
          let $headers := (
            <name>{ html:label($entries, ('File', 'Files')) }</name>,
            <date type='dateTime' order='desc'>Date</date>,
            <size type='bytes' order='desc'>Size</size>
          )
          let $buttons := html:button('delete-files', 'Delete', true())
          let $link := function($value) { 'file/' || $value }
          return html:table($entries, $headers, $buttons, map {}, $sort, $link)
        }
        </form>

Upload Files

        <form action="upload-files" method="post" enctype="multipart/form-data">
          <input type="file" name="files" multiple="multiple"/>
          <input type="submit" value='Send'/>
        </form>

          The files are located on the DBA system in the temporary directory
          { $cons:DBA-DIR }.

  )
};

(:~
 : Redirects to the specified action.
 : @param  $action  action to perform
 : @param  $names   names of files
 :)
declare
  %rest:POST
  %rest:path("/dba/files")
  %rest:query-param("action", "{$action}")
  %rest:query-param("name",   "{$names}")
  %output:method("html")
function _:action(
  $action  as xs:string,
  $names   as xs:string*
) {
  web:redirect($action, map { 'name': $names, 'redirect': $_:CAT })
};

(:~
 : Downloads a file.
 : @param  $name  name of file
 : @return file
 :)
declare
  %rest:GET
  %rest:path("/dba/file/{$name}")
function _:files(
  $name  as xs:string
) as item()+ {
  web:response-header(),
  file:read-binary($cons:DBA-DIR || $name)
};


minor fix to path interpretation

minor fix to path interpretation

module namespace crday  = "http://aac.ac.at/content_repository/data-ay";

import module namespace repo-utils =  "http://aac.ac.at/content_repository/utils" at  "repo-utils.xqm";

import module namespace xdb="http://exist-db.org/xquery/xmldb";
(:import module namespace diag =  "http://www.loc.gov/zing/srw/diagnostic/" at  "modules/diagnostics/diagnostics.xqm";
import module namespace util="http://exist-db.org/xquery/util";
import module namespace kwic="http://exist-db.org/xquery/kwic";
:)
declare namespace sru = "http://www.loc.gov/zing/srw/";
declare namespace fcs = "http://clarin.eu/fcs/1.0";
declare namespace cmd = "http://www.clarin.eu/cmd/";
(:declare namespace tei = "http://www.tei-c.org/ns/1.0";:)

declare variable $crday:docTypeTerms := "Terms";

(:~ analyzes the xml-structure - sub-elements and text-nodes
in the context of given collection, starting from given xpath

@param $context nodeset to analyze
@param $path if starts-with '/' or = '' start directly at the $context, else eval on f 'descendants-or-self'-axis
calls elem-r for recursive processing

@returns xml-with paths and numbers
:)
declare function crday:ay-xml($context as item()*, $path as xs:string, $depth as xs:integer ) as element() {

  (:let $collection := collection($cr:dataPath),
  if ($collections[1] eq $cr:collectionRoot) then
  util:eval(fn:concat("$collection/descendant::IsPartOf[ft:query(., <query><term>", xdb:decode($coll), "</term></query>)]/ancestor-or-self::CMD/descendant-or-self::", $path))
  :)
   let $ns-uri := namespace-uri($context[1]/*),
       $qname := $context[1]/*/name(),
       $prefix := if (exists(prefix-from-QName($qname))) then prefix-from-QName($qname) else "",
       $dummy := if (exists($ns-uri)) then util:declare-namespace($prefix,$ns-uri) else ()

   let $full-path := if (starts-with($path,'/') or $path = '' ) then
                        fn:concat("$context", $path)
                       else     fn:concat("$context/descendant-or-self::", $path)

  let $path-nodes := util:eval($full-path )

  let $entries := crday:elem-r($path-nodes, $path, $ns-uri, $depth, $depth),
(:      $coll-names-value := if (fn:empty($collections)) then () else attribute colls {fn:string-join($collections, ",")},:)
        $dummy-undeclare-ns := util:declare-namespace("",xs:anyURI("")),
	  $result := element {$crday:docTypeTerms} {
(:      		  $coll-names-value,:)
      		  attribute depth {$depth},
      		  attribute created {fn:current-dateTime()},
      		  $entries
		}
    return $result
};

(:~ goes down the xml-structure recursively and creates a summary about it along the way

namespace aware (handles namespace: none, default, explicit)

:)
declare function crday:elem-r($path-nodes as node()*, $path as xs:string, $ns as xs:anyURI?, $max-depth as xs:integer, $depth as xs:integer) as element() {
      let $path-count := count($path-nodes),
	$child-elements := $path-nodes/child::element(),
	$child-ns-qnames := if (exists($child-elements)) then distinct-values($child-elements/concat(namespace-uri(), '|', name())) else (),
	$nodes-child-terminal := if (empty($child-elements)) then $path-nodes else () (: Maybe some selected elements $child-elements[not(element())] later on :),
	$text-nodes := $nodes-child-terminal/text(),
	$text-count := count($text-nodes),
	$text-count-distinct := count(distinct-values($text-nodes)),
	$dummy-undeclare-ns := util:declare-namespace("",xs:anyURI(""))
	return
(:	<Term path="{fn:concat("//", $path)}" name="{text:groups($path, "/([^/]+)$")[last()]}" count="{$path-count}" count_text="{$text-count}"  count_distinct_text="{$text-count-distinct}">{ :)
	<Term path="{fn:concat("", translate($path,'/','.'))}" name="{(text:groups($path, "/([^/]+)$")[last()],$path)[1] }" count="{$path-count}" count_text="{$text-count}"  count_distinct_text="{$text-count-distinct}">{
	   (attribute ns {$ns},
	  if ($depth > 0) then
	    for $ns-qname in $child-ns-qnames[. != '']
	       let $ns-uri := substring-before($ns-qname, '|'),
	           $qname := substring-after($ns-qname, '|'),
	           $prefix := if (exists(prefix-from-QName($qname))) then prefix-from-QName($qname) else "",
	           (: dynamically declare a namespace for the next step, if one is defined in current context :)
	           $dummy := if (exists($ns-uri)) then util:declare-namespace($prefix,$ns-uri) else ()
	           return
	           crday:elem-r(util:eval(concat("$path-nodes/", $qname)), concat($path, '/', $qname), $ns-uri, $max-depth, $depth - 1)
	  else 'maxdepth'
	)}</Term>
};

(:~ analyze xml-structure
  API function queryModel.
:)
(:declare function crday:ay-xml-wrap($init-xpath as xs:string, $collection as xs:string+, $max-depth as xs:integer) as item()? {

  let $name := repo-utils:gen-cache-id("model", ($collection, $cmd-index-path), xs:string($max-depth)),
    $doc :=
    if (repo-utils:is-in-cache($name)) then
      repo-utils:get-from-cache($name)
    else
      let $data := cr:elem($collection, $cmd-index-path, $max-depth)
        return repo-utils:store-in-cache($name, $data)

  return $doc
};
:)

module namespace crday  = "http://aac.ac.at/content_repository/data-ay";

import module namespace repo-utils =  "http://aac.ac.at/content_repository/utils" at  "repo-utils.xqm";

import module namespace xdb="http://exist-db.org/xquery/xmldb";
(:import module namespace diag =  "http://www.loc.gov/zing/srw/diagnostic/" at  "modules/diagnostics/diagnostics.xqm";
import module namespace util="http://exist-db.org/xquery/util";
import module namespace kwic="http://exist-db.org/xquery/kwic";
:)
declare namespace sru = "http://www.loc.gov/zing/srw/";
declare namespace fcs = "http://clarin.eu/fcs/1.0";
declare namespace cmd = "http://www.clarin.eu/cmd/";
(:declare namespace tei = "http://www.tei-c.org/ns/1.0";:)

declare variable $crday:docTypeTerms := "Terms";

(:~ analyzes the xml-structure - sub-elements and text-nodes
in the context of given collection, starting from given xpath

@param $context nodeset to analyze
calls elem-r for recursive processing

@returns xml-with paths and numbers
:)
declare function crday:ay-xml($context as item()*, $path as xs:string, $depth as xs:integer ) as element() {

  (:let $collection := collection($cr:dataPath),
  if ($collections[1] eq $cr:collectionRoot) then
  util:eval(fn:concat("$collection/descendant::IsPartOf[ft:query(., <query><term>", xdb:decode($coll), "</term></query>)]/ancestor-or-self::CMD/descendant-or-self::", $path))
  :)
   let $ns-uri := namespace-uri($context[1]/*),
       $qname := $context[1]/*/name(),
       $prefix := if (exists(prefix-from-QName($qname))) then prefix-from-QName($qname) else "",
       $dummy := if (exists($ns-uri)) then util:declare-namespace($prefix,$ns-uri) else ()

  let $path-nodes := util:eval(fn:concat("$context/descendant-or-self::", $path))

  let $entries := crday:elem-r($path-nodes, $path, $ns-uri, $depth, $depth),
(:      $coll-names-value := if (fn:empty($collections)) then () else attribute colls {fn:string-join($collections, ",")},:)
        $dummy-undeclare-ns := util:declare-namespace("",xs:anyURI("")),
	  $result := element {$crday:docTypeTerms} {
(:      		  $coll-names-value,:)
      		  attribute depth {$depth},
      		  attribute created {fn:current-dateTime()},
      		  $entries
		}
    return $result
};

(:~ goes down the xml-structure recursively and creates a summary about it along the way

namespace aware (handles namespace: none, default, explicit)

:)
declare function crday:elem-r($path-nodes as node()*, $path as xs:string, $ns as xs:anyURI?, $max-depth as xs:integer, $depth as xs:integer) as element() {
      let $path-count := count($path-nodes),
	$child-elements := $path-nodes/child::element(),
	$child-ns-qnames := if (exists($child-elements)) then distinct-values($child-elements/concat(namespace-uri(), '|', name())) else (),
	$nodes-child-terminal := if (empty($child-elements)) then $path-nodes else () (: Maybe some selected elements $child-elements[not(element())] later on :),
	$text-nodes := $nodes-child-terminal/text(),
	$text-count := count($text-nodes),
	$text-count-distinct := count(distinct-values($text-nodes)),
	$dummy-undeclare-ns := util:declare-namespace("",xs:anyURI(""))
	return
(:	<Term path="{fn:concat("//", $path)}" name="{text:groups($path, "/([^/]+)$")[last()]}" count="{$path-count}" count_text="{$text-count}"  count_distinct_text="{$text-count-distinct}">{ :)
	<Term path="{fn:concat("//", $path)}" name="{(text:groups($path, "/([^/]+)$")[last()],$path)[1] }" count="{$path-count}" count_text="{$text-count}"  count_distinct_text="{$text-count-distinct}">{
	   (attribute ns {$ns},
	  if ($depth > 0) then
	    for $ns-qname in $child-ns-qnames[. != '']
	       let $ns-uri := substring-before($ns-qname, '|'),
	           $qname := substring-after($ns-qname, '|'),
	           $prefix := if (exists(prefix-from-QName($qname))) then prefix-from-QName($qname) else "",
	           (: dynamically declare a namespace for the next step, if one is defined in current context :)
	           $dummy := if (exists($ns-uri)) then util:declare-namespace($prefix,$ns-uri) else ()
	           return
	           crday:elem-r(util:eval(concat("$path-nodes/", $qname)), concat($path, '/', $qname), $ns-uri, $max-depth, $depth - 1)
	  else 'maxdepth'
	)}</Term>
};

(:~ analyze xml-structure
  API function queryModel.
:)
(:declare function crday:ay-xml-wrap($init-xpath as xs:string, $collection as xs:string+, $max-depth as xs:integer) as item()? {

  let $name := repo-utils:gen-cache-id("model", ($collection, $cmd-index-path), xs:string($max-depth)),
    $doc :=
    if (repo-utils:is-in-cache($name)) then
      repo-utils:get-from-cache($name)
    else
      let $data := cr:elem($collection, $cmd-index-path, $max-depth)
        return repo-utils:store-in-cache($name, $data)

  return $doc
};
:)


improved documentation for fetch

improved documentation for fetch

xquery version "3.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.
:)

(:~
 : This module provides functions to fetch the contents or the type
 : of the content for a resource identified by a URI.
 : For example, it fetches content for file or http resources if Zorba
 : allows file or http access, respectively.
 :
 :
The errors raised by functions of this module have the namespace
 : <tt>http://www.zorba-xquery.com/errors</tt> (associated with prefix zerr).

 :
 : @see http://www.zorba-xquery.com/errors
 :
 : @author Matthias Brantner
 :
 : @project external
 :)
module namespace fetch = "http://www.zorba-xquery.com/modules/fetch";

declare namespace ann = "http://www.zorba-xquery.com/annotations";

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

(:~
 :
Tries to fetch the resource referred to by the given URI.

 :
 :
In order to retrieve the content, the functions uses the
 : URI resolution and URL resolver process as documented at
 :
 : URI Resolvers. Therefore, it queries all URI mappers
 : and resolvers with kind <tt>EntityData::SOME_CONTENT</tt>.

 :
 :
The function is annotated with the <tt>ann:streamable</tt>
 : annotation, that is it returns a streamable string. A streamable
 : string can only be consumed once. Please see section "Streamable Strings"
 : in the
 : documentation of Zorba's annotations.
 :

 :
 : @param $uri the resource to fetch.
 : @return the resource referred to by the given URI as streamble string.
 :
 : @error zerr:ZXQP0025 if the URI could not be resolved
 :   or did not resolve to a <tt>StreamResource</tt>.
 :
 : @see URI Resolvers.
 : @see Annotations.
 :)
declare %ann:streamable function fetch:content($uri as xs:string) as xs:string external;

xquery version "3.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.
:)

(:~
 : This module provides functions to fetch the contents or the type
 : of the content for a resource identified by a URI.
 : For example, it fetches content for file or http resources if Zorba
 : allows file or http access, respectively.
 :
 : @author Matthias Brantner
 : @project external
 :)
module namespace fetch = "http://www.zorba-xquery.com/modules/fetch";
declare namespace ann = "http://www.zorba-xquery.com/annotations";
declare namespace ver = "http://www.zorba-xquery.com/options/versioning";
declare option ver:module-version "2.0";

(:~
 : fetch:ErrRetrievingResource
 :)
declare variable $fetch:ErrRetrievingResource as xs:QName :=
  fn:QName("http://www.zorba-xquery.com/modules/fetch",
           "fetch:ErrRetrievingResource");

(:~
 : fetch:ResourceDoesNotExist
 :)
declare variable $fetch:ResourceDoesNotExist as xs:QName :=
  fn:QName("http://www.zorba-xquery.com/modules/fetch",
           "fetch:ResourceDoesNotExist");

(:~
 : Tries to fetch the resource referred to by the given URI.
 :
 : @param $uri the resource to fetch to
 : @return the resource referred to by the given URI
 : @error fetch:ErrRetrievingResource if an error occurred
 :        retrieving the resource.
 : @error fetch:ResourceDoesNotExist if no resource could be found at
 :        the given location.
 :)
declare %ann:streamable function fetch:content($uri as xs:string) as xs:string external;


Exit from org hierarchy when village is selected

import module namespace functx = "http://www.functx.com";
declare namespace csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

let $t_top_orgid  :=  $careServicesRequest/query[@name = 'orgid']/text()
let $top_org :=  (/csd:CSD/csd:organizationDirectory/csd:organization[@entityID = $t_top_orgid])[1]

let $selected_text := $careServicesRequest/query[@name = 'input']/text()
(:
let $selections := $careServicesRequest/values/item[./pair[@name = 'label' and ./text() = 'facilityselection']]
let $selected_text :=
  if (count($selections) > 0)
  then
    let $max_time := max(for $time in $selections/pair[@name='time'] return xs:dateTime($time))
    return $selections[./pair[@name = 'time'] = $max_time]/pair[@name='text']/text()
   else ()
:)

let $selected_index := if ($selected_text castable as xs:integer) then xs:integer($selected_text) else -1

let $selected :=
  if ($selected_index = 0)
  then
    /csd:CSD/csd:organizationDirectory/csd:organization[
      @entityID = /csd:CSD/csd:organizationDirectory/csd:organization[@entityID = $top_org/@entityID]/csd:parent/@entityID
    ]
  else if ($selected_index > 0)
  then
    let $select_orgs :=
      if (exists($top_org))
      then /csd:CSD/csd:organizationDirectory/csd:organization[./csd:parent/@entityID = $top_org/@entityID]
      else /csd:CSD/csd:organizationDirectory/csd:organization[count(./csd:parent[@entityID]) = 0]

    let $select_facs :=
      if (exists($top_org))
      then /csd:CSD/csd:facilityDirectory/csd:facility[./csd:organizations/csd:organization[@entityID = $top_org/@entityID]]
      else ()
    return ($select_orgs,$select_facs)[ $selected_index]
  else ()

let $orgs :=
  if (exists($selected) and  local-name($selected ) = 'organization')
  then /csd:CSD/csd:organizationDirectory/csd:organization[./csd:parent/@entityID = $selected/@entityID]
  else /csd:CSD/csd:organizationDirectory/csd:organization[count(./csd:parent[@entityID]) = 0]

let $facs :=
  if (exists($selected) and  local-name($selected ) = 'organization')
  then /csd:CSD/csd:facilityDirectory/csd:facility[./csd:organizations/csd:organization[@entityID = $selected/@entityID]]
  else ()

let $output :=
  if ( local-name($selected ) = 'facility')
  then
    <json type='object'>
      <menutext>You already selected a facility.  You shouldn't see this message</menutext>
      <facility>{string($selected/@entityID)}</facility>
      <facilityname>{$selected/csd:primaryName/text()}</facilityname>
    </json>
  else  if ( local-name($selected ) = 'organization'  or not(exists($selected)))
  then
    <json type='object'>
      <menutext >
 	{ if (exists($selected)) then concat("In ", $selected/csd:primaryName/text(), ". ")  else () }
	{
	  let $parent := (/csd:CSD/csd:organizationDirectory/csd:organization[@entityID = $selected/csd:parent/@entityID])[1]/csd:primaryName/text()
	  return
	    if ($parent)
	    then concat("O) Up to ", $parent, " ")
	    else ()
        }
	{ for $ent at $pos in ($orgs,$facs)  return concat( $pos, ") ", $ent/csd:primaryName/text())    }
      </menutext>
      <orgid>{if (exists($selected)) then string($selected/@entityID) else ()}</orgid>
      <orgcode>{if (exists($selected)) then string($selected/csd:otherID/@code) else ()}</orgcode>
      <village>{if ($selected/csd:codedType/@code=6) then string($selected/@entityID) else ()}</village>
      <villagename>{if ($selected/csd:codedType/@code=6) then string($selected/csd:primaryName/text()) else ()}</villagename>
    </json>
   else <json type='object'/>

(:return $output :)
return json:serialize($output,map{'format':'direct'})

import module namespace functx = "http://www.functx.com";
declare namespace csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

let $t_top_orgid  :=  $careServicesRequest/query[@name = 'orgid']/text()
let $top_org :=  (/csd:CSD/csd:organizationDirectory/csd:organization[@entityID = $t_top_orgid])[1]

let $selected_text := $careServicesRequest/query[@name = 'input']/text()
(:
let $selections := $careServicesRequest/values/item[./pair[@name = 'label' and ./text() = 'facilityselection']]
let $selected_text :=
  if (count($selections) > 0)
  then
    let $max_time := max(for $time in $selections/pair[@name='time'] return xs:dateTime($time))
    return $selections[./pair[@name = 'time'] = $max_time]/pair[@name='text']/text()
   else ()
:)

let $selected_index := if ($selected_text castable as xs:integer) then xs:integer($selected_text) else -1

let $selected :=
  if ($selected_index = 0)
  then
    /csd:CSD/csd:organizationDirectory/csd:organization[
      @entityID = /csd:CSD/csd:organizationDirectory/csd:organization[@entityID = $top_org/@entityID]/csd:parent/@entityID
    ]
  else if ($selected_index > 0)
  then
    let $select_orgs :=
      if (exists($top_org))
      then /csd:CSD/csd:organizationDirectory/csd:organization[./csd:parent/@entityID = $top_org/@entityID]
      else /csd:CSD/csd:organizationDirectory/csd:organization[count(./csd:parent[@entityID]) = 0]

    let $select_facs :=
      if (exists($top_org))
      then /csd:CSD/csd:facilityDirectory/csd:facility[./csd:organizations/csd:organization[@entityID = $top_org/@entityID]]
      else ()
    return ($select_orgs,$select_facs)[ $selected_index]
  else ()

let $orgs :=
  if (exists($selected) and  local-name($selected ) = 'organization')
  then /csd:CSD/csd:organizationDirectory/csd:organization[./csd:parent/@entityID = $selected/@entityID]
  else /csd:CSD/csd:organizationDirectory/csd:organization[count(./csd:parent[@entityID]) = 0]

let $facs :=
  if (exists($selected) and  local-name($selected ) = 'organization')
  then /csd:CSD/csd:facilityDirectory/csd:facility[./csd:organizations/csd:organization[@entityID = $selected/@entityID]]
  else ()

let $output :=
  if ( local-name($selected ) = 'facility')
  then
    <json type='object'>
      <menutext>You already selected a facility.  You shouldn't see this message</menutext>
      <facility>{string($selected/@entityID)}</facility>
      <facilityname>{$selected/csd:primaryName/text()}</facilityname>
    </json>
  else  if ( local-name($selected ) = 'organization'  or not(exists($selected)))
  then
    <json type='object'>
      <menutext >
 	{ if (exists($selected)) then concat("In ", $selected/csd:primaryName/text(), ". ")  else () }
	{
	  let $parent := (/csd:CSD/csd:organizationDirectory/csd:organization[@entityID = $selected/csd:parent/@entityID])[1]/csd:primaryName/text()
	  return
	    if ($parent)
	    then concat("O) Up to ", $parent, " ")
	    else ()
        }
	{ for $ent at $pos in ($orgs,$facs)  return concat( $pos, ") ", $ent/csd:primaryName/text())    }
      </menutext>
      <orgid>{if (exists($selected)) then string($selected/@entityID) else ()}</orgid>
      <facility/>
      <facilityname/>
    </json>
   else <json type='object'/>

(:return $output :)
return json:serialize($output,map{'format':'direct'})


[ignore] test to make sure mime-type is now treated as text not binary

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

xquery version "1.0";

(:~ Basic XQuery equivalents of map, fold, and filter functions adapted from
 :  the standard library of the Scheme programming language.  Demonstrates the
 :  use of higher-order functions in eXist.
 :)

module namespace seq="http://exist-db.org/xquery/sequences";

import module namespace util="http://exist-db.org/xquery/util";

(:~ Applies $func to the items
 :  of two sequences and returns the results as
 :  a new sequence. Both input sequences should
 :  have the same length.
 :)
declare function seq:map($func as function, $seqA as item()*, $seqB as item()*)
as item()* {
	if(count($seqA) != count($seqB)) then
		error("The sequences passed to seq:map should have equal length.")
	else
    	for $a at $i in $seqA
    	let $b := $seqB[$i]
    	return
        	util:call($func, $a, $b)
};

(:~	Calls $func for all items in the sequence. For example, if
 :  the sequence is (1, 2, 3), $func will be called with arguments
 :  (1, 2) and (3, 3).
 :)
declare function seq:fold($func as function, $seq as item()*, $start as item()) {
	if(empty($seq)) then
		$start
	else
		seq:fold($func, remove($seq, 1), util:call($func, $start, $seq[1]))
};

(:~ Filters the passed sequence by calling $func for every
 :  item. All items for which $func returns true are copied
 :  to the output sequence, items for which it returns false
 :  are skipped.
 :)
declare function seq:filter($func as function, $seq as item()*)
as item()* {
	for $i in $seq
	return
		if(util:call($func, $i)) then
			$i
		else
			()
};


Fix for lp:967284.

Fix for lp:967284.

xquery version "3.0";

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

(:~
 : Function library provides functions for generating the XQDoc XML's for a project.
 :
 : @author Sorin Nasoi
 : @project xqdoc
 :)

module namespace pxqdoc  = "http://www.zorba-xquery.com/modules/project_xqdoc";

(:~ needed for generating the XML's :)
import module namespace xqd  = "http://www.zorba-xquery.com/modules/xqdoc";
(:~ needed for writing the XML's to disk:)
import module namespace file = "http://expath.org/ns/file";

import schema namespace xqdoc = "http://www.xqdoc.org/1.0";
import schema namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";

declare namespace an = "http://www.zorba-xquery.com/annotations";
declare namespace zm = "http://www.zorba-xquery.com/manifest";
import module namespace fetch = "http://www.zorba-xquery.com/modules/fetch";

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

import module namespace err  = "http://www.zorba-xquery.com/modules/xqdoc2xhtml/error";
declare namespace werr = "http://www.w3.org/2005/xqt-errors";
declare option ver:module-version "2.0";

(:~
 : The serialization parameters for XML serialization.
 :)
declare variable $pxqdoc:serParamXml :=
  <output:serialization-parameters>
    <output:method value="xml"/>
    <output:indent value="yes"/>
  </output:serialization-parameters>;

(:~
 : Delete the intermediary xml dir
 :
 : @param $xqdocPath where to generate the XQDoc XML documents.
 : @return empty sequence.
 :)
declare %an:sequential function pxqdoc:delete-XML-dir(
  $xqdocPath as xs:string)
{
  variable $xqdocXMLPath  := fn:concat( $xqdocPath,
                                        file:directory-separator(),
                                        "xml");
  (: clear the XML folder :)
  if(file:exists($xqdocXMLPath)) then
    file:delete($xqdocXMLPath);
  else ();
};

declare %private %an:nondeterministic function pxqdoc:load-manifest(
  $zorbaManifestPath as xs:string)
{
  try
  {
    fn:parse-xml(file:read-text($zorbaManifestPath))
  }
  catch *
  {
    fn:error($err:UE004,fn:concat("The file <",$zorbaManifestPath,"> does not have the correct structure."))
  }
};

(:~
 : This function generates the XQDoc XML for all the modules found in build/ZorbaManifest.xml
 :
 : @param $zorbaManifestPath location of ZorbaManifest.xml.
 : @param $xqdocPath where to generate the XQDoc XML documents.
 : @return empty sequence.
 :)
declare %an:sequential function pxqdoc:generate-xqdoc-XML(
  $zorbaManifestPath as xs:string,
  $xqdocPath as xs:string)
{
  (: Note: only the modules that are configured in the Zorba version you are using will be build :)
  variable $xqdocXMLPath := concat($xqdocPath, file:directory-separator(), "xml");

  (: create the XML folder if it does not exist already :)
  file:create-directory($xqdocXMLPath);

  if(not(file:is-file($zorbaManifestPath))) then
  {
    variable $message := fn:concat("The file <ZorbaManifest.xml> was not found: <", $zorbaManifestPath, ">. Suggestion: run 'cmake' in your build folder such that ZorbaManifest.xml is regenerated.");
    fn:error($err:UE004, $message);
  }
  else
  {
    variable $manifestXML := pxqdoc:load-manifest($zorbaManifestPath);
    variable $moduleManifests := $manifestXML/zm:manifest/zm:module;
    if(count($moduleManifests) eq xs:integer(0)) then ();
    else
    {
      for $module in $moduleManifests
      (: note the module version is not supported because of a bug in the fetch for the module URI ending with / :)
      (:let $moduleURI := if(ends-with(data($module/zm:uri),'/')) then data($module/zm:uri)
                       else if(exists($module/@version)) then concat(data($module/zm:uri),"#",data($module/@version))
                       else data($module/zm:uri):)
      (:let $moduleFetched := fetch:content(trace($moduleURI,"fetch module URI version.."), "MODULE"):)
      let $moduleURI := if(ends-with(data($module/zm:uri),".xq")) then substring-before(data($module/zm:uri),".xq") else data($module/zm:uri)
      let $moduleFetched := fetch:content($moduleURI, "MODULE")
      let $moduleFetched := fn:replace($moduleFetched, '&(nbsp|#160);' , codepoints-to-string(160))
      let $xqdoc := xqd:xqdoc-content($moduleFetched)
      let $xqdocRelFileName  := pxqdoc:get-filename($moduleURI)
      let $xqdocFileName := concat($xqdocXMLPath, file:directory-separator(), $xqdocRelFileName, ".xml")
      return
        file:write($xqdocFileName,
                   $xqdoc,
                   $pxqdoc:serParamXml)
    };
  }
};

(:~
 : Returns the string resulting from replacing the directory-separators (i.e. / ) with '_'
 :
 : @param $moduleURI the path to the module URI.
 : @return the string resulting from replacing the directory-separators (i.e. / ) with '_'.
 :
 :)
declare function pxqdoc:get-filename(
  $moduleURI as xs:string) as xs:string {
  let $lmodule := if(fn:ends-with($moduleURI,"/")) then fn:concat($moduleURI,"index") else $moduleURI
  return
    replace(
      replace($lmodule, "/", "_"),
      "http:__",
      ""
  )
};

xquery version "3.0";

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

(:~
 : Function library provides functions for generating the XQDoc XML's for a project.
 :
 : @author Sorin Nasoi
 : @project xqdoc
 :)

module namespace pxqdoc  = "http://www.zorba-xquery.com/modules/project_xqdoc";

(:~ needed for generating the XML's :)
import module namespace xqd  = "http://www.zorba-xquery.com/modules/xqdoc";
(:~ needed for writing the XML's to disk:)
import module namespace file = "http://expath.org/ns/file";

import schema namespace xqdoc = "http://www.xqdoc.org/1.0";
import schema namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";

declare namespace an = "http://www.zorba-xquery.com/annotations";
declare namespace zm = "http://www.zorba-xquery.com/manifest";
import module namespace fetch = "http://www.zorba-xquery.com/modules/fetch";

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

import module namespace err  = "http://www.zorba-xquery.com/modules/xqdoc2xhtml/error";
declare namespace werr = "http://www.w3.org/2005/xqt-errors";
declare option ver:module-version "2.0";

(:~
 : The serialization parameters for XML serialization.
 :)
declare variable $pxqdoc:serParamXml :=
  <output:serialization-parameters>
    <output:method value="xml"/>
    <output:indent value="yes"/>
  </output:serialization-parameters>;

(:~
 : Delete the intermediary xml dir
 :
 : @param $xqdocPath where to generate the XQDoc XML documents.
 : @return empty sequence.
 :)
declare %an:sequential function pxqdoc:delete-XML-dir(
  $xqdocPath as xs:string)
{
  variable $xqdocXMLPath  := fn:concat( $xqdocPath,
                                        file:directory-separator(),
                                        "xml");
  (: clear the XML folder :)
  if(file:exists($xqdocXMLPath)) then
    file:delete($xqdocXMLPath);
  else ();
};

declare %private %an:nondeterministic function pxqdoc:load-manifest(
  $zorbaManifestPath as xs:string)
{
  try
  {
    fn:parse-xml(file:read-text($zorbaManifestPath))
  }
  catch *
  {
    fn:error($err:UE004,fn:concat("The file <",$zorbaManifestPath,"> does not have the correct structure."))
  }
};

(:~
 : This function generates the XQDoc XML for all the modules found in build/ZorbaManifest.xml
 :
 : @param $zorbaManifestPath location of ZorbaManifest.xml.
 : @param $xqdocPath where to generate the XQDoc XML documents.
 : @return empty sequence.
 :)
declare %an:sequential function pxqdoc:generate-xqdoc-XML(
  $zorbaManifestPath as xs:string,
  $xqdocPath as xs:string)
{
  (: Note: only the modules that are configured in the Zorba version you are using will be build :)
  variable $xqdocXMLPath := concat($xqdocPath, file:directory-separator(), "xml");

  (: create the XML folder if it does not exist already :)
  file:create-directory($xqdocXMLPath);

  if(not(file:is-file($zorbaManifestPath))) then
  {
    variable $message := fn:concat("The file <ZorbaManifest.xml> was not found: <", $zorbaManifestPath, ">. Suggestion: run 'cmake' in your build folder such that ZorbaManifest.xml is regenerated.");
    fn:error($err:UE004, $message);
  }
  else
  {
    variable $manifestXML := pxqdoc:load-manifest($zorbaManifestPath);
    variable $moduleManifests := $manifestXML/zm:manifest/zm:module;
    if(count($moduleManifests) eq xs:integer(0)) then ();
    else
    {
      for $module in $moduleManifests
      (: note the module version is not supported because of a bug in the fetch for the module URI ending with / :)
      (:let $moduleURI := if(ends-with(data($module/zm:uri),'/')) then data($module/zm:uri)
                       else if(exists($module/@version)) then concat(data($module/zm:uri),"#",data($module/@version))
                       else data($module/zm:uri):)
      (:let $moduleFetched := fetch:content(trace($moduleURI,"fetch module URI version.."), "MODULE"):)
      let $moduleURI := if(ends-with(data($module/zm:uri),".xq")) then substring-before(data($module/zm:uri),".xq") else data($module/zm:uri)
      let $moduleFetched := fetch:content($moduleURI, "MODULE")
      let $xqdoc := xqd:xqdoc-content($moduleFetched)
      let $xqdocRelFileName  := pxqdoc:get-filename($moduleURI)
      let $xqdocFileName := concat($xqdocXMLPath, file:directory-separator(), $xqdocRelFileName, ".xml")
      return
        file:write($xqdocFileName,
                   $xqdoc,
                   $pxqdoc:serParamXml)
    };
  }
};

(:~
 : Returns the string resulting from replacing the directory-separators (i.e. / ) with '_'
 :
 : @param $moduleURI the path to the module URI.
 : @return the string resulting from replacing the directory-separators (i.e. / ) with '_'.
 :
 :)
declare function pxqdoc:get-filename(
  $moduleURI as xs:string) as xs:string {
  let $lmodule := if(fn:ends-with($moduleURI,"/")) then fn:concat($moduleURI,"index") else $moduleURI
  return
    replace(
      replace($lmodule, "/", "_"),
      "http:__",
      ""
  )
};


Typo.

Typo.

let $testdoc := doc("testdoc.xml") return (
(:
test insert attribute with the following tests:
-- non-existing qn non-existing value
-- existing qn non-existing value
-- non-existing qn existing value
-- existing qn existing value
test rename attribute with the following tests:
-- non-existing qn
-- existing qn
test replace attribute value with the following tests:
-- non-existing value
-- existing value
test delete attribute

In passing, also test that rename preserves identity.
:)
for $elem in $testdoc/document/element
	return (do insert attribute author {"Sjoerd Mullender"} into exactly-one($elem),
		do insert attribute title {"test element"} into exactly-one($elem),
		do insert attribute attr {text{$elem/@attribute}} into exactly-one($elem),
		do insert attribute copyright {text{$elem/../@copyright}} into exactly-one($elem),

		do rename exactly-one($elem/@attribute) with "Attribute",

		do rename exactly-one($elem/@dummy) with "foo",
		do replace value of exactly-one($elem/@xyzzy) with "hgulp",
		do replace value of exactly-one($elem/@dummy) with "bar")
,
do delete ($testdoc/document/@title, $testdoc/document/@copyright, $testdoc/document/@foo)
,
(: test changing comment value with the following test:
-- new text
:)
for $elem in $testdoc//comment()
	return do replace value of exactly-one($elem) with concat(text{$elem}, "foo ")
,
(: test changing CDATA content with the following tests:
-- new text
:)
for $elem in $testdoc/document/element/text()
	return do replace value of exactly-one($elem) with concat("element ", text{$elem})
,
(: test changing processing instructions with the following tests:
-- existing instruction, new target
-- new instruction, existing target
-- new instruction, new target - XXX can't be done since there is no PI construction
-- rename instruction and replace target
:)
(do replace value of exactly-one($testdoc//processing-instruction(pi0000)) with "foo",
 do rename exactly-one($testdoc//processing-instruction(pi1000)) with "bar",
 do replace exactly-one($testdoc//processing-instruction(pi2000)) with (: <?target instruction?> :) exactly-one($testdoc//processing-instruction(pi4000)),
 do rename exactly-one($testdoc//processing-instruction(pi5000)) with "xyzzy",
 do replace value of exactly-one($testdoc//processing-instruction(pi5000)) with "plugh")
,
(: test delete with the following tests:
-- deleting text
-- deleting element
-- deleting comment
-- deleting processing instruction
:)
do delete ($testdoc/document/text()[1],
	   $testdoc/document/element[10],
	   $testdoc/document/comment()[3],
	   $testdoc//processing-instruction("pi4000"))
,
(: test insert with the following tests:
-- test multiple insert as first
-- test multiple insert as last
-- test multiple insert before
-- test multiple insert after
:)
for $node in $testdoc/document/element[@attribute = 10]
  return typeswitch ($node)
         case $elem as element()
       return (do insert <a/> as first into $elem,
                   do insert <b/> as first into $elem)
         default return error ("we expect a single element as input")
,
for $node in $testdoc/document/element[@attribute = 20]
  return typeswitch ($node)
         case $elem as element()
       return (do insert <a/> as last into $elem,
                   do insert <b/> as last into $elem)
         default return error ("we expect a single element as input")
(:
for $elem in $testdoc/document/element[@attribute = 10]
  return (do insert <a/> as first into exactly-one($elem),
	  do insert <b/> as first into exactly-one($elem))
,
for $elem in $testdoc/document/element[@attribute = 20]
  return (do insert <a/> as last into exactly-one($elem),
	  do insert <b/> as last into exactly-one($elem))
:)
,
for $elem in $testdoc/document/element[@attribute = 30]
  return (do insert <a/> before exactly-one($elem),
	  do insert <b/> before exactly-one($elem))
,
for $elem in $testdoc/document/element[@attribute = 40]
  return (do insert <a/> after exactly-one($elem),
	  do insert <b/> after exactly-one($elem))
)

let $testdoc := doc("testdoc.xml") return (
(:
test insert attribute with the following tests:
-- non-existing qn non-existing value
-- existing qn non-existing value
-- non-existing qn existing value
-- existing qn existing value
test rename attribute with the following tests:
-- non-existing qn
-- existing qn
test replace attribute value with the following tests:
-- non-existing value
-- existing value
test delete attribute

In passing, also test that rename preserves identity.
:)
for $elem in $testdoc/document/element
	return (do insert attribute author {"Sjoerd Mullender"} into exactly-one($elem),
		do insert attribute title {"test element"} into exactly-one($elem),
		do insert attribute attr {text{$elem/@attribute}} into exactly-one($elem),
		do insert attribute copyright {text{$elem/../@copyright}} into exactly-one($elem),

		do rename exactly-one($elem/@attribute) with "Attribute",

		do rename exactly-one($elem/@dummy) with "foo",
		do replace value of exactly-one($elem/@xyzzy) with "hgulp",
		do replace value of exactly-one($elem/@dummy) with "bar")
,
do delete ($testdoc/document/@title, $testdoc/document/@copyright, $testdoc/document/@foo)
,
(: test changing comment value with the following test:
-- new text
:)
for $elem in $testdoc//comment()
	return do replace value of exactly-one($elem) with concat(text{$elem}, "foo ")
,
(: test changing CDATA content with the following tests:
-- new text
:)
for $elem in $testdoc/document/element/text()
	return do replace value of exactly-one($elem) with concat("element ", text{$elem})
,
(: test chaning processing instructions with the following tests:
-- existing instruction, new target
-- new instruction, existing target
-- new instruction, new target - XXX can't be done since there is no PI construction
-- rename instruction and replace target
:)
(do replace value of exactly-one($testdoc//processing-instruction(pi0000)) with "foo",
 do rename exactly-one($testdoc//processing-instruction(pi1000)) with "bar",
 do replace exactly-one($testdoc//processing-instruction(pi2000)) with (: <?target instruction?> :) exactly-one($testdoc//processing-instruction(pi4000)),
 do rename exactly-one($testdoc//processing-instruction(pi5000)) with "xyzzy",
 do replace value of exactly-one($testdoc//processing-instruction(pi5000)) with "plugh")
,
(: test delete with the following tests:
-- deleting text
-- deleting element
-- deleting comment
-- deleting processing instruction
:)
do delete ($testdoc/document/text()[1],
	   $testdoc/document/element[10],
	   $testdoc/document/comment()[3],
	   $testdoc//processing-instruction("pi4000"))
,
(: test insert with the following tests:
-- test multiple insert as first
-- test multiple insert as last
-- test multiple insert before
-- test multiple insert after
:)
for $node in $testdoc/document/element[@attribute = 10]
  return typeswitch ($node)
         case $elem as element()
       return (do insert <a/> as first into $elem,
                   do insert <b/> as first into $elem)
         default return error ("we expect a single element as input")
,
for $node in $testdoc/document/element[@attribute = 20]
  return typeswitch ($node)
         case $elem as element()
       return (do insert <a/> as last into $elem,
                   do insert <b/> as last into $elem)
         default return error ("we expect a single element as input")
(:
for $elem in $testdoc/document/element[@attribute = 10]
  return (do insert <a/> as first into exactly-one($elem),
	  do insert <b/> as first into exactly-one($elem))
,
for $elem in $testdoc/document/element[@attribute = 20]
  return (do insert <a/> as last into exactly-one($elem),
	  do insert <b/> as last into exactly-one($elem))
:)
,
for $elem in $testdoc/document/element[@attribute = 30]
  return (do insert <a/> before exactly-one($elem),
	  do insert <b/> before exactly-one($elem))
,
for $elem in $testdoc/document/element[@attribute = 40]
  return (do insert <a/> after exactly-one($elem),
	  do insert <b/> after exactly-one($elem))
)