Additional biblio setup for users groups

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

xquery version "1.0";
(: $Id$ :)
(:
    Module: examples setup
:)

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

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

declare namespace xproc="http://xproc.net/xproc";

declare function setup:main() as element()
{

Examples Setup

        {
let $action := request:get-parameter("action", ()) return
		if($action) then
		                (
		                    if($action eq "Import Example Data") then
		                    (
		                        setup:importLocal()
		                    )
		                    else if($action eq "Import Files") then
		                    (
		                        setup:importFromURLs()
		                    )
		                    else
		                    (
		                        setup:report()
		                    )
		                )
		                else
		                (
		                    setup:select()
		                )

        }

};

declare function setup:importLocal() as element()+
{
    let $home := system:get-exist-home(),
    $pathSep := util:system-property("file.separator"),
    $dir := if (doc-available(concat("file:///", $home, "/exist-samples/examples.xml"))) then
        (
            concat($home, $pathSep, "exist-samples")
        )
        else if(ends-with($home, "WEB-INF")) then
        (
            concat(substring-before($home, "WEB-INF"), "samples")
        )
        else
        (
            concat($home, $pathSep, "samples")
        ),
    $webapp := if (doc-available(concat("file:///", $home, "/webapp/index.xml"))) then
        (
            concat($home, $pathSep, "webapp")
        )
        else if(ends-with($home, "WEB-INF")) then
        (
            substring-before($home, "WEB-INF")
        )
        else
        (
            concat($home, $pathSep, "webapp")
        )
        (: ,
        $betterform := concat($home, "/extensions/betterform/src/main/xrx/timetracker/")
        :)
    return (
                setup:create-collection("/db/system/config", "db"),
                setup:create-collection("/db/system/config/db", "shakespeare"),
                setup:store-files("/db/system/config/db/shakespeare", $dir,
                    "shakespeare/collection.xconf", "text/xml"),
                setup:create-collection("/db", "shakespeare"),
                setup:create-collection("/db/shakespeare", "plays"),
                setup:store-files("/db/shakespeare/plays", $dir,  "shakespeare/*.xml", "text/xml"),
                setup:store-files("/db/shakespeare/plays", $dir, "shakespeare/*.xsl", "text/xml"),
                setup:store-files("/db/shakespeare/plays", $dir, "shakespeare/*.css", "text/css"),
                setup:create-collection("/db", "xinclude"),
                setup:create-collection("/db/xinclude", "styles"),
                setup:store-files("/db/xinclude", $dir, "xinclude/*.xsl", "text/xml"),
                setup:store-files("/db/xinclude", $dir, "xinclude/*.xml", "text/xml"),
                setup:store-files("/db/xinclude", $dir, "xinclude/*.xq", "application/xquery"),
                setup:store-files("/db/xinclude", $dir, "xinclude/*.jpg", "image/jpeg"),
                setup:store-files("/db/xinclude/styles", $dir, "xinclude/styles/*", "text/css"),
                setup:create-collection("/db/xinclude", "scripts"),
                setup:create-collection("/db/xinclude/scripts", "syntax"),
                setup:store-files("/db/xinclude/scripts/syntax", $dir, "xinclude/scripts/syntax/*.js", "application/x-javascript"),
                setup:create-collection("/db", "library"),
                setup:store-files("/db/library", $dir, "*.rdf", "text/xml"),
                setup:create-collection("/db/system/config/db", "mods"),
                setup:store-files("/db/system/config/db/mods", $dir, "mods/collection.xconf", "text/xml"),
                setup:create-collection("/db", "mods"),
                setup:create-collection("/db/mods", "eXist"),
                setup:create-collection("/db/mods", "samples"),
                setup:create-collection("/db/mods", "users"),
                setup:create-group("biblio.users"),
                setup:set-collection-group("/db/mods/users", "biblio.users"),
                setup:set-collection-permissions("/db/mods/users", "rwurwu---"),
                setup:create-collection("/db/mods", "groups"),
                setup:set-collection-group("/db/mods/groups", "biblio.users"),
                setup:set-collection-permissions("/db/mods/groups", "rwurwu---"),
                setup:store-files("/db/mods/samples", $dir, "mods/*.xml", "text/xml"),
                setup:store-files("/db/mods/eXist", $dir, "mods/eXist/*.xml", "text/xml"),
                setup:store-files("/db", $dir, "*.xml", "text/xml"),
                setup:create-collection("/db/system/config/db", "mondial"),
                setup:store-files("/db/system/config/db/mondial", $dir, "mondial.xconf", "text/xml"),
                setup:create-collection("/db/system/config/db", "xmlad"),
                setup:store-files("/db/system/config/db/xmlad", $dir, "acronyms.xconf", "text/xml"),

                (: Storing Testing :)
                setup:create-collection("/db", "testing"),
                setup:store-files("/db/testing", $webapp, "testing/*.xml", "text/html"),
                setup:store-files("/db/testing", $webapp, "testing/*.xq*", "application/xquery"),
                setup:create-collection("/db/testing", "examples"),
                setup:store-files("/db/testing/examples", $webapp, "testing/examples/*.xml", "text/html"),
                setup:store-files("/db/testing/examples", $webapp, "testing/examples/*.xq*", "application/xquery"),

                (: Storing XProc :)
                setup:create-collection("/db", "xproc"),
                setup:create-collection("/db/xproc", "unit-test"),
                setup:create-collection("/db/xproc", "xml"),
                setup:create-collection("/db/xproc", "xslt"),
                setup:create-collection("/db/xproc", "result"),
                setup:create-collection("/db/xproc", "examples"),
                setup:create-collection("/db/xproc", "pipelines"),
                setup:store-files("/db/xproc/unit-test", $webapp, "xproc/unit-test/*.xml", "text/xml"),
                setup:store-files("/db/xproc/unit-test", $webapp, "xproc/unit-test/*.xql", "application/xquery"),
                setup:store-files("/db/xproc/unit-test", $webapp, "xproc/unit-test/*.xsl", "text/xml"),

                setup:store-files("/db/xproc/pipelines", $webapp, "xproc/pipelines/*.xml", "text/xml"),
                setup:store-files("/db/xproc/xml", $webapp, "xproc/xml/*.xml", "text/xml"),
                setup:store-files("/db/xproc/xslt", $webapp, "xproc/xml/*.xsl", "text/xml"),

                setup:store-files("/db/xproc/examples", $webapp, "xproc/examples/*.xproc", "application/xml+xproc"),
                setup:store-files("/db/xproc/examples", $webapp, "xproc/examples/*.xml", "text/xml"),

                setup:store-files("/db/xproc/examples", $webapp, "xproc/examples/*.xql", "application/xquery"),
                setup:store-files("/db/xproc", $webapp, "xproc/*.xml", "text/xml"),
                setup:store-files("/db/xproc", $webapp, "xproc/*.xql", "application/xquery") (:,

                (: Storing XForms in the db won't work right now :)

                setup:create-collection("/db", "xforms"),
                setup:store-files("/db/xforms", $webapp, "xforms/*.xml", "text/html"),
                setup:store-files("/db/xforms", $webapp, "xforms/*.xq*", "application/xquery"),
                setup:create-collection("/db/xforms", "xsltforms"),
                setup:create-collection("/db/xforms", "data"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.properties", "text/plain"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.png", "image/png"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.gif", "image/gif"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.xsl","text/xml"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.js","application/x-javascript"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.css","text/css")
                :)

				(: Storing betterFORM XRX sample application :)
				(:
				setup:create-collection("/db", "betterform"),
				setup:create-collection("/db/betterform", "apps"),
				setup:create-collection("/db/betterform/apps", "timetracker"),
				setup:store-files("/db/betterform/apps/timetracker", $betterform, "*.xql","application/xquery"),
				setup:store-files("/db/betterform/apps/timetracker", $betterform, "*.html","text/html"),
				setup:store-files("/db/betterform/apps/timetracker", $betterform, "*.xml","application/xml"),
				setup:create-collection("/db/betterform/apps/timetracker", "data"),
				setup:store-files("/db/betterform/apps/timetracker/data", $betterform, "data/*.xml", "application/xml"),
				setup:create-collection("/db/betterform/apps/timetracker/data", "task"),
				setup:store-files("/db/betterform/apps/timetracker/data/task", $betterform, "data/task/*.xml","application/xml"),
				setup:create-collection("/db/betterform/apps/timetracker/", "edit"),
				setup:store-files("/db/betterform/apps/timetracker/edit", $betterform, "edit/*.xql","application/xquery"),
				setup:create-collection("/db/betterform/apps/timetracker/", "lucene"),
				setup:store-files("/db/betterform/apps/timetracker/lucene", $betterform, "lucene/*.xconf","application/xml"),
				setup:create-collection("/db/betterform/apps/timetracker/", "reports"),
				setup:store-files("/db/betterform/apps/timetracker/reports", $betterform, "reports/*.xql","application/xquery"),
				setup:create-collection("/db/betterform/apps/timetracker/", "resources"),
				setup:store-files("/db/betterform/apps/timetracker/resources", $betterform, "resources/*.css","text/css"),
				setup:create-collection("/db/betterform/apps/timetracker/resources", "images"),
				setup:store-files("/db/betterform/apps/timetracker/resources/images", $betterform, "resources/images/*.gif","image/gif"),
				setup:store-files("/db/betterform/apps/timetracker/resources/images", $betterform, "resources/images/*.png","image/png"),
				setup:store-files("/db/betterform/apps/timetracker/resources/images", $betterform, "resources/images/*.jpg","image/jpeg"),
				setup:create-collection("/db/betterform/apps/timetracker/", "search"),
				setup:store-files("/db/betterform/apps/timetracker/search", $betterform, "search/*.xql","application/xquery"),
				setup:store-files("/db/betterform/apps/timetracker/search", $betterform, "search/*.html","text/html"),
				setup:create-collection("/db/betterform/apps/timetracker/", "update"),
				setup:store-files("/db/betterform/apps/timetracker/update", $betterform, "update/*.xql","application/xquery"),
				setup:create-collection("/db/betterform/apps/timetracker/", "views"),
				setup:store-files("/db/betterform/apps/timetracker/views", $betterform, "views/*.xql","application/xquery"),
				setup:store-files("/db/betterform/apps/timetracker/views", $betterform, "views/*.html","text/html"),
				setup:store-files("/db/betterform/apps/timetracker/views", $betterform, "views/*.xsl","application/xml")
                :)
    )
};

declare function setup:importFromURLs() as element()+
{
    (
        setup:report(),

Actions:

            {
                let $includeXmlad := request:get-parameter("xmlad", ()),
                $includeMondial := request:get-parameter("mondial", ()),
 				$includeLocal := request:get-parameter("local", ()) return
                (
					if($includeLocal) then
					( setup:importLocal()
					)
					else (),
                    if($includeXmlad) then
                    (
                        setup:create-collection("/db", "xmlad"),
                        setup:load-URL("/db/xmlad", xs:anyURI("http://surfnet.dl.sourceforge.net/sourceforge/xmlad/xmlad.xml"), "xmlad.xml")
                    )else (),
                    if($includeMondial) then
                    (
                        setup:create-collection("/db", "mondial"),
                        setup:load-URL("/db/mondial", xs:anyURI("http://www.dbis.informatik.uni-goettingen.de/Mondial/mondial-europe.xml"), "mondial.xml")
                    )else ()
                )
            }

    )
};

declare function setup:load-URL($collection as xs:string, $url as xs:anyURI, $docName as xs:string) as element()
{
    let $x := xdb:store($collection, $docName, $url) return

File {$docName} imported from url: {$url}

};

declare function setup:store-files($collection as xs:string, $home as xs:string, $patterns as xs:string, $mimeType as xs:string) as element()*
{
    let $stored := xdb:store-files-from-pattern($collection, $home, $patterns, $mimeType)
    for $doc in $stored return

Uploaded: {$doc}

};

declare function setup:create-collection($parent as xs:string, $name as xs:string) as element()
{
    let $col := xdb:create-collection($parent, $name) return

Created collection: {$col}

};

declare function setup:create-group($group as xs:string) as element()
{
    let $result := xdb:create-group($group) return
        if($result)then (

Created group: {$group}

        ) else (

Failed to create group: {$group}

        )
};

declare function setup:set-collection-group($collection as xs:string, $group as xs:string) as element() {
    let $null := xdb:set-collection-permissions($collection, xdb:get-owner($collection), $group, xdb:get-permissions($collection)) return

Set collection '{$collection}' group to '{$group}'

};

declare function setup:set-collection-permissions($collection as xs:string, $permissions as xs:string) as element() {
        let $null := xdb:set-collection-permissions($collection, xdb:get-owner($collection), xdb:get-group($collection), xdb:string-to-permissions($permissions)) return

Set collection '{$collection}' permissions '{$permissions}'.

};

declare function setup:select() as element()
{
    <form action="{session:encode-url(request:get-uri())}" method="post">

eXist ships with a number of XQuery examples. Some of these
        require certain documents to be stored in the database. The XQuery examples also use some
		XML data not included with the distribution which can be downloaded by selecting
		the checkboxes below.

		<input type="checkbox" name="local" checked="true"/>
		eXist-db shipped files

        <input type="checkbox" name="xmlad"/>
        The XML Acronym Demystifier
        (approx. 384K)

        <input type="checkbox" name="mondial"/>
        The Mondial Database (Europe)
        (approx. 410K)

<input type="submit" name="action" value="Import Files"/>
        <input type="submit" name="action" value="Skip"/>

        <input type="hidden" name="panel" value="setup"/>
    </form>
};

declare function setup:report() as element()
{

Files have been loaded. You can now go to the
    examples page.

};

xquery version "1.0";
(: $Id$ :)
(:
    Module: examples setup
:)

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

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

declare namespace xproc="http://xproc.net/xproc";

declare function setup:main() as element()
{

Examples Setup

        {
let $action := request:get-parameter("action", ()) return
		if($action) then
		                (
		                    if($action eq "Import Example Data") then
		                    (
		                        setup:importLocal()
		                    )
		                    else if($action eq "Import Files") then
		                    (
		                        setup:importFromURLs()
		                    )
		                    else
		                    (
		                        setup:report()
		                    )
		                )
		                else
		                (
		                    setup:select()
		                )

        }

};

declare function setup:importLocal() as element()+
{
    let $home := system:get-exist-home(),
    $pathSep := util:system-property("file.separator"),
    $dir := if (doc-available(concat("file:///", $home, "/exist-samples/examples.xml"))) then
        (
            concat($home, $pathSep, "exist-samples")
        )
        else if(ends-with($home, "WEB-INF")) then
        (
            concat(substring-before($home, "WEB-INF"), "samples")
        )
        else
        (
            concat($home, $pathSep, "samples")
        ),
    $webapp := if (doc-available(concat("file:///", $home, "/webapp/index.xml"))) then
        (
            concat($home, $pathSep, "webapp")
        )
        else if(ends-with($home, "WEB-INF")) then
        (
            substring-before($home, "WEB-INF")
        )
        else
        (
            concat($home, $pathSep, "webapp")
        )
        (: ,
        $betterform := concat($home, "/extensions/betterform/src/main/xrx/timetracker/")
        :)
    return (
                setup:create-collection("/db/system/config", "db"),
                setup:create-collection("/db/system/config/db", "shakespeare"),
                setup:store-files("/db/system/config/db/shakespeare", $dir,
                    "shakespeare/collection.xconf", "text/xml"),
                setup:create-collection("/db", "shakespeare"),
                setup:create-collection("/db/shakespeare", "plays"),
                setup:store-files("/db/shakespeare/plays", $dir,  "shakespeare/*.xml", "text/xml"),
                setup:store-files("/db/shakespeare/plays", $dir, "shakespeare/*.xsl", "text/xml"),
                setup:store-files("/db/shakespeare/plays", $dir, "shakespeare/*.css", "text/css"),
                setup:create-collection("/db", "xinclude"),
                setup:create-collection("/db/xinclude", "styles"),
                setup:store-files("/db/xinclude", $dir, "xinclude/*.xsl", "text/xml"),
                setup:store-files("/db/xinclude", $dir, "xinclude/*.xml", "text/xml"),
                setup:store-files("/db/xinclude", $dir, "xinclude/*.xq", "application/xquery"),
                setup:store-files("/db/xinclude", $dir, "xinclude/*.jpg", "image/jpeg"),
                setup:store-files("/db/xinclude/styles", $dir, "xinclude/styles/*", "text/css"),
                setup:create-collection("/db/xinclude", "scripts"),
                setup:create-collection("/db/xinclude/scripts", "syntax"),
                setup:store-files("/db/xinclude/scripts/syntax", $dir, "xinclude/scripts/syntax/*.js", "application/x-javascript"),
                setup:create-collection("/db", "library"),
                setup:store-files("/db/library", $dir, "*.rdf", "text/xml"),
                setup:create-collection("/db/system/config/db", "mods"),
                setup:store-files("/db/system/config/db/mods", $dir, "mods/collection.xconf", "text/xml"),
                setup:create-collection("/db", "mods"),
                setup:create-collection("/db/mods", "eXist"),
                setup:create-collection("/db/mods", "samples"),
                setup:create-collection("/db/mods", "users"),
                setup:create-group("biblio.users"),
                setup:set-collection-group("/db/mods/users", "biblio.users"),
                setup:set-collection-permissions("/db/mods/users", "rwurwu---"),
                setup:store-files("/db/mods/samples", $dir, "mods/*.xml", "text/xml"),
                setup:store-files("/db/mods/eXist", $dir, "mods/eXist/*.xml", "text/xml"),
                setup:store-files("/db", $dir, "*.xml", "text/xml"),
                setup:create-collection("/db/system/config/db", "mondial"),
                setup:store-files("/db/system/config/db/mondial", $dir, "mondial.xconf", "text/xml"),
                setup:create-collection("/db/system/config/db", "xmlad"),
                setup:store-files("/db/system/config/db/xmlad", $dir, "acronyms.xconf", "text/xml"),

                (: Storing Testing :)
                setup:create-collection("/db", "testing"),
                setup:store-files("/db/testing", $webapp, "testing/*.xml", "text/html"),
                setup:store-files("/db/testing", $webapp, "testing/*.xq*", "application/xquery"),
                setup:create-collection("/db/testing", "examples"),
                setup:store-files("/db/testing/examples", $webapp, "testing/examples/*.xml", "text/html"),
                setup:store-files("/db/testing/examples", $webapp, "testing/examples/*.xq*", "application/xquery"),

                (: Storing XProc :)
                setup:create-collection("/db", "xproc"),
                setup:create-collection("/db/xproc", "unit-test"),
                setup:create-collection("/db/xproc", "xml"),
                setup:create-collection("/db/xproc", "xslt"),
                setup:create-collection("/db/xproc", "result"),
                setup:create-collection("/db/xproc", "examples"),
                setup:create-collection("/db/xproc", "pipelines"),
                setup:store-files("/db/xproc/unit-test", $webapp, "xproc/unit-test/*.xml", "text/xml"),
                setup:store-files("/db/xproc/unit-test", $webapp, "xproc/unit-test/*.xql", "application/xquery"),
                setup:store-files("/db/xproc/unit-test", $webapp, "xproc/unit-test/*.xsl", "text/xml"),

                setup:store-files("/db/xproc/pipelines", $webapp, "xproc/pipelines/*.xml", "text/xml"),
                setup:store-files("/db/xproc/xml", $webapp, "xproc/xml/*.xml", "text/xml"),
                setup:store-files("/db/xproc/xslt", $webapp, "xproc/xml/*.xsl", "text/xml"),

                setup:store-files("/db/xproc/examples", $webapp, "xproc/examples/*.xproc", "application/xml+xproc"),
                setup:store-files("/db/xproc/examples", $webapp, "xproc/examples/*.xml", "text/xml"),

                setup:store-files("/db/xproc/examples", $webapp, "xproc/examples/*.xql", "application/xquery"),
                setup:store-files("/db/xproc", $webapp, "xproc/*.xml", "text/xml"),
                setup:store-files("/db/xproc", $webapp, "xproc/*.xql", "application/xquery") (:,

                (: Storing XForms in the db won't work right now :)

                setup:create-collection("/db", "xforms"),
                setup:store-files("/db/xforms", $webapp, "xforms/*.xml", "text/html"),
                setup:store-files("/db/xforms", $webapp, "xforms/*.xq*", "application/xquery"),
                setup:create-collection("/db/xforms", "xsltforms"),
                setup:create-collection("/db/xforms", "data"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.properties", "text/plain"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.png", "image/png"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.gif", "image/gif"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.xsl","text/xml"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.js","application/x-javascript"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.css","text/css")
                :)

				(: Storing betterFORM XRX sample application :)
				(:
				setup:create-collection("/db", "betterform"),
				setup:create-collection("/db/betterform", "apps"),
				setup:create-collection("/db/betterform/apps", "timetracker"),
				setup:store-files("/db/betterform/apps/timetracker", $betterform, "*.xql","application/xquery"),
				setup:store-files("/db/betterform/apps/timetracker", $betterform, "*.html","text/html"),
				setup:store-files("/db/betterform/apps/timetracker", $betterform, "*.xml","application/xml"),
				setup:create-collection("/db/betterform/apps/timetracker", "data"),
				setup:store-files("/db/betterform/apps/timetracker/data", $betterform, "data/*.xml", "application/xml"),
				setup:create-collection("/db/betterform/apps/timetracker/data", "task"),
				setup:store-files("/db/betterform/apps/timetracker/data/task", $betterform, "data/task/*.xml","application/xml"),
				setup:create-collection("/db/betterform/apps/timetracker/", "edit"),
				setup:store-files("/db/betterform/apps/timetracker/edit", $betterform, "edit/*.xql","application/xquery"),
				setup:create-collection("/db/betterform/apps/timetracker/", "lucene"),
				setup:store-files("/db/betterform/apps/timetracker/lucene", $betterform, "lucene/*.xconf","application/xml"),
				setup:create-collection("/db/betterform/apps/timetracker/", "reports"),
				setup:store-files("/db/betterform/apps/timetracker/reports", $betterform, "reports/*.xql","application/xquery"),
				setup:create-collection("/db/betterform/apps/timetracker/", "resources"),
				setup:store-files("/db/betterform/apps/timetracker/resources", $betterform, "resources/*.css","text/css"),
				setup:create-collection("/db/betterform/apps/timetracker/resources", "images"),
				setup:store-files("/db/betterform/apps/timetracker/resources/images", $betterform, "resources/images/*.gif","image/gif"),
				setup:store-files("/db/betterform/apps/timetracker/resources/images", $betterform, "resources/images/*.png","image/png"),
				setup:store-files("/db/betterform/apps/timetracker/resources/images", $betterform, "resources/images/*.jpg","image/jpeg"),
				setup:create-collection("/db/betterform/apps/timetracker/", "search"),
				setup:store-files("/db/betterform/apps/timetracker/search", $betterform, "search/*.xql","application/xquery"),
				setup:store-files("/db/betterform/apps/timetracker/search", $betterform, "search/*.html","text/html"),
				setup:create-collection("/db/betterform/apps/timetracker/", "update"),
				setup:store-files("/db/betterform/apps/timetracker/update", $betterform, "update/*.xql","application/xquery"),
				setup:create-collection("/db/betterform/apps/timetracker/", "views"),
				setup:store-files("/db/betterform/apps/timetracker/views", $betterform, "views/*.xql","application/xquery"),
				setup:store-files("/db/betterform/apps/timetracker/views", $betterform, "views/*.html","text/html"),
				setup:store-files("/db/betterform/apps/timetracker/views", $betterform, "views/*.xsl","application/xml")
                :)
    )
};

declare function setup:importFromURLs() as element()+
{
    (
        setup:report(),

Actions:

            {
                let $includeXmlad := request:get-parameter("xmlad", ()),
                $includeMondial := request:get-parameter("mondial", ()),
 				$includeLocal := request:get-parameter("local", ()) return
                (
					if($includeLocal) then
					( setup:importLocal()
					)
					else (),
                    if($includeXmlad) then
                    (
                        setup:create-collection("/db", "xmlad"),
                        setup:load-URL("/db/xmlad", xs:anyURI("http://surfnet.dl.sourceforge.net/sourceforge/xmlad/xmlad.xml"), "xmlad.xml")
                    )else (),
                    if($includeMondial) then
                    (
                        setup:create-collection("/db", "mondial"),
                        setup:load-URL("/db/mondial", xs:anyURI("http://www.dbis.informatik.uni-goettingen.de/Mondial/mondial-europe.xml"), "mondial.xml")
                    )else ()
                )
            }

    )
};

declare function setup:load-URL($collection as xs:string, $url as xs:anyURI, $docName as xs:string) as element()
{
    let $x := xdb:store($collection, $docName, $url) return

File {$docName} imported from url: {$url}

};

declare function setup:store-files($collection as xs:string, $home as xs:string, $patterns as xs:string, $mimeType as xs:string) as element()*
{
    let $stored := xdb:store-files-from-pattern($collection, $home, $patterns, $mimeType)
    for $doc in $stored return

Uploaded: {$doc}

};

declare function setup:create-collection($parent as xs:string, $name as xs:string) as element()
{
    let $col := xdb:create-collection($parent, $name) return

Created collection: {$col}

};

declare function setup:create-group($group as xs:string) as element()
{
    let $result := xdb:create-group($group) return
        if($result)then (

Created group: {$group}

        ) else (

Failed to create group: {$group}

        )
};

declare function setup:set-collection-group($collection as xs:string, $group as xs:string) as element() {
    let $null := xdb:set-collection-permissions($collection, xdb:get-owner($collection), $group, xdb:get-permissions($collection)) return

Set collection '{$collection}' group to '{$group}'

};

declare function setup:set-collection-permissions($collection as xs:string, $permissions as xs:string) as element() {
        let $null := xdb:set-collection-permissions($collection, xdb:get-owner($collection), xdb:get-group($collection), xdb:string-to-permissions($permissions)) return

Set collection '{$collection}' permissions '{$permissions}'.

};

declare function setup:select() as element()
{
    <form action="{session:encode-url(request:get-uri())}" method="post">

eXist ships with a number of XQuery examples. Some of these
        require certain documents to be stored in the database. The XQuery examples also use some
		XML data not included with the distribution which can be downloaded by selecting
		the checkboxes below.

		<input type="checkbox" name="local" checked="true"/>
		eXist-db shipped files

        <input type="checkbox" name="xmlad"/>
        The XML Acronym Demystifier
        (approx. 384K)

        <input type="checkbox" name="mondial"/>
        The Mondial Database (Europe)
        (approx. 410K)

<input type="submit" name="action" value="Import Files"/>
        <input type="submit" name="action" value="Skip"/>

        <input type="hidden" name="panel" value="setup"/>
    </form>
};

declare function setup:report() as element()
{

Files have been loaded. You can now go to the
    examples page.

};


Inital JSON converter.

Inital JSON converter.

xquery version "3.1" encoding "UTF-8";

declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";
declare namespace map = "http://www.w3.org/2005/xpath-functions/map";
declare namespace array = "http://www.w3.org/2005/xpath-functions/array";
declare namespace mapping = "http://docs.rackspace.com/identity/api/ext/MappingRules";
declare namespace xs = "http://www.w3.org/2001/XMLSchema";

declare option output:method "json";
declare option output:indent "yes";

declare function mapping:convertLocalGroup($local as element()) as map(*) {
  let $elems := $local/element()
  return map:merge(for $elem in $elems return map:entry(local-name($elem),string($elem/@value)))
};

declare function mapping:convertLocalGroups($local as element()) as map(*) {
  let $elems := $local/element()
  return map:merge(for $elem in $elems return map:entry(local-name($elem),mapping:convertLocalGroup($elem)))
};

let $rules := for $rule in /mapping:rules/mapping:rule return map {
  "local" : mapping:convertLocalGroups($rule/mapping:local),
  "remote" : "remotePart"
}
return map {"rules" : array{$rules}}

error: pathspec 'core/src/main/resources/xq/mapping2JSON.xq' did not match any file(s) known to git


Add BaseX Lazy Module function signatures.

xquery version "3.0";
(:~
: BaseX Lazy Module functions
:
: @see http://docs.basex.org/wiki/Lazy_Module
:)
module namespace lazy = "http://basex.org/modules/lazy";

import module namespace a = "http://reecedunn.co.uk/xquery/annotations" at "res://reecedunn.co.uk/xquery/annotations.xqy";

declare %a:since("basex", "9.0") function lazy:cache($items as item()*) as item()* external;
declare %a:since("basex", "9.1") function lazy:cache($items as item()*, $lazy as xs:boolean) as item()* external;
declare %a:since("basex", "9.0") function lazy:is-lazy($item as item()) as xs:boolean external;
declare %a:since("basex", "9.0") function lazy:is-cached($item as item()) as xs:boolean external;

error: pathspec 'src/main/resources/builtin/basex.org/modules/lazy.xqy' did not match any file(s) known to git


Script to show papers in order of most recently edited

import module namespace notes="http://cefn.com/readinglog/notes" at "/home/cefn/Documents/highwire/participatory firmware design/readinglog/scripts/server/xquery/lib/notes.xq";
import module namespace template="http://cefn.com/readinglog/template" at "/home/cefn/Documents/highwire/participatory firmware design/readinglog/scripts/server/xquery/lib/template.xq";

import module namespace uri = "http://zorba.io/modules/uri";
import module namespace file = "http://expath.org/ns/file";

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

let $refdir := '/home/cefn/Documents/highwire/participatory firmware design/readinglog/notes/'
return
template:webpage(

		{for $heading in notes:allnotes()//h1 let $datetime := file:last-modified(concat($refdir,file:base-name(uri:decode(document-uri(root($heading)))))) order by $datetime descending return
{string($heading)} {format-date(xs:date($datetime), "[D1o] [MNn], [Y]", "en", (), ())} {notes:paperlinks($heading)}
}

)

error: pathspec 'scripts/server/xquery/newest_papers.xq' did not match any file(s) known to git


[bugfix] fixed svnlog to work again

[bugfix] fixed svnlog to work again

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

xquery version "1.0";

declare namespace svnu="http://exist-db.org/svnutil";

import module namespace svn="http://exist-db.org/xquery/svn"
at "java:org.exist.xquery.modules.svn.SVNModule";

declare option exist:output-size-limit "-1";

declare option exist:serialize "media-type=text/html";

declare variable $USER := "anonymous";
declare variable $PASS := "anonymous";

declare variable $CATEGORIES :=
    <messages>
        <cat abbrev="\[bugfix.*\]">Bug Fixes</cat>
        <cat abbrev="\[feature.*\]">Features</cat>
        <cat abbrev="\[documentation.*\]">Documentation</cat>
        <cat abbrev="\[performance\]">Performance</cat>
        <cat abbrev="\[(lib-)?update\]">Updates</cat>
        <cat abbrev="\[refactor.*\]">Refactoring</cat>
        <cat abbrev="\[test.*\]">Test Suite</cat>
        <cat abbrev="\[general\]">General</cat>
        <cat abbrev="\[build.*\]">Build</cat>
    </messages>
;

declare variable $URIS :=
    <uris>
        <uri description="1.2 stable branch">https://exist.svn.sourceforge.net/svnroot/exist/branches/eXist-stable-1.2</uri>
        <uri description="1.3 development branch">https://exist.svn.sourceforge.net/svnroot/exist/trunk/eXist</uri>
    </uris>
;

declare variable $IGNORE := ('[ignore]', '[ingnore]', '[bugtest]', '[comment]',
    '[improvement]', '[unchecked]', '[cosmetic]');

declare function svnu:translate-category($abbrev as xs:string) as xs:string {
    let $verbose := $CATEGORIES/cat[matches($abbrev, @abbrev)]/text()
    return
        if ($verbose) then string($verbose[1])
        else $abbrev
};

declare function svnu:to-html($entries as element(entry)*) as element() {

    {
        for $entry in $entries
        order by xs:integer($entry/@rev) descending
        return

                {string($entry/@rev)}
                by {string($entry/@author)}
                at {string($entry/@date)}

{$entry/message/text()}

                {
                    for $path in $entry/paths/path
                    return

                        {
                            let $file := $path/text()
                            return

                                {$file}

                        }

                }

    }

};

declare function svnu:print-by-category($log as element(log)) as item()* {
    let $categories :=
        distinct-values(
            for $message in $log/entry/message
            return
                if ($message/text()) then text:groups($message/text(), "^(\[[^\]]+\])")[2] else ()
        )
    let $translated :=
        distinct-values(
            for $cat in $categories where not($cat = $IGNORE)
            return svnu:translate-category($cat)
        )
    return (

        {
            for $cat at $pos in $translated
            return

{$cat}

        }

,

        for $cat at $pos in $translated
        let $regex := concat('^', $CATEGORIES/cat[. = $cat]/@abbrev)
        return

{svnu:translate-category($cat)}

                {svnu:to-html($log/entry[matches(message, $regex)])}

    )
};

<book>
    <bookinfo>
        <graphic fileref="logo.jpg"/>
        <productname>Open Source Native XML Database</productname>
        <title>SVN Log</title>
        <link rel="stylesheet" type="text/css" href="styles/svn.css"/>

error: pathspec 'webapp/xquery/svnlog.xql' did not match any file(s) known to git


Add BaseX client module function signatures.

xquery version "3.0";
(:~
: BaseX client module functions
:
: @see http://docs.basex.org/wiki/Client_Module
:)
module namespace client = "http://basex.org/";

import module namespace a = "http://reecedunn.co.uk/xquery/annotations" at "res://reecedunn.co.uk/xquery/annotations.xqy";

declare %a:since("basex", "9.0") function client:connect($host as xs:string, $port as xs:integer, $user as xs:string, $password as xs:string) as xs:anyURI external;
declare %a:since("basex", "9.0") function client:execute($id as xs:anyURI, $command as xs:string) as xs:string external;
declare %a:since("basex", "9.0") function client:info($id as xs:anyURI) as xs:string external;
declare %a:since("basex", "9.0") function client:query($id as xs:anyURI, $query as xs:string) as item()* external;
declare %a:since("basex", "9.0") function client:query($id as xs:anyURI, $query as xs:string, $bindings as map(*)?) as item()* external;
declare %a:since("basex", "9.0") function client:close($id as xs:anyURI) as empty-sequence() external;

error: pathspec 'src/main/resources/builtin/basex/modules/client.xqy' did not match any file(s) known to git


new Conformance module

new Conformance module

module namespace comm = "http://hl7.org/fhir";
declare namespace rest = "http://www.exquery.com/restxq";
declare namespace bgdm = "http://bagridb.com/bagri-xdm";

declare
  %rest:GET
  %rest:path("/metadata")
  %rest:produces("application/fhir+xml")
  %rest:query-param("_format", "{$format}", "")
function comm:get-conformance($format as xs:string?) as element()* {
  <Conformance xmlns="http://hl7.org/fhir">
    <url value="http://bagridb.com"/>
    <version value="1.1-SNAPSHOT"/>
    <name value="Bagri DB"/>
    <status value="draft"/>
    <experimental value="true"/>
    <date value="{fn:current-dateTime()}"/>
    <publisher value="Bagri Project"/>
    <kind value="instance"/>
    <fhirVersion value="DSTU2"/>
    <acceptUnknown value="both"/>
    <format value="xml"/>
    <format value="json"/>
    <format value="application/fhir+xml"/>
    <format value="application/fhir+json"/>
  </Conformance>
};

(:

<Conformance xmlns="http://hl7.org/fhir">

 <url value="[uri]"/>
 <version value="[string]"/>
 <name value="[string]"/>
 <status value="[code]"/>
 <experimental value="[boolean]"/>
 <date value="[dateTime]"/>
 <publisher value="[string]"/>
 <contact>
  <name value="[string]"/>
  <telecom></telecom>
 </contact>
 <description value="[markdown]"/>
 <useContext></useContext>
 <requirements value="[markdown]"/>
 <copyright value="[string]"/>
 <kind value="[code]"/>
 <instantiates value="[uri]"/>
 <software>
  <name value="[string]"/>
  <version value="[string]"/>
  <releaseDate value="[dateTime]"/>
 </software>
 <implementation>
  <description value="[string]"/>
  <url value="[uri]"/>
 </implementation>
 <fhirVersion value="[id]"/>
 <acceptUnknown value="[code]"/>
 <format value="[code]"/>
 <profile></profile>
 <rest>
  <mode value="[code]"/>
  <documentation value="[string]"/>
  <security>
   <cors value="[boolean]"/>
   <service></service>
   <description value="[string]"/>
   <certificate>
    <type value="[code]"/>
    <blob value="[base64Binary]"/>
   </certificate>
  </security>
  <resource>
   <type value="[code]"/>
   <profile></profile>
   <documentation value="[markdown]"/>
   <interaction>

    <documentation value="[string]"/>
   </interaction>
   <versioning value="[code]"/>
   <readHistory value="[boolean]"/>
   <updateCreate value="[boolean]"/>
   <conditionalCreate value="[boolean]"/>
   <conditionalRead value="[code]"/>
   <conditionalUpdate value="[boolean]"/>
   <conditionalDelete value="[code]"/>
   <searchInclude value="[string]"/>
   <searchRevInclude value="[string]"/>
   <searchParam>
    <name value="[string]"/>
    <definition value="[uri]"/>
    <type value="[code]"/>
    <documentation value="[string]"/>
    <target value="[code]"/>
    <modifier value="[code]"/>
    <chain value="[string]"/>
   </searchParam>
  </resource>
  <interaction>

   <documentation value="[string]"/>
  </interaction>
  <searchParam></searchParam>
  <operation>
   <name value="[string]"/>
   <definition></definition>
  </operation>
  <compartment value="[uri]"/>
 </rest>
 <messaging>
  <endpoint>
   <protocol></protocol>
   <address value="[uri]"/>
  </endpoint>
  <reliableCache value="[unsignedInt]"/>
  <documentation value="[string]"/>
  <event>

   <category value="[code]"/>
   <mode value="[code]"/>
   <focus value="[code]"/>
   <request></request>
   <response></response>
   <documentation value="[string]"/>
  </event>
 </messaging>
 <document>
  <mode value="[code]"/>
  <documentation value="[string]"/>
  <profile></profile>
 </document>
</Conformance>

:)

error: pathspec 'etc/samples/fhir/common_module.xq' did not match any file(s) known to git


Add `a:variadic` annotation to BaseX `out:format`.

xquery version "3.0";
(:~
: BaseX Output Module functions
:
: @see http://docs.basex.org/wiki/Output_Module
:)
module namespace out = "http://basex.org/modules/out";

import module namespace a = "http://reecedunn.co.uk/xquery/annotations" at "res://reecedunn.co.uk/xquery/annotations.xqy";

declare %a:since("basex", "9.0") function out:cr() as xs:string external;
declare %a:since("basex", "7.3") function out:nl() as xs:string external;
declare %a:since("basex", "7.3") function out:tab() as xs:string external;
declare %a:since("basex", "7.3") %a:variadic("basex", "7.3", "item()") function out:format($format as xs:string, $item as item()) as xs:string external;

error: pathspec 'src/main/resources/builtin/basex.org/modules/out.xqy' did not match any file(s) known to git


XQuery for rocket date duration arithmetic

xquery version "3.1";
declare namespace ebb="http://newtfire.org";
declare variable $rocketColl := collection('/db/rocket/');
(: ebb :The user-defined function in line 6 will unpack the date components from the dateTime in this attribute using year-from-dateTime(), and a picture string that will give us the date's numerical position as the nth day in the year. We can turn that into a decimal by dividing it by 365 (since most years have 365 days). This will give us a decimal format we can use. :)
declare function ebb:dateDecimalConverter($dT as xs:dateTime)
as xs:decimal?
{
let $year := year-from-dateTime($dT) ! xs:integer(.)
let $dayInYear := format-dateTime($dT, '[d]') ! xs:integer(.)
let $decimalDay := $dayInYear div 365
return $year + $decimalDay
};
(: ebb: The next user-defined function will convert the xs:duration datatype into a decimal value based on number of days.
 : So if we input a duration indicating 1 day, 6 hours, and 0 minutes, we should return 1.25 from this function.
 : Here's what we're calculating: There are 24 hours in a day. (Divide the H portion by 24) and add it to the days.
 : There are 60 minutes in an hour. (Divide the M portion by 60 * 24) and add it to hours.
 : There are 60 seconds in a minute (Divide the S portion by 60 * 60 * 24) and add it to minutes and hours
 : :)
declare function ebb:durationConverter($d as xs:integer, $h as xs:integer, $m as xs:integer, $s as xs:integer?)
as xs:decimal?
{
let $TDec := $h div 24 + $m div (60 * 24) + $s div (60 * 60 * 24)
return $d + $TDec
};

let $launchDateTimes := $rocketColl//launch/@sDateTime
for $l in $launchDateTimes
(: To do date arithmetic, take a look at these functions: https://www.w3.org/TR/xpath-functions-31/#dates-times
 : We'll write a user-defined function to convert this datatype into a decimal notation. :)
let $lDec := ebb:dateDecimalConverter($l)
let $m := $rocketColl//launch[@sDateTime = $l]/preceding-sibling::sts
let $mID := $m  ! tokenize(., ':')[1]

let $duration := $m/following-sibling::duration/@time
(: ebb: To do duration arithmetic, start by looking at the functions here: https://www.w3.org/TR/xpath-functions-31/#durations
 : Let's try representing durations in terms of days with a decimal. We'll write a user-defined function to convert hours, minutes, and seconds into a fraction of the day. :)
let $durDays := days-from-duration($duration)
let $durHours := hours-from-duration($duration)
let $durMins := minutes-from-duration($duration)
let $durSecs := seconds-from-duration($duration)
(: Now in line 43, we send our variables to our user-defined function for turning date datatypes into decimal values. :)
let $durDayDec := ebb:durationConverter($durDays, $durHours, $durMins, $durSecs)

order by $lDec
return concat('Launch Date: ', $l, ', mission: ', $mID, ': This Launch Decimal Date: ', $lDec, ': Duration: ', $duration, ': Decimal Notation:', $durDayDec)

error: pathspec 'Class-Examples/XQuery/rocket-date-duration-survey.xql' did not match any file(s) known to git


Add BaseX Request Module function signatures.

xquery version "3.0";
(:~
: BaseX Request Module functions
:
: @see http://docs.basex.org/wiki/Request_Module
:
:)
module namespace request = "http://exquery.org/ns/request";

import module namespace a = "http://reecedunn.co.uk/xquery/annotations" at "res://reecedunn.co.uk/xquery/annotations.xqy";

declare %a:since("basex", "7.5") function request:method() as xs:string external;
declare %a:since("basex", "7.7") function request:attribute($name as xs:string) as xs:string external;
declare %a:since("basex", "7.5") function request:scheme() as xs:string external;
declare %a:since("basex", "7.5") function request:hostname() as xs:string external;
declare %a:since("basex", "7.5") function request:port() as xs:integer external;
declare %a:since("basex", "7.5") function request:path() as xs:string external;
declare %a:since("basex", "7.5") function request:query() as xs:string? external;
declare %a:since("basex", "7.5") function request:uri() as xs:anyURI external;
declare %a:since("basex", "7.8") function request:context-path() as xs:string external;
declare %a:since("basex", "7.5") function request:address() as xs:string external;
declare %a:since("basex", "7.5") function request:remote-hostname() as xs:string external;
declare %a:since("basex", "7.5") function request:remote-address() as xs:string external;
declare %a:since("basex", "7.5") function request:remote-port() as xs:string external;
declare %a:since("basex", "7.5") function request:parameter-names() as xs:string* external;
declare %a:since("basex", "7.5") function request:parameter($name as xs:string) as xs:string* external;
declare %a:since("basex", "7.5") function request:parameter($name as xs:string, $default as xs:string) as xs:string* external;
declare %a:since("basex", "7.5") function request:header-names() as xs:string* external;
declare %a:since("basex", "7.5") function request:header($name as xs:string) as xs:string? external;
declare %a:since("basex", "7.5") function request:header($name as xs:string, $default as xs:string) as xs:string external;
declare %a:since("basex", "7.5") function request:cookie-names() as xs:string* external;
declare %a:since("basex", "7.5") function request:cookie($name as xs:string) as xs:string* external;
declare %a:since("basex", "7.5") function request:cookie($name as xs:string, $default as xs:string) as xs:string external;

error: pathspec 'src/main/resources/builtin/exquery.org/ns/request.xqy' did not match any file(s) known to git


Add BaseX Repository Module function signatures.

xquery version "3.0";
(:~
: BaseX Repository Module functions
:
: @see http://docs.basex.org/wiki/Repository_Module
:)
module namespace repo = "http://basex.org/modules/repo";

import module namespace a = "http://reecedunn.co.uk/xquery/annotations" at "res://reecedunn.co.uk/xquery/annotations.xqy";

declare %a:since("basex", "7.1") function repo:install($path as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.1") function repo:delete($pkg as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.1") function repo:list() as element(package)* (: [7.1] as xs:string [7.2] as element(package)* :) external;

error: pathspec 'src/main/resources/builtin/basex.org/modules/repo.xqy' did not match any file(s) known to git


Simplify function.

Simplify function.

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/julen/tzos.git/'


Start BaseX File Module signatures

Start BaseX File Module signatures

xquery version "3.0";
(:~
: BaseX File Module functions
:
: @see http://docs.basex.org/wiki/File_Module
:)
module namespace file = "http://expath.org/ns/file";

import module namespace a = "http://reecedunn.co.uk/xquery/annotations" at "res://reecedunn.co.uk/xquery/annotations.xqy";

declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";

declare %a:since("basex", "7.8") function file:list($dir as xs:string) as xs:string external;
declare %a:since("basex", "7.8") function file:list($dir as xs:string, $recursive as xs:boolean) as xs:string external;
declare %a:since("basex", "7.8") function file:list($dir as xs:string, $recursive as xs:boolean, $pattern as xs:string) as xs:string external;
declare %a:since("basex", "7.8") function file:children($dir as xs:string) as xs:string* external;
declare %a:since("basex", "7.8") function file:read-binary($path as xs:string) as xs:base64Binary external;
declare %a:since("basex", "7.8") function file:read-binary($path as xs:string, $offset as xs:integer) as xs:base64Binary external;
declare %a:since("basex", "7.8") function file:read-binary($path as xs:string, $offset as xs:integer, $length as xs:integer) as xs:base64Binary external;
declare %a:since("basex", "7.8") function file:read-text($path as xs:string) as xs:string external;
declare %a:since("basex", "7.8") function file:read-text($path as xs:string, $encoding as xs:string) as xs:string external;
declare %a:since("basex", "7.8") function file:read-text($path as xs:string, $encoding as xs:string, $fallback as xs:boolean) as xs:string external;
declare %a:since("basex", "7.8") function file:read-text-lines($path as xs:string) as xs:string external;
declare %a:since("basex", "7.8") function file:read-text-lines($path as xs:string, $encoding as xs:string) as xs:string* external;
declare %a:since("basex", "7.8") function file:read-text-lines($path as xs:string, $encoding as xs:string, $fallback as xs:boolean) as xs:string* external;
declare %a:since("basex", "7.8") function file:read-text-lines($path as xs:string, $encoding as xs:string, $fallback as xs:boolean, $offset as xs:integer) as xs:string* external;
declare %a:since("basex", "7.8") function file:read-text-lines($path as xs:string, $encoding as xs:string, $fallback as xs:boolean, $offset as xs:integer, $length as xs:integer) as xs:string* external;
declare %a:since("basex", "7.8") function file:create-dir($dir as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8") function file:create-temp-dir($prefix as xs:string, $suffix as xs:string) as xs:string external;
declare %a:since("basex", "7.8") function file:create-temp-dir($prefix as xs:string, $suffix as xs:string, $dir as xs:string) as xs:string external;
declare %a:since("basex", "7.8") function file:create-temp-file($prefix as xs:string, $suffix as xs:string) as xs:string external;
declare %a:since("basex", "7.8") function file:create-temp-file($prefix as xs:string, $suffix as xs:string, $dir as xs:string) as xs:string external;
declare %a:since("basex", "7.8") function file:delete($path as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8") function file:delete($path as xs:string, $recursive as xs:boolean) as empty-sequence() external;
declare %a:since("basex", "7.8") function file:write($path as xs:string, $items as item()*) as empty-sequence() external;
declare %a:since("basex", "7.8") function file:write($path as xs:string, $items as item()*, $params as item()) as empty-sequence() external;
declare %a:since("basex", "7.8") function file:write-binary($path as xs:string, $value as xs:anyAtomicType) as empty-sequence() external;
declare %a:since("basex", "7.8") function file:write-binary($path as xs:string, $value as xs:anyAtomicType, $offset as xs:integer) as empty-sequence() external;
declare %a:since("basex", "7.8") function file:write-text($path as xs:string, $value as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8") function file:write-text($path as xs:string, $value as xs:string, $encoding as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8") function file:write-text-lines($path as xs:string, $values as xs:string*) as empty-sequence() external;
declare %a:since("basex", "7.8") function file:write-text-lines($path as xs:string, $values as xs:string*, $encoding as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8") function file:append($path as xs:string, $items as item()*) as empty-sequence() external;
declare %a:since("basex", "7.8") function file:append($path as xs:string, $items as item()*, $params as item()) as empty-sequence() external;
declare %a:since("basex", "7.8") function file:append-binary($path as xs:string, $value as xs:anyAtomicType) as empty-sequence() external;
declare %a:since("basex", "7.8") function file:append-text($path as xs:string, $value as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8") function file:append-text($path as xs:string, $value as xs:string, $encoding as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8") function file:append-text-lines($path as xs:string, $values as xs:string*) as empty-sequence() external;
declare %a:since("basex", "7.8") function file:append-text-lines($path as xs:string, $values as xs:string*, $encoding as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8") function file:copy($source as xs:string, $target as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8") function file:move($source as xs:string, $target as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8") function file:exists($path as xs:string) as xs:boolean external;
declare %a:since("basex", "7.8") function file:is-dir($path as xs:string) as xs:boolean external;
declare %a:since("basex", "7.8") function file:is-absolute($path as xs:string) as xs:boolean external;
declare %a:since("basex", "7.8") function file:is-file($path as xs:string) as xs:boolean external;
declare %a:since("basex", "7.8") function file:last-modified($path as xs:string) as xs:dateTime external;
declare %a:since("basex", "7.8") function file:size($file as xs:string) as xs:integer external;
declare %a:since("basex", "7.8") function file:name($path as xs:string) as xs:string external;
declare %a:since("basex", "7.8") function file:parent($path as xs:string) as xs:string? external;
declare %a:since("basex", "7.8") function file:path-to-native($path as xs:string) as xs:string external;
declare %a:since("basex", "7.8") function file:resolve-path($path as xs:string) as xs:string external;
declare %a:since("basex", "7.8") function file:resolve-path($path as xs:string, $base as xs:string) as xs:string external;
declare %a:since("basex", "7.8") function file:path-to-uri($path as xs:string) as xs:string external;
declare %a:since("basex", "7.8") function file:dir-separator() as xs:string external;
declare %a:since("basex", "7.8") function file:path-separator() as xs:string external;
declare %a:since("basex", "7.8") function file:line-separator() as xs:string external;
declare %a:since("basex", "7.8") function file:temp-dir() as xs:string external;
declare %a:since("basex", "7.8") function file:current-dir() as xs:string external;
declare %a:since("basex", "7.8") function file:base-dir() as xs:string? external;

error: pathspec 'src/main/resources/builtin/basex/modules/file.xqy' did not match any file(s) known to git


Address admin module for #54

Address admin module for #54

xquery version "3.0";
(:~
:  BaseX admin module functions
:
: @see http://docs.basex.org/wiki/Admin_Module
:)
module namespace admin = "http://basex.org/modules/admin";

import module namespace a = "http://reecedunn.co.uk/xquery/annotations" at "res://reecedunn.co.uk/xquery/annotations.xqy";

declare %a:since("basex", "9.0") function admin:sessions() as element(session)* external;
declare %a:since("basex", "9.0") function admin:logs() as element(file)* external;
declare %a:since("basex", "9.0") function admin:logs($date as xs:string) as element(entry)* external;
declare %a:since("basex", "9.0") function admin:logs($date as xs:string, $merge as xs:boolean) as element(entry)* external;
declare %a:since("basex", "9.0") function admin:write-log($text as xs:string) as empty-sequence() external;
declare %a:since("basex", "9.0") function admin:write-log($text as xs:string, $type as xs:string) as empty-sequence() external;
declare %a:since("basex", "9.0") function admin:delete-logs($date as xs:string) as empty-sequence() external;

error: pathspec 'src/main/resources/builtin/basex.org/9.0/admin.xqy' did not match any file(s) known to git


Added a report that lists all of the code-table names for a given tab.  Just pass this script a tab-id URL parameter such as:

http://localhost:8080/exist/rest/db/org/library/apps/mods/analysis/code-names-for-tab.xq?tab-id=name

Useful for debugging problems related to tab-sepcific code tables.

- Dan

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

xquery version "1.0";
import module namespace style = "http://exist-db.org/mods-style" at "../../../modules/style.xqm";
declare namespace xf = "http://www.w3.org/2002/xforms";
declare option exist:serialize "method=xml media-type=text/xml indent=yes";

(: code-names-for-tab.xq
   This Query takes an input URL parameter of a tab id and returns just the names of all
   the code tables references by that tab.  Used mostly for debugging and consistency checks.

   Created for the MODS form.

   It calculates which tabs are needed by looking through the XForms body files
   in the edit/body collection of the mods editor.

   Input parameter: the tab ID
   Output: a list of all the code table names used by the tab
   Output format: XML

   Author: Dan McCreary
   Date: October. 2010

   :)

let $tab-id := request:get-parameter('tab-id', '')
let $debug := xs:boolean(request:get-parameter('debug', 'false'))

(: TODO check for required tab-id parameter and make sure that the tab is a valid tab ID
let $check-tab := if ( string-length($tab-id) < 1 )
  then
        <error>
           <message>Tab ID is a required parameter.</message>
        </error>
else
:)

let $code-table-collection := concat($style:web-path-to-app, '/code-tables/')
let $xforms-body-collection := concat($style:web-path-to-app, '/edit/body')
let $itemsets := collection($xforms-body-collection)/*[@tab-id=$tab-id]//xf:itemset
let $code-table-names :=
   for $itemset in $itemsets
      let $nodeset := string($itemset/@nodeset)
      let $after := substring-after($nodeset, "code-table-name='")
      let $code-table-name := substring-before($after, "']/items/item")
      order by $code-table-name
      return $code-table-name
let $distinct-code-table-names := distinct-values($code-table-names)
let $itemset-count := count($itemsets)
let $count-distinct := count($distinct-code-table-names)

return
<code-table-names>
   <tab-id>{$tab-id}</tab-id>
   { if ($debug)
     then
     <debug>
       <code-table-collection>{$code-table-collection}</code-table-collection>
       <xforms-body-collection>{$xforms-body-collection}</xforms-body-collection>
       <tab-id>{$tab-id}</tab-id>
       <itemset-count>{$itemset-count}</itemset-count>
       <code-table-name-count>{$count-distinct}</code-table-name-count>
       <distinct-code-table-names>{$distinct-code-table-names}</distinct-code-table-names>
     </debug>
     else ()
   }

   {for $code-table-name in $distinct-code-table-names

      return
            <code-table-name>{$code-table-name}</code-table-name>
   }
</code-table-names>

error: pathspec 'webapp/biblio/mods/apps/mods/analysis/code-names-for-tab.xq' did not match any file(s) known to git


Add new tests

Add new tests

xquery version "3.1";

module namespace test = 'http://xokomola.com/xquery/origami/tests';

import module namespace o = 'http://xokomola.com/xquery/origami'
    at '../origami.xqm';

declare %unit:test function test:node-extractors()
{
    unit:assert-equals(
        o:xml(o:transform(

<x y="10"/>
<x y="20"/>

,
            ['x[@y]']
        )),
        (<x y="10"/>,<x y="20"/>),
        "Using simple XPath expression"
    ),

    unit:assert-equals(
        o:xml(o:transform(

<x y="10"/>
<x y="20"/>

,
            ['//x[@y]']
        )),
        (<x y="10"/>,<x y="20"/>),
        "Using descendant axis"
    )
};

declare %unit:test function test:node-annotation()
{
    unit:assert-equals(
        o:xml(o:apply(o:transform(

<x y="10"/>
<x y="20"/>

,
            ['/*',
                ['x[@y]',
                    function($n) {
                        $n =>
                        o:advise-attr('z',
                            if (o:attrs($n)?y < 20) then
                                'A'
                            else 'B')
                    }
                ]
            ]
        ))),

<x y="10" z="A"/>
<x y="20" z="B"/>

,
        "Add attributes using a handler (using apply)"
    )

    (: TODO: this doesn't work (by-design?) :)
    (:,

    unit:assert-equals(
        o:xml(o:apply(o:transform(

<x y="10"/>
<x y="20"/>

,
            (
                ['/*']
                ['//x[@y]',
                    function($n) {
                        $n =>
                        o:advise-attr('z',
                            if (o:attrs($n)?y < 20) then
                                'A'
                            else 'B')
                    }
                ]
            )
        ))),

<x y="10" z="A"/>
<x y="20" z="B"/>

,
        "Add attributes using a handler (using apply)"
    )
    :)
};

error: pathspec 'test/test-transformers.xqm' did not match any file(s) known to git


adding input

adding input

xquery version "1.0-ml";

module namespace runFlow = "http://marklogic.com/rest-api/transform/run-flow";

import module namespace flow = "http://marklogic.com/data-hub/flow-lib"
at "/com.marklogic.hub/lib/flow-lib.xqy";

declare function runFlow:transform(
  $context as map:map,
  $params as map:map,
  $content as document-node()
  ) as document-node()
{
  let $entityName := map:get($params, 'entity-name')
  let $flowName := map:get($params, 'flow-name')

  let $flow := flow:get-flow($entityName,$flowName, "input")

  let $uri := map:get($context, 'uri')

  let $transformedContent := flow:run-plugins($flow, $uri, $content, $params)

  return document { $transformedContent }

};

xquery version "1.0-ml";

module namespace runFlow = "http://marklogic.com/rest-api/transform/run-flow";

import module namespace flow = "http://marklogic.com/data-hub/flow-lib"
at "/com.marklogic.hub/lib/flow-lib.xqy";

declare function runFlow:transform(
  $context as map:map,
  $params as map:map,
  $content as document-node()
  ) as document-node()
{
  let $entityName := map:get($params, 'entity-name')
  let $flowName := map:get($params, 'flow-name')

  let $flow := flow:get-flow($entityName,$flowName,())

  let $uri := map:get($context, 'uri')

  let $transformedContent := flow:run-plugins($flow, $uri, $content, $params)

  return document { $transformedContent }

};


Adding FHIR Location Resource as a service directory

module namespace page = 'http://basex.org/modules/web-page';
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace functx = 'http://www.functx.com';
import module namespace csr_proc = "https://github.com/openhie/openinfoman/csr_proc";
import module namespace csd_webui =  "https://github.com/openhie/openinfoman/csd_webui";
import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";
declare namespace fhir = "http://hl7.org/fhir";
declare namespace csd =  "urn:ihe:iti:csd:2013";
declare default element  namespace   "urn:ihe:iti:csd:2013";

declare function page:get_location ($doc_name,$_id,$page,$_count,$_since)
{
  <CSD xmlns:csd="urn:ihe:iti:csd:2013"  >
    {
      let $search_collection :=
      <collection>
        <search directory="facilityDirectory">urn:ihe:iti:csd:2014:stored-function:facility-search</search>
        <search directory="organizationDirectory">urn:ihe:iti:csd:2014:stored-function:organization-search</search>
      </collection>
      for $search in $search_collection/search
      let $search_name := $search/text()
      return
      (
        let $careServicesSubRequest :=
        <csd:careServicesRequest>
          <csd:function urn="{$search_name}" resource="{$doc_name}" base_url="{csd_webui:generateURL('')}">
            <csd:requestParams>
              {
                let $id := $_id
                return if (functx:all-whitespace($id)) then () else <csd:id entityID="{$id}"/>
              }

              {
                let $t_start := $page
                return if (functx:is-a-number($t_start))
                  then
                    let $start := max((xs:int($t_start),1))
                    let $t_count := $_count
                    let $count := if(functx:is-a-number($t_count)) then  max((xs:int($t_count),1)) else 50
                    let $startIndex := ($start - 1)*$count + 1
                    return <csd:start>{$startIndex}</csd:start>
                  else ()
              }
         {
           let $count := $_count
           return
              if(functx:is-a-number($count))
              then  <csd:max>{max((xs:int($count),1))} </csd:max>
              else ()
         }
         {
          let $since := $_since
          return if (functx:all-whitespace($since)) then () else <csd:record updated="{$since}"/>
         }
            </csd:requestParams>
          </csd:function>
        </csd:careServicesRequest>

        let $doc :=  csd_dm:open_document($doc_name)
        let $contents := csr_proc:process_CSR_stored_results( $doc , $careServicesSubRequest)
        let $directory := $search/@directory/string()
        return $contents/*[name() = $directory]
      )
    }
  </CSD>
};

declare
  %rest:path("/FHIR/Location/_history/{$id}")
  %rest:query-param("page", "{$page}")
  %rest:query-param("_count", "{$_count}")
  %rest:query-param("_since", "{$_since}")
  %rest:query-param("doc_name", "{$doc_name}")
  %rest:GET
  function page:FHIRID($id,$page,$_count,$_since,$doc_name)
{
  page:FHIR($id,$page,$_count,$_since,$doc_name)
};

declare
  %rest:path("/FHIR/Location/_history")
  %rest:query-param("_id", "{$_id}")
  %rest:query-param("page", "{$page}")
  %rest:query-param("_count", "{$_count}")
  %rest:query-param("_since", "{$_since}")
  %rest:query-param("doc_name", "{$doc_name}")
  %rest:GET
  function page:FHIR($_id,$page,$_count,$_since,$doc_name)
{
let $contents := page:get_location ($doc_name,$_id,$page,$_count,$_since)

let $location :=
<json type='object'>
<resourceType>Bundle</resourceType>
<total>{count($contents/facilityDirectory/facility) + count($contents/organizationDirectory/organization)}</total>
<type>history</type>
<entry type="array">
{
for $content in ($contents/facilityDirectory/facility,$contents/organizationDirectory/organization)
return
<_ type="object">
{
  <fullURL>{csd_webui:generateURL('FHIR/Location/_history/' || $content/@entityID)}?doc_name={$doc_name}</fullURL>,
  <resource type="object">
    <resourceType>Location</resourceType>
    <id>{$content/@entityID/string()}</id>
    {
     if(exists($content/otherID))
     then
     <identifier type="array">
      {
      for $otherid in $content/otherID
      return
      <_ type="object">
        <system>{$otherid/@assigningAuthorityName/string()}/{$otherid/@code/string()}</system>
        <value>{$otherid/text()}</value>
      </_>
      }
     </identifier>
     else ()
    }
    {
      let $search_name := "urn:ihe:iti:csd:2014:stored-function:organization-search"
      let $parent :=
      if(exists($content/organizations/organization))
      then
      $content/organizations/organization/@entityID/string()
      else
      if (exists($content/parent))
      then $content/parent/@entityID/string()
      else ()

      return if($parent)
      then
      let $careServicesSubRequest :=
      <csd:careServicesRequest>
        <csd:function urn="{$search_name}" resource="{$doc_name}" base_url="{csd_webui:generateURL()}">
          <csd:requestParams>
            <csd:id entityID="{$parent}"/>
          </csd:requestParams>
        </csd:function>
      </csd:careServicesRequest>
      let $doc :=  csd_dm:open_document($doc_name)
      let $organization := csr_proc:process_CSR_stored_results( $doc , $careServicesSubRequest)
      return if(exists($organization/organizationDirectory/organization))
      then
      <partOf type="object">
        <reference>{csd_webui:generateURL('FHIR/Location/_history/' || $organization/organizationDirectory/organization/@entityID/string())}?doc_name={$doc_name}</reference>
        <display>{$organization/organizationDirectory/organization/primaryName/text()}</display>
      </partOf>
      else ()
      else ()
    }
    {
    if(exists($content/contactPoint))
    then
    <telecom type="array">
     {
     for $contactPoint in $content/contactPoint
     return ()
     }
    </telecom>
    else ()
    }
    {
      if(exists($content/geocode))
      then
      <position type="object">
        <longitude>{$content/geocode/longitude/text()}</longitude>
        <latitude>{$content/geocode/latitude/text()}</latitude>
      </position>
      else ()
    }
    <meta type="object">
     <lastUpdated>{$content/record/@updated/string()}</lastUpdated>
    <tag type="array">
      <_ type="object">
        {$content/record/@sourceDirectory/string()}
        <system>https://github.com/openhie/openinfoman/tags/fhir/sourceDirectory</system>
      </_>
    </tag>
    </meta>
    {
      if(exists($content/codedType))
      then
        <type type="object">
          <coding type="array">
            {
              for $codedType in $content/codedType
                return
                <_ type="object">
                  {$codedType/@code/string()}
                  <system>{$codedType/@codingScheme/string()}</system>
                  {
                  if(functx:all-whitespace($codedType/text()))
                  then ()
                  else
                  <display>{$codedType/text()}</display>
                  }
                </_>
            }
          </coding>
        </type>
      else ()
    }
  </resource>,
  <status>{$content/record/@status/string()}</status>,
  <name>{$content/primaryName/text()}</name>,
  <mode>instance</mode>
}
</_>
}
</entry>
</json>

return (
  <rest:response>
    <output:serialization-parameters>
      <output:media-type value='application/json'/>
    </output:serialization-parameters>
  </rest:response>,
  json:serialize($location,map{"format":"direct",'escape': 'no'})
  )

};

declare
  %rest:path("/test")
  %rest:query-param("_id", "{$_id}")
  %rest:query-param("page", "{$page}")
  %rest:query-param("_count", "{$_count}")
  %rest:query-param("_since", "{$_since}")
  %rest:query-param("doc_name", "{$doc_name}")
  %rest:GET
  function page:test($_id,$page,$_count,$_since,$doc_name)
{
let $contents := page:get_location ($doc_name,$_id,$page,$_count,$_since)
return $contents/organizationDirectory/organization
};

error: pathspec 'webapp/fhir.xqm' did not match any file(s) known to git


Experiment reading headers

Experiment reading headers

import module namespace notes="http://cefn.com/readinglog/notes" at "/home/cefn/Documents/highwire/participatory firmware design/readinglog/scripts/server/xquery/lib/notes.xq";
import module namespace template="http://cefn.com/readinglog/template" at "/home/cefn/Documents/highwire/participatory firmware design/readinglog/scripts/server/xquery/lib/template.xq";
declare default element namespace "http://www.w3.org/1999/xhtml";

let $headers := notes:allnotes()//h2[contains(text(),"Authors")],
	$headertexts := $headers/text()
return template:webpage(

		{
			for $result in distinct-values($headertexts) return

{$result}

{count($headers[text()=$result])}

		}

)

error: pathspec 'scripts/server/xquery/headerreport.xq' did not match any file(s) known to git


xqy setup

xqy setup

(: forest :)
xquery version "1.0-ml";
import module namespace admin = "http://marklogic.com/xdmp/admin" at "/MarkLogic/admin.xqy";
let $config := admin:get-configuration()
let $config := admin:forest-create(
  $config,
  "outdoor-explorer-01",
  xdmp:host(),
  ())
return admin:save-configuration($config);

(: database :)
xquery version "1.0-ml";
import module namespace admin = "http://marklogic.com/xdmp/admin" at "/MarkLogic/admin.xqy";
let $config := admin:get-configuration()
let $config := admin:database-create(
  $config,
  "outdoor-explorer",
  xdmp:database("Security"),
  xdmp:database("Schemas"))
return admin:save-configuration($config);

(: attach forest to database :)
xquery version "1.0-ml";
import module namespace admin = "http://marklogic.com/xdmp/admin" at "/MarkLogic/admin.xqy";
let $config := admin:get-configuration()
let $config := admin:database-attach-forest(
  $config,
  xdmp:database("outdoor-explorer"),
  xdmp:forest("outdoor-explorer-01"))
return admin:save-configuration($config);

(: application server :)
xquery version "1.0-ml";
import module namespace admin = "http://marklogic.com/xdmp/admin" at "/MarkLogic/admin.xqy";
let $config := admin:get-configuration()
let $groupid := admin:group-get-id($config, "Default")
let $server := admin:http-server-create(
  $config,
  $groupid,
  "8050-outdoor-explorer",
  "C:\Users\ivana.frankic\workspace\projects\outdoor-explorer",
  8050,
  0,
  admin:database-get-id($config, "outdoor-explorer"))
return admin:save-configuration($server);

(: Create XDBC application server for loading data with mlcp :)
xquery version "1.0-ml";
import module namespace admin = "http://marklogic.com/xdmp/admin" at "/MarkLogic/admin.xqy";
let $config := admin:get-configuration()
let $groupid := admin:group-get-id($config, "Default")
let $server := admin:xdbc-server-create(
    $config,
    $groupid,
    "outdoor-explorer-XDBC",
    "/",
    8056,
    0,
    admin:database-get-id($config, "outdoor-explorer"))
return admin:save-configuration($server);

error: pathspec 'forest_db_appserver.xqy' did not match any file(s) known to git


Transforms for bitemporal

Transforms for bitemporal

xquery version "1.0-ml";
module namespace example =
  "http://marklogic.com/rest-api/transform/add-element-xquery-transform";

declare function example:transform(
  $context as map:map,
  $params as map:map,
  $content as document-node()
) as document-node()
{
   if (fn:empty($content/*)) then $content
  else (
    let $value := (map:get($params,"value"),"UNDEFINED")[1]
    let $name := (map:get($params, "name"), "transformed")[1]
    let $root  := $content/*
    let $element-name := "new-element"
    let $element-value := "2007-12-31T11:59:59"
    return
    (
    document {
      $root/preceding-sibling::node(),
      element {fn:name($root)} {
        attribute { fn:QName("", $name) } {$value},
	element {$element-name} {$element-value},
        $root/@*,
        $root/node()
      },
      $root/following-sibling::node()
    },
    xdmp:log(fn:concat($name,"-",$value))
    )
    )
};

error: pathspec 'test-complete/src/test/java/com/marklogic/javaclient/transforms/add-element-xquery-transform.xqy' did not match any file(s) known to git


for job density reports

for job density reports

xquery version "1.0";
module namespace density = "http://density.tlos.com/";

import module namespace hs="http://hs.tlos.com/" at "xmldb:exist://db/TLOSSW/modules/moduleReportOperations.xquery";
declare namespace rep="http://www.likyateknoloji.com/XML_report_types";
declare namespace dat="http://www.likyateknoloji.com/XML_data_types";
declare namespace stat="http://www.likyateknoloji.com/state-types";
declare namespace state-types="http://www.likyateknoloji.com/state-types";

(:
Programmed by : Hakan Saribiyik
Version : 0.1
First Release Date : 6 May 2013
UpdateDate :
Purpose : Job state density reporting.
Usage :

 recStat( status, substatus, state, reportDateA, reportDateB, step)

example;
let $startDateTime := xs:dateTime("2013-05-05T15:42:00+03:00")
let $endDateTime   := xs:dateTime("2013-05-05T15:59:00+03:00")

return  density:recStat(xs:string("RUNNING"), xs:string("ON-RESOURCE"), xs:string("TIME-IN") , $startDateTime, $endDateTime, xs:dayTimeDuration('PT60S'))

:)

declare function density:stringToDateTime($t1 as xs:string) as xs:dateTime
{
    (: Degisik tarih formatlari icin dusunuldu. 2011-10-13T15:08:31+0300 veya 2011-10-13T15:08:31.91+0300 veya 2011-10-13T15:08:31.897+0300 :)
    let $uzunluk := string-length($t1)
    let $baslangic := if($uzunluk eq 24) then 19 else if($uzunluk eq 27) then 22 else if($uzunluk eq 28) then 23 else ()

    let $t2 := substring($t1, 1, $baslangic)
    let $t3 := substring($t1, $baslangic+2, 2)
    let $t7 := concat($t2, '+', $t3, ':00')
    let $t8 := xs:dateTime($t7)

    return $t8
};

(:
let $startDateTime := xs:dateTime("2013-05-04T16:15:00+03:00")
let $endDateTime   := xs:dateTime("2013-06-01T00:00:00+03:00")
let $stateName := xs:string("FINISHED")
let $substateName := xs:string("COMPLETED")
let $statusName := xs:string("SUCCESS")
:)
declare function density:focusedRecords($startDateTime as xs:dateTime, $endDateTime as xs:dateTime) as node()
{

let $getJobs := hs:getJobsReport(1,0,0, true())

  let $sonuc :=
              for $jobProperties in $getJobs/dat:jobProperties
              let $liveStateInfos := $jobProperties/dat:stateInfos/state-types:LiveStateInfos
              let $liveStateInfosSorted := <state-types:LiveStateInfos> {
                                       for $item in $liveStateInfos/state-types:LiveStateInfo
                                       let $lSIDateTime := density:stringToDateTime($item/@LSIDateTime)
                                       order by $lSIDateTime ascending
                                       return $item
              }</state-types:LiveStateInfos>
              let $fish :=  <group agentId="{$jobProperties/@agentId}" ID="{$jobProperties/@ID}" LSIDateTime="{$jobProperties/@LSIDateTime}"> {
                                     for $liveStateInfo in $liveStateInfosSorted/state-types:LiveStateInfo
                                     let $lSIDateTime := density:stringToDateTime($liveStateInfo/@LSIDateTime)
                                     let $lSIDateTimeNext := $liveStateInfo/following-sibling::state-types:LiveStateInfo[1]/@LSIDateTime
                                     let $lSIDateTimeNextValue := if(exists($lSIDateTimeNext)) then density:stringToDateTime($lSIDateTimeNext) else $lSIDateTime
                                     where
                                       (($startDateTime < $lSIDateTime) and ( $endDateTime > $lSIDateTime )) or
                                       (($startDateTime > $lSIDateTime) and (exists($lSIDateTimeNext) and $startDateTime < $lSIDateTimeNextValue))
                                     return <state-types:LiveStateInfo LSIDateTime="{$lSIDateTime}" LSIDateTimeEnd="{$lSIDateTimeNextValue}">
                                              { $liveStateInfo/* }
                                            </state-types:LiveStateInfo>
                                    } </group>

              return  $fish

  return <focused>{ $sonuc } </focused>
} ;

declare function density:SSSInterval($startDateTime as xs:dateTime, $endDateTime as xs:dateTime) as node()
{
let $focused := density:focusedRecords($startDateTime, $endDateTime)

let $tektek :=
  let $sonuc := for $liveStateInfo in $focused/group

               return $liveStateInfo

  return <statistic sDTime="{$startDateTime}" eDTime="{$endDateTime}"> { $sonuc } </statistic>
return $tektek

} ;

declare function density:calcStat($stateName as xs:string, $substateName as xs:string, $statusName as xs:string, $startDateTime as xs:dateTime, $endDateTime as xs:dateTime) as node()
{
let $focused := density:SSSInterval($startDateTime, $endDateTime)

let $tektek :=
  let $sonuc := for $liveStateInfos in $focused/group
                 let $lsi :=
                    for $liveStateInfo in $liveStateInfos/state-types:LiveStateInfo
                    let $lSIDateTime := $liveStateInfo/@LSIDateTime
                    let $lSIDateTimeEnd := $liveStateInfo/@LSIDateTimeEnd
                    let $rightState := if(compare($stateName, $liveStateInfo/state-types:StateName/text()) eq 0) then true() else false()
                    let $rightSubstate := if(compare($substateName, $liveStateInfo/state-types:SubstateName/text()) eq 0) then true() else false()
                    let $rightStatus := if(compare($statusName, $liveStateInfo/state-types:StatusName/text()) eq 0) then true() else false()
                    where (
                            (($startDateTime < $lSIDateTime) and ( $endDateTime > $lSIDateTime )) or
                            (($startDateTime > $lSIDateTime) and ($startDateTime < $lSIDateTimeEnd))
                           )
                           and $rightState and $rightSubstate and $rightStatus
                    return $liveStateInfo

              return if(exists($lsi)) then <group agentId="{$liveStateInfos/@agentId}" ID="{$liveStateInfos/@ID}" LSIDateTime="{$lsi/@LSIDateTime}" LSIDateTimeEnd="{$lsi/@LSIDateTimeEnd}"/>
                     else ()

  return <statistic sDTime="{$startDateTime}" eDTime="{$endDateTime}" count="{count($sonuc)}"> { $sonuc } </statistic>
return $tektek

} ;

declare function density:recStat($stateName as xs:string, $substateName as xs:string, $statusName as xs:string, $startDateTime as xs:dateTime, $endDateTime as xs:dateTime, $step as xs:dayTimeDuration) as node()
{
  if($endDateTime > $startDateTime) then
    let $diff := $endDateTime - $startDateTime
    let $numberOfInterval := xs:integer($diff div $step)
    let $sonuc :=
      let $seq := 1 to $numberOfInterval
      for $n in $seq
       let $kac := xs:integer($n)-1
       let $startDTime := $startDateTime+ $kac*$step
       let $endDTime := $startDateTime+ $n*$step
       let $fonk := density:calcStat($stateName, $substateName, $statusName, $startDTime, $endDTime)
      return $fonk
    return <statistics> { $sonuc } </statistics>
 else ()
};

(:
let $startDateTime := xs:dateTime("2013-05-05T15:42:00+03:00")
let $endDateTime   := xs:dateTime("2013-05-05T15:59:00+03:00")

return  density:recStat(xs:string("RUNNING"), xs:string("ON-RESOURCE"), xs:string("TIME-IN") , $startDateTime, $endDateTime, xs:dayTimeDuration('PT60S'))

:)
(:   density:recStat(<statistics></statistics>, $startDateTime, $endDateTime, xs:dayTimeDuration('PT60S')) :)

(: let $endDTime := $endDateTime  $startDateTime + xs:dayTimeDuration('PT30S') :)
(: let $sonson := density:recStat(<statistics></statistics>, $startDateTime, $endDateTime) :)
(: return <statistics state="{xs:string("FINISHED")}" substate="{xs:string("COMPLATED")}" status="{xs:string("FAILED")}"> { $sonson/* } </statistics> :)
(:   :let $focused := density:SSSInterval($startDateTime, $endDTime):)
(:   :let $focused := density:calcStat(xs:string("RUNNING"), xs:string("ON-RESOURCE"), xs:string("TIME-IN"), $startDateTime, $endDTime) :)
(:   density:focusedRecords(xs:string("FINISHED"), xs:string("COMPLETED"), xs:string("FAILED"), $startDateTime, $endDTime) :)

error: pathspec 'TlosSW_V1.0_Schema/dbfiles/modules/moduleDensityCalculations.xquery' did not match any file(s) known to git


[testsuite] Add tests from issue #2437 which are also fixed now

xquery version "3.1";

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

declare variable $devar:static := 'I am static.';
declare variable $devar:dynamic := replace($devar:static, 'static', 'dynamic');
declare variable $devar:function := (function ($a) {
    replace($a, 'static', 'the return of a function expression')
})($devar:static);

declare variable $devar:arrow := $devar:static
=> replace('static', 'the return of an arrow expression')
;

declare
%test:assertEquals('I am static.')
function devar:read-static () {
    $devar:static
};

declare
%test:assertEquals('I am dynamic.')
function devar:read-dynamic () {
    $devar:dynamic
};

declare
%test:assertEquals('I am the return of a function expression.')
function devar:read-function () {
    $devar:function
};

declare
%test:assertEquals('I am the return of a arrow expression.')
function devar:read-arrow () {
    $devar:arrow
};

error: pathspec 'exist-core/src/test/xquery/xquery3/dynamically-declared-vars.xql' did not match any file(s) known to git


adding transform for test

adding transform for test

xquery version "1.0-ml";
module namespace example =
  "http://marklogic.com/rest-api/transform/add-attr-xquery-transform";

declare function example:transform(
  $context as map:map,
  $params as map:map,
  $content as document-node()
) as document-node()
{
   if (fn:empty($content/*)) then $content
  else (
    let $value := (map:get($params,"trans:value"),"UNDEFINED")[1]
    let $name := (map:get($params, "trans:name"), "transformed")[1]
    let $root  := $content/*
    return
    (
    document {
      $root/preceding-sibling::node(),
      element {fn:name($root)} {
        attribute { fn:QName("", $name) } {$value},
        $root/@*,
        $root/node()
      },
      $root/following-sibling::node()
    },
    xdmp:log(fn:concat($name,"-",$value))
    )
    )
};

error: pathspec 'test-complete/src/test/java/com/marklogic/javaclient/transforms/add-attr-xquery-transform.xqy' did not match any file(s) known to git


separate starting script for cr-xq in the mdrepo incarnation

xquery version "1.0";

import module namespace fcs  = "http://clarin.eu/fcs/1.0" at "fcs.xqm";

let $config := 'etc/config_mdrepo.xml'

return fcs:repo($config)

error: pathspec 'fcs/wrapper/cr-xq/mdrepo.xql' did not match any file(s) known to git


Added xq file expressing query 8 using XQuery

Web data management & xml (CSE 5335)/Programming assignment 7/Individual queries/8.xq

/bin/sh: 1: Syntax error: word unexpected (expecting ")")


adding the 'original' version of the module

module namespace cmd = "http://clarin.eu/cmd/collections";
import module namespace fcs  = "http://clarin.eu/fcs/1.0" at "xmldb:exist:///db/cr/fcs.xqm";
import module namespace repo-utils = "http://aac.ac.at/content_repository/utils" at  "xmldb:exist:///db/cr/repo-utils.xqm";

(:~
  API function getCollections.
:)
declare function cmd:get-collections($collections as xs:string+, $format as xs:string, $max-depth as xs:integer) as item() {
  let $name := repo-utils:gen-cache-id("collection", $collections, xs:string($max-depth)),
    $doc :=
    if (repo-utils:is-in-cache($name)) then
       repo-utils:get-from-cache($name)
    else
      let $data := cmd:colls($collections, $max-depth)
 	return repo-utils:store-in-cache($name, $data)
  return
    repo-utils:serialise-as($doc, $format,"scan")
};

(:
  **********************
  getCollections - subfunctions
:)
declare function cmd:colls($collections as xs:string+, $max-depth as xs:integer) as element() {
		let $children :=
	  	for $collection-item in $collections
	   		return
	   			for $collection-doc in cmd:get-resource-by-handle($collection-item)
	     			return cmd:colls-r($collection-doc, cmd:get-md-collection-name($collection-doc), $collection-doc//MdSelfLink, "", $max-depth)
		let $res-count := sum($children/@cnt)
		let $coll-count := sum($children/@cnt_subcolls) + count($children)
		let $data := <Collections cnt="{$res-count}" cnt_subcolls="{$coll-count}" cnt_children="{count($children)}" root="{$collections}">{$children}</Collections>
		return $data
};

(:
  Recurse down in collections.
:)
declare function cmd:colls-r($collection as node(), $name as xs:string, $handle as xs:string, $proxy-id as xs:string, $depth as xs:integer) as item()* {
  let $children :=  if ($depth eq 1) then () else cmd:get-children-colls($collection)
  (: let $dummy := util:log('debug', fn:concat(cmd:get-md-collection-name($collection), " ", $collection//MdSelfLink, " ", xs:string($depth), " CHILDREN = ", string-join(for $child in $children return $child//MdSelfLink, "#"))) :)
    return
      if (fn:exists($children)) then
	let $child-results :=
	  for $child in $children
	    (: let $child-doc := if (empty($child/unresolvable-uri)) then
		cmd:get-resource-by-handle($child/ResourceRef) else (), :)
            let $child-name := cmd:get-md-collection-name($child)
	    let $proxyid := ($collection//ResourceProxy[ResourceRef = $child//MdSelfLink]/@id, concat("UNKNOWN proxy id:", $child//MdSelfLink))[1]
	    return
	      cmd:colls-r($child, $child-name, $child//Header/MdSelfLink, $proxyid, $depth - 1)

	  return
	  <c n="{$name}" handle="{$handle}" proxy-id="{$proxy-id}" cnt="{sum($child-results/@cnt)}" cnt_subcolls="{if ($handle eq '') then '-1' else cmd:get-collection-count($handle)}" cnt_children="{count($child-results)}" >{$child-results}</c>
      else
      	<c n="{$name}" handle="{$handle}" proxy-id="{$proxy-id}" cnt_subcolls="{if ($handle eq '') then '-1' else cmd:get-collection-count($handle)}" cnt="{if ($handle eq '') then '-1' else cmd:get-resource-count($handle)}"></c>
};

(:
  Get the MD resource by handle.
:)
declare function cmd:get-resource-by-handle($id as xs:string) as node()* {
  let $collection := collection($cmd:dataPath)
  return
    if ($id eq "" or $id eq $cmd:collectionRoot) then
    $collection//IsPartOf[. = $cmd:collectionRoot]/ancestor::CMD
  else
    util:eval(concat("$collection/ft:query(descendant::MdSelfLink, <term>", xmldb:decode($id), "</term>)/ancestor::CMD"))
 (: $collection/descendant::MdSelfLink[. = xdb:decode($id)]/ancestor::CMD :)
};

(:
  Get the next level collection-records (ResourceType='Metadata')
  rely on the ResourceProxy of the parent (param)
:)
declare function cmd:get-children-colls($collection as node()) as node()* {
  let $handle := $collection//MdSelfLink/text(),
    $cmdi-collection := collection($cmd:dataPath)
  return util:eval(concat("$cmdi-collection/ft:query(descendant::IsPartOf, <term>", $handle, "</term>)/ancestor::CMD[descendant::ResourceType[. = 'Metadata']]"))
    (: collection($cmd:dataPath)/descendant::IsPartOf[. eq $handle]/ancestor::CMD[descendant::ResourceType[. = "Metadata"]] :)
};

(:
  count ALL (independent of maxDepth) resource-records (ie actually ResourceType=Resource, but
  there are records without ResourceProxy[ResourceType=Resource] -
  so care for that (not(exists((ResourceType))))
:)
declare function cmd:get-resource-count($handle as xs:string) as xs:string {
 (: 	xs:string(count(collection($cmd:dataPath)//IsPartOf[. eq $handle]/ancestor::CMD[descendant::ResourceType[. = "Resource"] or not(exists(descendant::ResourceType)) ])):)
	xs:string(count(collection($cmd:dataPath)//IsPartOf[. eq $handle]/ancestor::CMD[not(descendant::ResourceType eq 'Metadata') ]))
};

(:
  This is complement to cmd:get-resource-count()
  count ALL (independent of maxDepth) collection-records
  (ie ResourceType=Metadata)
:)
declare function cmd:get-collection-count($handle as xs:string) as xs:string {
	xs:string(count(collection($cmd:dataPath)//IsPartOf[. eq $handle]/ancestor::CMD[descendant::ResourceType[. = "Metadata"]]))
};

(:
  Try to derive a name from the collection-record (more-or-less agnostic about
  the actual schema.
:)
declare function cmd:get-md-collection-name($collection-doc as node()) as xs:string {
($collection-doc//Corpus/Name, $collection-doc//Session/Name, $collection-doc//Collection/GeneralInfo/Name, $collection-doc//Collection/GeneralInfo/Title, $collection-doc//Name, $collection-doc//name, $collection-doc//Title, $collection-doc//title, "UNKNOWN")[1]
};

error: pathspec 'fcs/wrapper/cr-xq/cmd-collections.xqm' did not match any file(s) known to git