add an filtered saved options to test filtered work-around in PojoFacadeTest.java

xquery version "1.0-ml";

module namespace bootstrap = "http://marklogic.com/rest-api/resource/bootstrap";
(: Copyright 2002-2010 Mark Logic Corporation.  All Rights Reserved. :)

import module namespace admin = "http://marklogic.com/xdmp/admin" at "/MarkLogic/admin.xqy";
import module namespace temporal = "http://marklogic.com/xdmp/temporal" at "/MarkLogic/temporal.xqy";

declare namespace dbx = "http://marklogic.com/xdmp/database";
declare namespace error = "http://marklogic.com/xdmp/error";

declare default function namespace "http://www.w3.org/2005/xpath-functions";
declare option xdmp:mapping "false";

declare function bootstrap:database-configure(
  $dbid as xs:unsignedLong
) as empty-sequence()
{
    let $c := admin:get-configuration()

    let $c := bootstrap:create-range-element-indexes($c, $dbid)
    let $c := bootstrap:create-element-attribute-range-indexes($c, $dbid)
    let $c := bootstrap:create-element-word-lexicons($c, $dbid)
    let $c := bootstrap:create-geospatial-element-pair-indexes($c, $dbid)
    let $c := bootstrap:create-field-range-indexes($c, $dbid)
    let $c := bootstrap:create-fields($c, $dbid)
    (: you can't create field and field range index in same transaction :)
    return admin:save-configuration-without-restart($c),

    let $c := admin:get-configuration()
    let $c := bootstrap:create-path-range-indexes($c, $dbid)
    let $c := bootstrap:create-geospatial-path-indexes($c, $dbid)
    return admin:save-configuration-without-restart($c)
};

declare function bootstrap:create-range-element-indexes(
    $c as element(configuration),
    $dbid as xs:unsignedLong
) as element(configuration)
{

    (: collection and word lexicons and triple index on :)
    let $c := admin:database-set-collection-lexicon($c, $dbid, true())
    let $c := admin:database-set-maintain-last-modified($c, $dbid, true())
    let $c := admin:database-set-triple-index($c, $dbid, true())

    let $index-specs :=
        let $curr-idx := admin:database-get-range-element-indexes($c, $dbid)
        let $new-idx  := (
            "dateTime", "http://marklogic.com/xdmp/property", "last-modified",
            "string",   "http://nwalsh.com/ns/photolib",      "tag",
            "date",     "http://nwalsh.com/ns/photolib",      "date",
            "double",   "",                                   "double",
            "int",      "",                                   "int",
            "string",   "",                                   "grandchild",
            "string",   "",                                   "string",
            "dateTime", "",                                   "system-start",
            "dateTime", "",                                   "system-end",
            "dateTime", "",                                   "valid-start",
            "dateTime", "",                                   "valid-end"
            )
        for $i in 1 to (count($new-idx) idiv 3)
        let $offset    := ($i * 3) - 2
        let $datatype  := subsequence($new-idx, $offset, 1)
        let $collation :=
            if ($datatype eq "string")
            then "http://marklogic.com/collation/"
            else ""
        let $ns        := subsequence($new-idx, $offset + 1, 1)
        let $name      := subsequence($new-idx, $offset + 2, 1)
        let $curr      := $curr-idx[
            string(dbx:scalar-type) eq $datatype and
            string(dbx:namespace-uri) eq $ns and
            tokenize(string(dbx:localname), "\s+") = $name and
            string(dbx:collation) eq $collation
            ]
        return
            if (exists($curr)) then (
                xdmp:log(concat("Element range index already exists: ", $name))
            ) else (
                admin:database-range-element-index(
                    $datatype, $ns, $name, $collation, false()
                ),
                xdmp:log(concat("Creating element range index: ", $name))
            )

    return
        if (empty($index-specs)) then $c
        else admin:database-add-range-element-index($c, $dbid, $index-specs)
};

declare function bootstrap:create-element-attribute-range-indexes(
    $c as element(configuration),
    $dbid as xs:unsignedLong
) as element(configuration)
{
    let $index-specs :=
        let $curr-idx := admin:database-get-range-element-attribute-indexes($c, $dbid)
        let $new-idx  := (
            "date", "http://nwalsh.com/ns/photolib", "view", "", "date"
            )
        for $i in 1 to (count($new-idx) idiv 5)
        let $offset    := ($i * 5) - 4
        let $datatype  := subsequence($new-idx, $offset, 1)
        let $collation :=
            if ($datatype eq "string")
            then "http://marklogic.com/collation/"
            else ""
        let $e-ns      := subsequence($new-idx, $offset + 1, 1)
        let $e-name    := subsequence($new-idx, $offset + 2, 1)
        let $a-ns      := subsequence($new-idx, $offset + 3, 1)
        let $a-name    := subsequence($new-idx, $offset + 4, 1)
        let $curr      := $curr-idx[
            string(dbx:scalar-type) eq $datatype and
            string(dbx:parent-namespace-uri) eq $e-ns and
            tokenize(string(dbx:parent-localname), "\s+") = $e-name and
            string(dbx:namespace-uri) eq $a-ns and
            tokenize(string(dbx:localname), "\s+") = $a-name and
            string(dbx:collation) eq $collation
            ]
        return
            if (exists($curr)) then (
                xdmp:log(concat("element-attribute range index already exists:[", $e-name, ",", $a-name, "]"))
            ) else (
                admin:database-range-element-attribute-index(
                    $datatype, $e-ns, $e-name, $a-ns, $a-name, $collation, false()
                ),
                xdmp:log(concat("Creating element-attribute range index:[", $e-name, ",", $a-name, "]"))
            )
    return
        if (empty($index-specs)) then $c
        else admin:database-add-range-element-attribute-index($c, $dbid, $index-specs)
};

declare function bootstrap:create-element-word-lexicons(
    $c as element(configuration),
    $dbid as xs:unsignedLong
) as element(configuration)
{
    let $index-specs :=
        let $curr-idx := admin:database-get-element-word-lexicons($c, $dbid)
        let $new-idx  := (
            "", "suggest"
            )
        for $i in 1 to (count($new-idx) idiv 2)
        let $offset    := ($i * 2) - 1
        let $collation := "http://marklogic.com/collation/"
        let $ns        := subsequence($new-idx, $offset, 1)
        let $name      := subsequence($new-idx, $offset + 1, 1)
        let $curr      := $curr-idx[
            string(dbx:namespace-uri) eq $ns and
            tokenize(string(dbx:localname), "\s+") = $name and
            string(dbx:collation) eq $collation
            ]
        return
            if (exists($curr)) then (
                xdmp:log(concat("element-word index already exists: ", $name))
            ) else (
                admin:database-element-word-lexicon($ns, $name, $collation),
                xdmp:log(concat("Creating element-word index: ", $name))
            )
    return
        if (empty($index-specs)) then $c
        else admin:database-add-element-word-lexicon($c, $dbid, $index-specs)
};

declare function bootstrap:create-geospatial-element-pair-indexes(
    $c as element(configuration),
    $dbid as xs:unsignedLong
) as element(configuration)
{
    (: create geospatial indexes for geo unit test :)
    let $index-specs :=
        let $curr-idx := admin:database-get-geospatial-element-pair-indexes($c, $dbid)
        let $p := "http://marklogic.com/ns/test/places"
        let $new-idx  := (
            $p, "place", $p, "lat", $p, "long", "wgs84"
            )
        for $i in 1 to (count($new-idx) idiv 7)
        let $offset    := ($i * 7) - 6
        let $p-ns      := subsequence($new-idx, $offset, 1)
        let $p-name    := subsequence($new-idx, $offset + 1, 1)
        let $lat-ns    := subsequence($new-idx, $offset + 2, 1)
        let $lat-name  := subsequence($new-idx, $offset + 3, 1)
        let $lon-ns    := subsequence($new-idx, $offset + 4, 1)
        let $lon-name  := subsequence($new-idx, $offset + 5, 1)
        let $coord-sys := subsequence($new-idx, $offset + 6, 1)
        let $curr      := $curr-idx[
            string(dbx:parent-namespace-uri) eq $p-ns and
            tokenize(string(dbx:parent-localname), "\s+") = $p-name and
            string(dbx:latitude-namespace-uri) eq $lat-ns and
            tokenize(string(dbx:latitude-localname), "\s+") = $lat-name and
            string(dbx:longitude-namespace-uri) eq $lon-ns and
            tokenize(string(dbx:longitude-localname), "\s+") = $lon-name and
            string(dbx:coordinate-system) eq $coord-sys
            ]
        return
            if (exists($curr)) then (
                xdmp:log(concat("Geo-elem-pair-index already exists:[", $p-name, ",", $lat-name, ",", $lon-name, "]"))
            ) else (
                admin:database-geospatial-element-pair-index(
                    $p-ns, $p-name, $lat-ns, $lat-name, $lon-ns, $lon-name, $coord-sys, false()
                ),
                xdmp:log(concat("Creating geo-elem-pair-index:[", $p-name, ",", $lat-name, ",", $lon-name, "]"))
            )
    return
        if (empty($index-specs)) then $c
        else admin:database-add-geospatial-element-pair-index($c, $dbid, $index-specs)
};

declare function bootstrap:create-fields(
    $c as element(configuration),
    $dbid as xs:unsignedLong
) as element(configuration)
{

    let $def-specs :=
        let $curr-def := admin:database-get-fields($c, $dbid)
        for $new-def in ("int1", "int2")
        let $curr := $curr-def[
            string(dbx:field-name) eq $new-def
            ]
        return
            if (exists($curr)) then (
                xdmp:log(concat("Field index already exists: ", $new-def))
            ) else (
                admin:database-field($new-def, false()),
                xdmp:log(concat("Creating field: ", $new-def))
            )
    return
        if (empty($def-specs)) then $c
        else admin:database-add-field($c, $dbid, $def-specs)
};

declare function bootstrap:create-field-range-indexes(
    $c as element(configuration),
    $dbid as xs:unsignedLong
) as element(configuration)
{
    let $index-specs :=
        let $curr-idx := admin:database-get-range-field-indexes($c, $dbid)
        let $new-idx  := (
            "int", "int1",
            "int", "int2"
            )
        for $i in 1 to (count($new-idx) idiv 2)
        let $offset    := ($i * 2) - 1
        let $datatype  := subsequence($new-idx, $offset, 1)
        let $collation :=
            if ($datatype eq "string")
            then "http://marklogic.com/collation/"
            else ""
        let $name      := subsequence($new-idx, $offset + 1, 1)
        let $curr      := $curr-idx[
            string(dbx:scalar-type) eq $datatype and
            tokenize(string(dbx:field-name), "\s+") = $name and
            string(dbx:collation) eq $collation
            ]
        return
            if (exists($curr)) then (
                xdmp:log(concat("Field range index already exists: ", $name))
            ) else (
                admin:database-range-field-index(
                    $datatype, $name, $collation, false()
                ),
                xdmp:log(concat("Creating field range index: ", $name))
            )
    return
        if (empty($index-specs)) then $c
        else admin:database-add-range-field-index($c, $dbid, $index-specs)
};

declare function bootstrap:create-path-range-indexes(
    $c as element(configuration),
    $dbid as xs:unsignedLong
) as element(configuration)
{
    let $index-specs :=
        let $curr-idx := admin:database-get-range-path-indexes($c, $dbid)
        let $new-idx  := (
            "long", "com.marklogic.client.test.City/population",
            "string", "com.marklogic.client.test.Country/continent"
            )
        for $i in 1 to (count($new-idx) idiv 2)
        let $offset    := ($i * 2) - 1
        let $datatype  := subsequence($new-idx, $offset, 1)
        let $collation :=
            if ($datatype eq "string")
            then "http://marklogic.com/collation/"
            else ""
        let $path      := subsequence($new-idx, $offset + 1, 1)
        let $curr      := $curr-idx[
            string(dbx:scalar-type) eq $datatype and
            string(dbx:path-expression) eq $path and
            string(dbx:collation) eq $collation
            ]
        return
            if (exists($curr)) then (
                xdmp:log(concat("Path range index already exists: ", $path))
            ) else (
                admin:database-range-path-index(
                    $dbid, $datatype, $path, $collation, false(), "ignore"
                ),
                xdmp:log(concat("Creating path range index: ", $path))
            )
    return
        if (empty($index-specs)) then $c
        else admin:database-add-range-path-index($c, $dbid, $index-specs)
};

declare function bootstrap:create-geospatial-path-indexes(
    $c as element(configuration),
    $dbid as xs:unsignedLong
) as element(configuration)
{
    let $index-specs :=
        let $curr-idx := admin:database-get-geospatial-path-indexes($c, $dbid)
        let $new-idx  := (
            "com.marklogic.client.test.City/latLong"
            )
        (: no offset necessary now since each new-idx only has one item, but that may change :)
        let $n := 1
        for $i in 1 to (count($new-idx) idiv $n)
        let $offset    := ($i * $n) - ($n - 1)
        let $path      := subsequence($new-idx, $offset, 1)
        let $curr      := $curr-idx[
            string(dbx:path-expression) eq $path and
            string(dbx:coordinate-system) eq "wgs84" and
            string(dbx:range-value-positions) eq "false" and
            string(dbx:point-format) eq "point"
            ]
        return
            if (exists($curr)) then (
                xdmp:log(concat("Geospatial-path-index already exists:", $path))
            ) else (
                admin:database-geospatial-path-index(
                    $path, "wgs84", false(), "point", "reject"
                ),
                xdmp:log(concat("Creating geospatial-path-index:", $path))
            )
    return
        if (empty($index-specs)) then $c
        else admin:database-add-geospatial-path-index($c, $dbid, $index-specs)
};

declare function bootstrap:security-config(
$command as xs:string
)
{
    try {
        xdmp:eval(concat('xquery version "1.0-ml"; ',
                    'import module namespace sec="http://marklogic.com/xdmp/security" at  ',
                    '    "/MarkLogic/security.xqy"; ',
                    $command),
        (),
        <options xmlns="xdmp:eval">
            <database>{ xdmp:database("Security") }</database>
        </options>)
    } catch($e) {
        xdmp:log($e)
    }
};

declare function bootstrap:temporal-setup() as xs:string*
{
    try {
        let $id := temporal:axis-create(
            "system-axis",
            cts:element-reference(xs:QName("system-start"), "type=dateTime"),
            cts:element-reference(xs:QName("system-end"), "type=dateTime")
        )
        return if ( $id ) then xdmp:log("Created system-axis") else ()
    } catch($e) {
        if ( "XDMP-ELEMRIDXNOTFOUND" = $e/error:code ) then
            xdmp:log("Couldn't create system-axis.  Waiting for creation of system-start and system-end " ||
                "element range indexes...try again")
        else if ( "TEMPORAL-DUPAXIS" = $e/error:code ) then xdmp:log("system-axis already exists")
        else xdmp:log($e)
    },
    try {
        let $id := temporal:axis-create(
            "valid-axis",
            cts:element-reference(xs:QName("valid-start"), "type=dateTime"),
            cts:element-reference(xs:QName("valid-end"), "type=dateTime")
        )
        return if ( $id ) then xdmp:log("Created valid-axis") else ()
    } catch($e) {
        if ( "XDMP-ELEMRIDXNOTFOUND" = $e/error:code ) then
            xdmp:log("Couldn't create system-axis.  Waiting for creation of valid-start and valid-end " ||
                "element range indexes...try again")
        else if ( "TEMPORAL-DUPAXIS" = $e/error:code ) then xdmp:log("valid-axis already exists")
        else xdmp:log($e)
    },
    try {
        let $id := temporal:collection-create("temporal-collection", "system-axis", "valid-axis")
        return if ( $id ) then xdmp:log("Created temporal-collection") else ()
    } catch($e) {
        if ( "TEMPORAL-AXISNOTFOUND" = $e/error:code ) then
            xdmp:log("Couldn't create temporal-collection.  " ||
                "Waiting for creation of system-axis and valid-axis...try again")
        else if ( "TEMPORAL-DUPCOLLECTION" = $e/error:code ) then xdmp:log("temporal-collection already exists")
        else xdmp:log($e)
    }
};

declare function bootstrap:load-data()
{
    xdmp:eval('xquery version "1.0-ml";
    xdmp:document-insert(
        "/sample/first.xml",
        <root name="first">
            <child id="1">
                <leaf>leaf1</leaf>
            </child>
            <child id="2">
                <leaf>leaf2</leaf>
            </child>
            <child id="3">
                <leaf>leaf3</leaf>
            </child>
        </root>
        ),
    xdmp:document-add-collections("/sample/first.xml",("http://some.org/collection1","http://some.org/collection2")),
    xdmp:document-set-permissions("/sample/first.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-set-properties(
        "/sample/first.xml",
        (
            <sample-property>first</sample-property>,
            <container-property><name>alpha</name><number>1</number></container-property>
            )
        ),
    xdmp:document-insert(
        "/sample/second.txt",
        <text><![CDATA[First line
    Second line
    Third line]]></text>/text()
        ),
    xdmp:document-set-permissions("/sample/second.txt",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-set-properties(
        "/sample/second.txt",
        (
            <sample-property>second</sample-property>,
            <container-property><name>beta</name><number>2</number></container-property>
            )
        ),
    xdmp:document-insert(
        "/sample/third.json",
        <text><![CDATA[{
        "firstKey":"first value",
        "secondKey":["first item","second item","third item"],
        "thirdKey":3,
        "fourthKey":{"subKey":"sub value"}
    }]]></text>/text()
        ),
    xdmp:document-set-permissions("/sample/third.json",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-set-properties(
        "/sample/third.json",
        (
            <json:sample-property type="string">third</json:sample-property>,
            <json:container-property type="object">
                <json:name type="string">gamma</json:name>
                <json:number type="number">3</json:number>
            </json:container-property>
            )
        ),
    xdmp:document-insert(
        "/sample/fourth.xml",
    <json:json version="1.0" type="object">
        <json:firstKey type="string">first value</json:firstKey>
        <json:fourthKey type="object">
            <json:subKey type="string">sub value</json:subKey>
        </json:fourthKey>
        <json:secondKey type="array">
            <json:item type="string">first item</json:item>
            <json:item type="string">second item</json:item>
            <json:item type="string">third item</json:item>
        </json:secondKey>
        <json:thirdKey type="number">3</json:thirdKey>
    </json:json>
        ),
    xdmp:document-set-permissions("/sample/fourth.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-set-properties(
        "/sample/fourth.xml",
        (
            <sample-property>fourth</sample-property>,
            <container-property><name>delta</name><number>4</number></container-property>
            )
        ),
    xdmp:document-insert(
        "/sample/fifth.sh",
            <text><![CDATA[#!/bin/sh
    echo "hello, world"
    ]]></text>/text()
        ),
    xdmp:document-set-permissions("/sample/fifth.sh",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-set-properties(
        "/sample/fifth.sh",
        (
            <sample-property>fifth</sample-property>,
            <container-property><name>epsilon</name><number>5</number></container-property>
            )
        ),
    xdmp:document-insert(
        "/sample/databases-icon-mini.png",
    binary{xs:hexBinary(xs:base64Binary(
    "iVBORw0KGgoAAAANSUhEUgAAAA0AAAATCAYAAABLN4eXAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oIEQEjMtAYogQAAAKvSURBVCjPlZLLbhxFAEVPVVdXVz/G8zCOn0CsKGyQkSIIKzas8xfsWbLkp/gJhCKheIlAJDaj2MYez6u7p7vrxQKUPVc6+yOdK77/4cfXQohJqlOVZdmBSpKY6jQKBM45oVMlgHvrvMuNWRljvlNKq69G2YyqLDg4mLE/2yPNYFRWlFXF/nTC2clRWbc7Fss1IcZzqTA8eWY5eu7p1Hv+WvyBVjnGZOQmI9UKISUqSXDO0bS7Tko0xfGSp18kjM7v+P3+NUMr8T5grWMYLCEErHM474khoCw1t78eU/8mEOpjXpxekJUORIZSCbkxSCnRWpPnBikTqbx31E1DjJHpeIzRhnW9xceI857H5Yr1Zku765jf3DIMtlUAIQRCiFhnabsOH1IEAmstAGWRY11ApykmM0oplTKZjNGZREpJoUueHI0ZFRV7exX7+1Nm0yn9YLm5u2fX96lUseLwxQ0vX8H04i2/XP9Et5H44OkHS920hBDo+56u77GDjcrHjvV1ya3TDO2M01mOUAEAhED+R5IkpKmCiFCOjoc/p+xuLbPpCc+P95HaEqIBIhHoB8t2W/PwsKBudl5FH7GxwUYYouJh5ci7nLbtWW02LBaPvLuef1AdrItKKolJpkivwGrG5QxTCsq8pCxLqqrk7PiIwTmW6y0xRCVTSg4vFnz+raM4+5ur1RtSUZHnOUWeMx5VVFWJTlOstfTWRuk96NIyOUgRRc188RZvgRg/3OffjoFESohxUMvmjqufP+X+MqDTU77+5EvMKKBUQpZpijxHSkluDHvjMW8uL79Rnz07bwSyzDLFqCzwDNw/PNI0O9bbhvVmQ7vb0bQdi+Wq327rl+rko8krodKnCHnofJju+r5oupBstg1KJT7Vuruev185O9zVm/WVUmouYoz83/0DxhRmafe2kasAAAAASUVORK5CYII="
    ))}
        ),
    xdmp:document-insert(
        "/sample/databases-icon-mini.xhtml",
    <xhtml:html xmlns:xhtml="http://www.w3.org/1999/xhtml">
      <xhtml:head>
        <xhtml:meta name="content-type" content="image/png"/>
        <xhtml:meta name="filter-capabilities" content="none"/>
        <xhtml:meta name="size" content="815"/>
        <xhtml:meta name="MarkLogic_Binary_Source" content="/sample/databases-icon-mini.png"/>
      </xhtml:head>
    </xhtml:html>
    ),
    xdmp:document-set-permissions("/sample/databases-icon-mini.png",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-set-permissions("/sample/databases-icon-mini.xhtml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/metadata-separate.xml",
        <metadata-target/>
        ),
    xdmp:document-set-permissions("/sample/metadata-separate.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/metadata-all.xml",
        <metadata-target/>
        ),
    xdmp:document-set-permissions("/sample/metadata-all.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/metadata-separate2.xml",
        <metadata-target/>
        ),
    xdmp:document-set-permissions("/sample/metadata-separate2.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/metadata-all2.xml",
        <metadata-target/>
        ),
    xdmp:document-set-permissions("/sample/metadata-all2.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/metadata-all3.xml",
        <metadata-target/>
        ),
    xdmp:document-set-permissions("/sample/metadata-all3.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/metadata-all4.xml",
        <metadata-target/>
        ),
    xdmp:document-set-permissions("/sample/metadata-all4.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/metadata-separate-json.xml",
        <json:json type="object"/>
        ),
    xdmp:document-set-permissions("/sample/metadata-separate-json.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/metadata-all-json.xml",
        <json:json type="object"/>
        ),
    xdmp:document-set-permissions("/sample/metadata-all-json.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/metadata-separate-json2.xml",
        <json:json type="object"/>
        ),
    xdmp:document-set-permissions("/sample/metadata-separate-json2.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/metadata-all-json2.xml",
        <json:json type="object"/>
        ),
    xdmp:document-set-permissions("/sample/metadata-all-json2.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/metadata-all-json3.xml",
        <json:json type="object"/>
        ),
    xdmp:document-set-permissions("/sample/metadata-all-json3.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-set-properties(
        "/sample/prop-only.xml",
        (
            <sample-property>first</sample-property>,
            <container-property><name>alpha</name><number>1</number></container-property>
            )
        ),
    xdmp:document-set-properties(
        "/sample/prop-only.json",
        (
            <json:sample-property type="string">third</json:sample-property>,
            <json:container-property type="object">
                <json:name type="string">gamma</json:name>
                <json:number type="number">3</json:number>
            </json:container-property>
            )
        ),
    xdmp:document-insert(
        "/sample/invalid-separate.xml",
        <metadata-target/>
        ),
    xdmp:document-set-permissions("/sample/invalid-separate.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/invalid-all.xml",
        <metadata-target/>
        ),
    xdmp:document-set-permissions("/sample/invalid-all.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/invalid-separate-json.xml",
        <json:json type="object"/>
        ),
    xdmp:document-set-permissions("/sample/invalid-separate-json.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/invalid-all-json.xml",
        <json:json type="object"/>
        ),
    xdmp:document-set-permissions("/sample/invalid-all-json.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/lexicon-test1.xml",
        <root name="first">
            <child id="1">
                <grandchild>grandchild1</grandchild>
            </child>
            <child id="2">
                <grandchild>grandchild2</grandchild>
            </child>
            <child id="3">
                <grandchild>grandchild3</grandchild>
            </child>
        </root>
        ),
    xdmp:document-add-collections("/sample/lexicon-test1.xml",("http://some.org/collection1","http://some.org/collection2")),
    xdmp:document-set-permissions("/sample/lexicon-test1.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-set-properties(
        "/sample/lexicon-test1.xml",
        (
            <sample-property>lexicon-test</sample-property>,
            <container-property><name>alpha</name><number>1</number></container-property>
            )
        ),
    xdmp:document-insert(
        "/sample/lexicon-test2.xml",
        <root name="first">
            <child id="1">
                <grandchild>grandchild4</grandchild>
            </child>
            <child id="2">
                <grandchild>grandchild5</grandchild>
            </child>
            <child id="3">
                <grandchild>grandchild6</grandchild>
            </child>
        </root>
        ),
    xdmp:document-add-collections("/sample/lexicon-test2.xml",("http://some.org/collection1","http://some.org/collection2")),
    xdmp:document-set-permissions("/sample/lexicon-test2.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-set-properties(
        "/sample/lexicon-test2.xml",
        (
            <sample-property>lexicon-test</sample-property>,
            <container-property><name>alpha</name><number>1</number></container-property>
            )
        ),
    xdmp:document-insert(
        "/sample/lexicon-test3.xml",
        <root name="first">
            <child id="1">
                <double>1.2</double>
                <int>10</int>
            </child>
            <child id="2">
                <double>2.3</double>
                <int>20</int>
            </child>
        </root>
        ),
    xdmp:document-set-permissions("/sample/lexicon-test3.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/lexicon-test4.xml",
        <root name="second">
            <child id="3">
                <double>2.2</double>
                <int>30</int>
            </child>
            <child id="5">
                <double>1.2</double>
                <int>10</int>
            </child>
             <child id="6">
                <double>1.2</double>
                <int>4</int>
            </child>
        </root>
        ),
    xdmp:document-set-permissions("/sample/lexicon-test4.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/udf-test.xml",
        <root name="first">
            <element-test attribute-test="1"/>
            <element-test attribute-test="5"/>
            <element-test attribute-test="9"/>
        </root>),
xdmp:document-insert(
    "/sample/tuples-test1.xml",
    <root name="first">
        <child id="1">
            <double>1.1</double>
            <int>1</int>
            <string>Alaska</string>
        </child>
    </root>
    ),
xdmp:document-set-permissions("/sample/tuples-test1.xml",
    (xdmp:permission("rest-reader","read"),
    xdmp:permission("rest-writer","update"),
    xdmp:permission("app-user","read"),
    xdmp:permission("app-user","update"))
    ),
xdmp:document-insert(
    "/sample/tuples-test2.xml",
    <root name="second">
        <child id="3">
            <double>1.1</double>
            <int>3</int>
            <string>Birmingham</string>
        </child>
    </root>
    ),
xdmp:document-set-permissions("/sample/tuples-test2.xml",
    (xdmp:permission("rest-reader","read"),
    xdmp:permission("rest-writer","update"),
    xdmp:permission("app-user","read"),
    xdmp:permission("app-user","update"))
    ),
xdmp:document-insert(
    "/sample/tuples-test3.xml",
    <root name="second">
        <child id="3">
            <double>1.2</double>
            <int>3</int>
            <string>Birmingham</string>
        </child>
    </root>
    ),
xdmp:document-set-permissions("/sample/tuples-test3.xml",
    (xdmp:permission("rest-reader","read"),
    xdmp:permission("rest-writer","update"),
    xdmp:permission("app-user","read"),
    xdmp:permission("app-user","update"))
    ),
xdmp:document-insert(
    "/sample/tuples-test4.xml",
    <root name="second">
        <child id="3">
            <double>1.2</double>
            <int>3</int>
            <string>Alaska</string>
        </child>
    </root>
    ),
xdmp:document-set-permissions("/sample/tuples-test4.xml",
    (xdmp:permission("rest-reader","read"),
    xdmp:permission("rest-writer","update"),
    xdmp:permission("app-user","read"),
    xdmp:permission("app-user","update"))
    ),
    xdmp:document-set-permissions("/sample/udf-test.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/legacy space file.xml",
        <samplelegacy>document</samplelegacy>
        ),
    xdmp:document-set-permissions("/sample/legacy space file.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"))
        ),

    xdmp:document-insert("/sample/suggestion.xml",
        <suggest><string>FINDME</string>Something I love to suggest is sugar with savory succulent limes.</suggest>),
    xdmp:document-set-permissions("/sample/suggestion.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"))
        ),
    xdmp:document-add-collections("/sample/suggestion.xml",("http://some.org/complexsuggestions")),
    xdmp:document-insert("/sample2/suggestion.xml",
        <suggest>Something I hate to suggest is liver with lard.</suggest>),
    xdmp:document-set-permissions("/sample2/suggestion.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"))
            ),
    xdmp:document-add-collections("/sample2/suggestion.xml",("http://some.org/suggestions"))
'
    ),
    xdmp:eval('xquery version "1.0-ml";
    xdmp:document-insert("/Default/java-unittest/rest-api/options/filtered.xml",
    <options xmlns="http://marklogic.com/appservices/search">
        <search-option>filtered</search-option>
    </options>
    )', (),
    <options xmlns="xdmp:eval">
        <database>{ xdmp:database("java-unittest-modules") }</database>
    </options>)
};

declare function bootstrap:load-search-data()
{
    ()
};

declare function bootstrap:post(
    $context as map:map,
    $params  as map:map,
    $input as document-node()*
) as document-node()*
{
    let $responses := (
        for $user in ("rest-admin", "rest-reader", "rest-writer", "valid")
        let $user-id :=
            try {
                xdmp:user($user)
            } catch($e) {
                xdmp:log("User "||$user||" not found.")
            }
        return
            if (exists($user-id)) then xdmp:log("User "|| $user || ", id "||$user-id|| "already exists")
            else if ($user eq "valid")
            then bootstrap:security-config('sec:create-user("valid", "valid unprivileged user", "x", (), (), (), ())')
            else bootstrap:security-config('sec:create-user("'||$user||'", "'||$user||' user", "x", ("'||$user||'"), (), (), () )'),

        let $dbid := xdmp:database("java-unittest")
        return (
            bootstrap:database-configure($dbid),
            xdmp:log(concat("Configured Java test database:", xdmp:database-name($dbid)))
            ),

        bootstrap:temporal-setup(),
        bootstrap:load-data()
    )
    return if ( $responses ) then
        document{<responses>{
            for $response in $responses
            return <response>{$response}</response>
        }</responses>}
    else ()
};

xquery version "1.0-ml";

module namespace bootstrap = "http://marklogic.com/rest-api/resource/bootstrap";
(: Copyright 2002-2010 Mark Logic Corporation.  All Rights Reserved. :)

import module namespace admin = "http://marklogic.com/xdmp/admin" at "/MarkLogic/admin.xqy";
import module namespace temporal = "http://marklogic.com/xdmp/temporal" at "/MarkLogic/temporal.xqy";

declare namespace dbx = "http://marklogic.com/xdmp/database";
declare namespace error = "http://marklogic.com/xdmp/error";

declare default function namespace "http://www.w3.org/2005/xpath-functions";
declare option xdmp:mapping "false";

declare function bootstrap:database-configure(
  $dbid as xs:unsignedLong
) as empty-sequence()
{
    let $c := admin:get-configuration()

    let $c := bootstrap:create-range-element-indexes($c, $dbid)
    let $c := bootstrap:create-element-attribute-range-indexes($c, $dbid)
    let $c := bootstrap:create-element-word-lexicons($c, $dbid)
    let $c := bootstrap:create-geospatial-element-pair-indexes($c, $dbid)
    let $c := bootstrap:create-field-range-indexes($c, $dbid)
    let $c := bootstrap:create-fields($c, $dbid)
    (: you can't create field and field range index in same transaction :)
    return admin:save-configuration-without-restart($c),

    let $c := admin:get-configuration()
    let $c := bootstrap:create-path-range-indexes($c, $dbid)
    let $c := bootstrap:create-geospatial-path-indexes($c, $dbid)
    return admin:save-configuration-without-restart($c)
};

declare function bootstrap:create-range-element-indexes(
    $c as element(configuration),
    $dbid as xs:unsignedLong
) as element(configuration)
{

    (: collection and word lexicons and triple index on :)
    let $c := admin:database-set-collection-lexicon($c, $dbid, true())
    let $c := admin:database-set-maintain-last-modified($c, $dbid, true())
    let $c := admin:database-set-triple-index($c, $dbid, true())

    let $index-specs :=
        let $curr-idx := admin:database-get-range-element-indexes($c, $dbid)
        let $new-idx  := (
            "dateTime", "http://marklogic.com/xdmp/property", "last-modified",
            "string",   "http://nwalsh.com/ns/photolib",      "tag",
            "date",     "http://nwalsh.com/ns/photolib",      "date",
            "double",   "",                                   "double",
            "int",      "",                                   "int",
            "string",   "",                                   "grandchild",
            "string",   "",                                   "string",
            "dateTime", "",                                   "system-start",
            "dateTime", "",                                   "system-end",
            "dateTime", "",                                   "valid-start",
            "dateTime", "",                                   "valid-end"
            )
        for $i in 1 to (count($new-idx) idiv 3)
        let $offset    := ($i * 3) - 2
        let $datatype  := subsequence($new-idx, $offset, 1)
        let $collation :=
            if ($datatype eq "string")
            then "http://marklogic.com/collation/"
            else ""
        let $ns        := subsequence($new-idx, $offset + 1, 1)
        let $name      := subsequence($new-idx, $offset + 2, 1)
        let $curr      := $curr-idx[
            string(dbx:scalar-type) eq $datatype and
            string(dbx:namespace-uri) eq $ns and
            tokenize(string(dbx:localname), "\s+") = $name and
            string(dbx:collation) eq $collation
            ]
        return
            if (exists($curr)) then (
                xdmp:log(concat("Element range index already exists: ", $name))
            ) else (
                admin:database-range-element-index(
                    $datatype, $ns, $name, $collation, false()
                ),
                xdmp:log(concat("Creating element range index: ", $name))
            )

    return
        if (empty($index-specs)) then $c
        else admin:database-add-range-element-index($c, $dbid, $index-specs)
};

declare function bootstrap:create-element-attribute-range-indexes(
    $c as element(configuration),
    $dbid as xs:unsignedLong
) as element(configuration)
{
    let $index-specs :=
        let $curr-idx := admin:database-get-range-element-attribute-indexes($c, $dbid)
        let $new-idx  := (
            "date", "http://nwalsh.com/ns/photolib", "view", "", "date"
            )
        for $i in 1 to (count($new-idx) idiv 5)
        let $offset    := ($i * 5) - 4
        let $datatype  := subsequence($new-idx, $offset, 1)
        let $collation :=
            if ($datatype eq "string")
            then "http://marklogic.com/collation/"
            else ""
        let $e-ns      := subsequence($new-idx, $offset + 1, 1)
        let $e-name    := subsequence($new-idx, $offset + 2, 1)
        let $a-ns      := subsequence($new-idx, $offset + 3, 1)
        let $a-name    := subsequence($new-idx, $offset + 4, 1)
        let $curr      := $curr-idx[
            string(dbx:scalar-type) eq $datatype and
            string(dbx:parent-namespace-uri) eq $e-ns and
            tokenize(string(dbx:parent-localname), "\s+") = $e-name and
            string(dbx:namespace-uri) eq $a-ns and
            tokenize(string(dbx:localname), "\s+") = $a-name and
            string(dbx:collation) eq $collation
            ]
        return
            if (exists($curr)) then (
                xdmp:log(concat("element-attribute range index already exists:[", $e-name, ",", $a-name, "]"))
            ) else (
                admin:database-range-element-attribute-index(
                    $datatype, $e-ns, $e-name, $a-ns, $a-name, $collation, false()
                ),
                xdmp:log(concat("Creating element-attribute range index:[", $e-name, ",", $a-name, "]"))
            )
    return
        if (empty($index-specs)) then $c
        else admin:database-add-range-element-attribute-index($c, $dbid, $index-specs)
};

declare function bootstrap:create-element-word-lexicons(
    $c as element(configuration),
    $dbid as xs:unsignedLong
) as element(configuration)
{
    let $index-specs :=
        let $curr-idx := admin:database-get-element-word-lexicons($c, $dbid)
        let $new-idx  := (
            "", "suggest"
            )
        for $i in 1 to (count($new-idx) idiv 2)
        let $offset    := ($i * 2) - 1
        let $collation := "http://marklogic.com/collation/"
        let $ns        := subsequence($new-idx, $offset, 1)
        let $name      := subsequence($new-idx, $offset + 1, 1)
        let $curr      := $curr-idx[
            string(dbx:namespace-uri) eq $ns and
            tokenize(string(dbx:localname), "\s+") = $name and
            string(dbx:collation) eq $collation
            ]
        return
            if (exists($curr)) then (
                xdmp:log(concat("element-word index already exists: ", $name))
            ) else (
                admin:database-element-word-lexicon($ns, $name, $collation),
                xdmp:log(concat("Creating element-word index: ", $name))
            )
    return
        if (empty($index-specs)) then $c
        else admin:database-add-element-word-lexicon($c, $dbid, $index-specs)
};

declare function bootstrap:create-geospatial-element-pair-indexes(
    $c as element(configuration),
    $dbid as xs:unsignedLong
) as element(configuration)
{
    (: create geospatial indexes for geo unit test :)
    let $index-specs :=
        let $curr-idx := admin:database-get-geospatial-element-pair-indexes($c, $dbid)
        let $p := "http://marklogic.com/ns/test/places"
        let $new-idx  := (
            $p, "place", $p, "lat", $p, "long", "wgs84"
            )
        for $i in 1 to (count($new-idx) idiv 7)
        let $offset    := ($i * 7) - 6
        let $p-ns      := subsequence($new-idx, $offset, 1)
        let $p-name    := subsequence($new-idx, $offset + 1, 1)
        let $lat-ns    := subsequence($new-idx, $offset + 2, 1)
        let $lat-name  := subsequence($new-idx, $offset + 3, 1)
        let $lon-ns    := subsequence($new-idx, $offset + 4, 1)
        let $lon-name  := subsequence($new-idx, $offset + 5, 1)
        let $coord-sys := subsequence($new-idx, $offset + 6, 1)
        let $curr      := $curr-idx[
            string(dbx:parent-namespace-uri) eq $p-ns and
            tokenize(string(dbx:parent-localname), "\s+") = $p-name and
            string(dbx:latitude-namespace-uri) eq $lat-ns and
            tokenize(string(dbx:latitude-localname), "\s+") = $lat-name and
            string(dbx:longitude-namespace-uri) eq $lon-ns and
            tokenize(string(dbx:longitude-localname), "\s+") = $lon-name and
            string(dbx:coordinate-system) eq $coord-sys
            ]
        return
            if (exists($curr)) then (
                xdmp:log(concat("Geo-elem-pair-index already exists:[", $p-name, ",", $lat-name, ",", $lon-name, "]"))
            ) else (
                admin:database-geospatial-element-pair-index(
                    $p-ns, $p-name, $lat-ns, $lat-name, $lon-ns, $lon-name, $coord-sys, false()
                ),
                xdmp:log(concat("Creating geo-elem-pair-index:[", $p-name, ",", $lat-name, ",", $lon-name, "]"))
            )
    return
        if (empty($index-specs)) then $c
        else admin:database-add-geospatial-element-pair-index($c, $dbid, $index-specs)
};

declare function bootstrap:create-fields(
    $c as element(configuration),
    $dbid as xs:unsignedLong
) as element(configuration)
{

    let $def-specs :=
        let $curr-def := admin:database-get-fields($c, $dbid)
        for $new-def in ("int1", "int2")
        let $curr := $curr-def[
            string(dbx:field-name) eq $new-def
            ]
        return
            if (exists($curr)) then (
                xdmp:log(concat("Field index already exists: ", $new-def))
            ) else (
                admin:database-field($new-def, false()),
                xdmp:log(concat("Creating field: ", $new-def))
            )
    return
        if (empty($def-specs)) then $c
        else admin:database-add-field($c, $dbid, $def-specs)
};

declare function bootstrap:create-field-range-indexes(
    $c as element(configuration),
    $dbid as xs:unsignedLong
) as element(configuration)
{
    let $index-specs :=
        let $curr-idx := admin:database-get-range-field-indexes($c, $dbid)
        let $new-idx  := (
            "int", "int1",
            "int", "int2"
            )
        for $i in 1 to (count($new-idx) idiv 2)
        let $offset    := ($i * 2) - 1
        let $datatype  := subsequence($new-idx, $offset, 1)
        let $collation :=
            if ($datatype eq "string")
            then "http://marklogic.com/collation/"
            else ""
        let $name      := subsequence($new-idx, $offset + 1, 1)
        let $curr      := $curr-idx[
            string(dbx:scalar-type) eq $datatype and
            tokenize(string(dbx:field-name), "\s+") = $name and
            string(dbx:collation) eq $collation
            ]
        return
            if (exists($curr)) then (
                xdmp:log(concat("Field range index already exists: ", $name))
            ) else (
                admin:database-range-field-index(
                    $datatype, $name, $collation, false()
                ),
                xdmp:log(concat("Creating field range index: ", $name))
            )
    return
        if (empty($index-specs)) then $c
        else admin:database-add-range-field-index($c, $dbid, $index-specs)
};

declare function bootstrap:create-path-range-indexes(
    $c as element(configuration),
    $dbid as xs:unsignedLong
) as element(configuration)
{
    let $index-specs :=
        let $curr-idx := admin:database-get-range-path-indexes($c, $dbid)
        let $new-idx  := (
            "long", "com.marklogic.client.test.City/population",
            "string", "com.marklogic.client.test.Country/continent"
            )
        for $i in 1 to (count($new-idx) idiv 2)
        let $offset    := ($i * 2) - 1
        let $datatype  := subsequence($new-idx, $offset, 1)
        let $collation :=
            if ($datatype eq "string")
            then "http://marklogic.com/collation/"
            else ""
        let $path      := subsequence($new-idx, $offset + 1, 1)
        let $curr      := $curr-idx[
            string(dbx:scalar-type) eq $datatype and
            string(dbx:path-expression) eq $path and
            string(dbx:collation) eq $collation
            ]
        return
            if (exists($curr)) then (
                xdmp:log(concat("Path range index already exists: ", $path))
            ) else (
                admin:database-range-path-index(
                    $dbid, $datatype, $path, $collation, false(), "ignore"
                ),
                xdmp:log(concat("Creating path range index: ", $path))
            )
    return
        if (empty($index-specs)) then $c
        else admin:database-add-range-path-index($c, $dbid, $index-specs)
};

declare function bootstrap:create-geospatial-path-indexes(
    $c as element(configuration),
    $dbid as xs:unsignedLong
) as element(configuration)
{
    let $index-specs :=
        let $curr-idx := admin:database-get-geospatial-path-indexes($c, $dbid)
        let $new-idx  := (
            "com.marklogic.client.test.City/latLong"
            )
        (: no offset necessary now since each new-idx only has one item, but that may change :)
        let $n := 1
        for $i in 1 to (count($new-idx) idiv $n)
        let $offset    := ($i * $n) - ($n - 1)
        let $path      := subsequence($new-idx, $offset, 1)
        let $curr      := $curr-idx[
            string(dbx:path-expression) eq $path and
            string(dbx:coordinate-system) eq "wgs84" and
            string(dbx:range-value-positions) eq "false" and
            string(dbx:point-format) eq "point"
            ]
        return
            if (exists($curr)) then (
                xdmp:log(concat("Geospatial-path-index already exists:", $path))
            ) else (
                admin:database-geospatial-path-index(
                    $path, "wgs84", false(), "point", "reject"
                ),
                xdmp:log(concat("Creating geospatial-path-index:", $path))
            )
    return
        if (empty($index-specs)) then $c
        else admin:database-add-geospatial-path-index($c, $dbid, $index-specs)
};

declare function bootstrap:security-config(
$command as xs:string
)
{
    try {
        xdmp:eval(concat('xquery version "1.0-ml"; ',
                    'import module namespace sec="http://marklogic.com/xdmp/security" at  ',
                    '    "/MarkLogic/security.xqy"; ',
                    $command),
        (),
        <options xmlns="xdmp:eval">
            <database>{ xdmp:database("Security") }</database>
        </options>)
    } catch($e) {
        xdmp:log($e)
    }
};

declare function bootstrap:temporal-setup() as xs:string*
{
    try {
        let $id := temporal:axis-create(
            "system-axis",
            cts:element-reference(xs:QName("system-start"), "type=dateTime"),
            cts:element-reference(xs:QName("system-end"), "type=dateTime")
        )
        return if ( $id ) then xdmp:log("Created system-axis") else ()
    } catch($e) {
        if ( "XDMP-ELEMRIDXNOTFOUND" = $e/error:code ) then
            xdmp:log("Couldn't create system-axis.  Waiting for creation of system-start and system-end " ||
                "element range indexes...try again")
        else if ( "TEMPORAL-DUPAXIS" = $e/error:code ) then xdmp:log("system-axis already exists")
        else xdmp:log($e)
    },
    try {
        let $id := temporal:axis-create(
            "valid-axis",
            cts:element-reference(xs:QName("valid-start"), "type=dateTime"),
            cts:element-reference(xs:QName("valid-end"), "type=dateTime")
        )
        return if ( $id ) then xdmp:log("Created valid-axis") else ()
    } catch($e) {
        if ( "XDMP-ELEMRIDXNOTFOUND" = $e/error:code ) then
            xdmp:log("Couldn't create system-axis.  Waiting for creation of valid-start and valid-end " ||
                "element range indexes...try again")
        else if ( "TEMPORAL-DUPAXIS" = $e/error:code ) then xdmp:log("valid-axis already exists")
        else xdmp:log($e)
    },
    try {
        let $id := temporal:collection-create("temporal-collection", "system-axis", "valid-axis")
        return if ( $id ) then xdmp:log("Created temporal-collection") else ()
    } catch($e) {
        if ( "TEMPORAL-AXISNOTFOUND" = $e/error:code ) then
            xdmp:log("Couldn't create temporal-collection.  " ||
                "Waiting for creation of system-axis and valid-axis...try again")
        else if ( "TEMPORAL-DUPCOLLECTION" = $e/error:code ) then xdmp:log("temporal-collection already exists")
        else xdmp:log($e)
    }
};

declare function bootstrap:load-data()
{
    xdmp:eval('xquery version "1.0-ml";
    xdmp:document-insert(
        "/sample/first.xml",
        <root name="first">
            <child id="1">
                <leaf>leaf1</leaf>
            </child>
            <child id="2">
                <leaf>leaf2</leaf>
            </child>
            <child id="3">
                <leaf>leaf3</leaf>
            </child>
        </root>
        ),
    xdmp:document-add-collections("/sample/first.xml",("http://some.org/collection1","http://some.org/collection2")),
    xdmp:document-set-permissions("/sample/first.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-set-properties(
        "/sample/first.xml",
        (
            <sample-property>first</sample-property>,
            <container-property><name>alpha</name><number>1</number></container-property>
            )
        ),
    xdmp:document-insert(
        "/sample/second.txt",
        <text><![CDATA[First line
    Second line
    Third line]]></text>/text()
        ),
    xdmp:document-set-permissions("/sample/second.txt",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-set-properties(
        "/sample/second.txt",
        (
            <sample-property>second</sample-property>,
            <container-property><name>beta</name><number>2</number></container-property>
            )
        ),
    xdmp:document-insert(
        "/sample/third.json",
        <text><![CDATA[{
        "firstKey":"first value",
        "secondKey":["first item","second item","third item"],
        "thirdKey":3,
        "fourthKey":{"subKey":"sub value"}
    }]]></text>/text()
        ),
    xdmp:document-set-permissions("/sample/third.json",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-set-properties(
        "/sample/third.json",
        (
            <json:sample-property type="string">third</json:sample-property>,
            <json:container-property type="object">
                <json:name type="string">gamma</json:name>
                <json:number type="number">3</json:number>
            </json:container-property>
            )
        ),
    xdmp:document-insert(
        "/sample/fourth.xml",
    <json:json version="1.0" type="object">
        <json:firstKey type="string">first value</json:firstKey>
        <json:fourthKey type="object">
            <json:subKey type="string">sub value</json:subKey>
        </json:fourthKey>
        <json:secondKey type="array">
            <json:item type="string">first item</json:item>
            <json:item type="string">second item</json:item>
            <json:item type="string">third item</json:item>
        </json:secondKey>
        <json:thirdKey type="number">3</json:thirdKey>
    </json:json>
        ),
    xdmp:document-set-permissions("/sample/fourth.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-set-properties(
        "/sample/fourth.xml",
        (
            <sample-property>fourth</sample-property>,
            <container-property><name>delta</name><number>4</number></container-property>
            )
        ),
    xdmp:document-insert(
        "/sample/fifth.sh",
            <text><![CDATA[#!/bin/sh
    echo "hello, world"
    ]]></text>/text()
        ),
    xdmp:document-set-permissions("/sample/fifth.sh",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-set-properties(
        "/sample/fifth.sh",
        (
            <sample-property>fifth</sample-property>,
            <container-property><name>epsilon</name><number>5</number></container-property>
            )
        ),
    xdmp:document-insert(
        "/sample/databases-icon-mini.png",
    binary{xs:hexBinary(xs:base64Binary(
    "iVBORw0KGgoAAAANSUhEUgAAAA0AAAATCAYAAABLN4eXAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oIEQEjMtAYogQAAAKvSURBVCjPlZLLbhxFAEVPVVdXVz/G8zCOn0CsKGyQkSIIKzas8xfsWbLkp/gJhCKheIlAJDaj2MYez6u7p7vrxQKUPVc6+yOdK77/4cfXQohJqlOVZdmBSpKY6jQKBM45oVMlgHvrvMuNWRljvlNKq69G2YyqLDg4mLE/2yPNYFRWlFXF/nTC2clRWbc7Fss1IcZzqTA8eWY5eu7p1Hv+WvyBVjnGZOQmI9UKISUqSXDO0bS7Tko0xfGSp18kjM7v+P3+NUMr8T5grWMYLCEErHM474khoCw1t78eU/8mEOpjXpxekJUORIZSCbkxSCnRWpPnBikTqbx31E1DjJHpeIzRhnW9xceI857H5Yr1Zku765jf3DIMtlUAIQRCiFhnabsOH1IEAmstAGWRY11ApykmM0oplTKZjNGZREpJoUueHI0ZFRV7exX7+1Nm0yn9YLm5u2fX96lUseLwxQ0vX8H04i2/XP9Et5H44OkHS920hBDo+56u77GDjcrHjvV1ya3TDO2M01mOUAEAhED+R5IkpKmCiFCOjoc/p+xuLbPpCc+P95HaEqIBIhHoB8t2W/PwsKBudl5FH7GxwUYYouJh5ci7nLbtWW02LBaPvLuef1AdrItKKolJpkivwGrG5QxTCsq8pCxLqqrk7PiIwTmW6y0xRCVTSg4vFnz+raM4+5ur1RtSUZHnOUWeMx5VVFWJTlOstfTWRuk96NIyOUgRRc188RZvgRg/3OffjoFESohxUMvmjqufP+X+MqDTU77+5EvMKKBUQpZpijxHSkluDHvjMW8uL79Rnz07bwSyzDLFqCzwDNw/PNI0O9bbhvVmQ7vb0bQdi+Wq327rl+rko8krodKnCHnofJju+r5oupBstg1KJT7Vuruev185O9zVm/WVUmouYoz83/0DxhRmafe2kasAAAAASUVORK5CYII="
    ))}
        ),
    xdmp:document-insert(
        "/sample/databases-icon-mini.xhtml",
    <xhtml:html xmlns:xhtml="http://www.w3.org/1999/xhtml">
      <xhtml:head>
        <xhtml:meta name="content-type" content="image/png"/>
        <xhtml:meta name="filter-capabilities" content="none"/>
        <xhtml:meta name="size" content="815"/>
        <xhtml:meta name="MarkLogic_Binary_Source" content="/sample/databases-icon-mini.png"/>
      </xhtml:head>
    </xhtml:html>
    ),
    xdmp:document-set-permissions("/sample/databases-icon-mini.png",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-set-permissions("/sample/databases-icon-mini.xhtml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/metadata-separate.xml",
        <metadata-target/>
        ),
    xdmp:document-set-permissions("/sample/metadata-separate.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/metadata-all.xml",
        <metadata-target/>
        ),
    xdmp:document-set-permissions("/sample/metadata-all.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/metadata-separate2.xml",
        <metadata-target/>
        ),
    xdmp:document-set-permissions("/sample/metadata-separate2.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/metadata-all2.xml",
        <metadata-target/>
        ),
    xdmp:document-set-permissions("/sample/metadata-all2.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/metadata-all3.xml",
        <metadata-target/>
        ),
    xdmp:document-set-permissions("/sample/metadata-all3.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/metadata-all4.xml",
        <metadata-target/>
        ),
    xdmp:document-set-permissions("/sample/metadata-all4.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/metadata-separate-json.xml",
        <json:json type="object"/>
        ),
    xdmp:document-set-permissions("/sample/metadata-separate-json.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/metadata-all-json.xml",
        <json:json type="object"/>
        ),
    xdmp:document-set-permissions("/sample/metadata-all-json.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/metadata-separate-json2.xml",
        <json:json type="object"/>
        ),
    xdmp:document-set-permissions("/sample/metadata-separate-json2.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/metadata-all-json2.xml",
        <json:json type="object"/>
        ),
    xdmp:document-set-permissions("/sample/metadata-all-json2.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/metadata-all-json3.xml",
        <json:json type="object"/>
        ),
    xdmp:document-set-permissions("/sample/metadata-all-json3.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-set-properties(
        "/sample/prop-only.xml",
        (
            <sample-property>first</sample-property>,
            <container-property><name>alpha</name><number>1</number></container-property>
            )
        ),
    xdmp:document-set-properties(
        "/sample/prop-only.json",
        (
            <json:sample-property type="string">third</json:sample-property>,
            <json:container-property type="object">
                <json:name type="string">gamma</json:name>
                <json:number type="number">3</json:number>
            </json:container-property>
            )
        ),
    xdmp:document-insert(
        "/sample/invalid-separate.xml",
        <metadata-target/>
        ),
    xdmp:document-set-permissions("/sample/invalid-separate.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/invalid-all.xml",
        <metadata-target/>
        ),
    xdmp:document-set-permissions("/sample/invalid-all.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/invalid-separate-json.xml",
        <json:json type="object"/>
        ),
    xdmp:document-set-permissions("/sample/invalid-separate-json.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/invalid-all-json.xml",
        <json:json type="object"/>
        ),
    xdmp:document-set-permissions("/sample/invalid-all-json.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/lexicon-test1.xml",
        <root name="first">
            <child id="1">
                <grandchild>grandchild1</grandchild>
            </child>
            <child id="2">
                <grandchild>grandchild2</grandchild>
            </child>
            <child id="3">
                <grandchild>grandchild3</grandchild>
            </child>
        </root>
        ),
    xdmp:document-add-collections("/sample/lexicon-test1.xml",("http://some.org/collection1","http://some.org/collection2")),
    xdmp:document-set-permissions("/sample/lexicon-test1.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-set-properties(
        "/sample/lexicon-test1.xml",
        (
            <sample-property>lexicon-test</sample-property>,
            <container-property><name>alpha</name><number>1</number></container-property>
            )
        ),
    xdmp:document-insert(
        "/sample/lexicon-test2.xml",
        <root name="first">
            <child id="1">
                <grandchild>grandchild4</grandchild>
            </child>
            <child id="2">
                <grandchild>grandchild5</grandchild>
            </child>
            <child id="3">
                <grandchild>grandchild6</grandchild>
            </child>
        </root>
        ),
    xdmp:document-add-collections("/sample/lexicon-test2.xml",("http://some.org/collection1","http://some.org/collection2")),
    xdmp:document-set-permissions("/sample/lexicon-test2.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-set-properties(
        "/sample/lexicon-test2.xml",
        (
            <sample-property>lexicon-test</sample-property>,
            <container-property><name>alpha</name><number>1</number></container-property>
            )
        ),
    xdmp:document-insert(
        "/sample/lexicon-test3.xml",
        <root name="first">
            <child id="1">
                <double>1.2</double>
                <int>10</int>
            </child>
            <child id="2">
                <double>2.3</double>
                <int>20</int>
            </child>
        </root>
        ),
    xdmp:document-set-permissions("/sample/lexicon-test3.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/lexicon-test4.xml",
        <root name="second">
            <child id="3">
                <double>2.2</double>
                <int>30</int>
            </child>
            <child id="5">
                <double>1.2</double>
                <int>10</int>
            </child>
             <child id="6">
                <double>1.2</double>
                <int>4</int>
            </child>
        </root>
        ),
    xdmp:document-set-permissions("/sample/lexicon-test4.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/udf-test.xml",
        <root name="first">
            <element-test attribute-test="1"/>
            <element-test attribute-test="5"/>
            <element-test attribute-test="9"/>
        </root>),
xdmp:document-insert(
    "/sample/tuples-test1.xml",
    <root name="first">
        <child id="1">
            <double>1.1</double>
            <int>1</int>
            <string>Alaska</string>
        </child>
    </root>
    ),
xdmp:document-set-permissions("/sample/tuples-test1.xml",
    (xdmp:permission("rest-reader","read"),
    xdmp:permission("rest-writer","update"),
    xdmp:permission("app-user","read"),
    xdmp:permission("app-user","update"))
    ),
xdmp:document-insert(
    "/sample/tuples-test2.xml",
    <root name="second">
        <child id="3">
            <double>1.1</double>
            <int>3</int>
            <string>Birmingham</string>
        </child>
    </root>
    ),
xdmp:document-set-permissions("/sample/tuples-test2.xml",
    (xdmp:permission("rest-reader","read"),
    xdmp:permission("rest-writer","update"),
    xdmp:permission("app-user","read"),
    xdmp:permission("app-user","update"))
    ),
xdmp:document-insert(
    "/sample/tuples-test3.xml",
    <root name="second">
        <child id="3">
            <double>1.2</double>
            <int>3</int>
            <string>Birmingham</string>
        </child>
    </root>
    ),
xdmp:document-set-permissions("/sample/tuples-test3.xml",
    (xdmp:permission("rest-reader","read"),
    xdmp:permission("rest-writer","update"),
    xdmp:permission("app-user","read"),
    xdmp:permission("app-user","update"))
    ),
xdmp:document-insert(
    "/sample/tuples-test4.xml",
    <root name="second">
        <child id="3">
            <double>1.2</double>
            <int>3</int>
            <string>Alaska</string>
        </child>
    </root>
    ),
xdmp:document-set-permissions("/sample/tuples-test4.xml",
    (xdmp:permission("rest-reader","read"),
    xdmp:permission("rest-writer","update"),
    xdmp:permission("app-user","read"),
    xdmp:permission("app-user","update"))
    ),
    xdmp:document-set-permissions("/sample/udf-test.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"),
        xdmp:permission("app-user","read"),
        xdmp:permission("app-user","update"))
        ),
    xdmp:document-insert(
        "/sample/legacy space file.xml",
        <samplelegacy>document</samplelegacy>
        ),
    xdmp:document-set-permissions("/sample/legacy space file.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"))
        ),

    xdmp:document-insert("/sample/suggestion.xml",
        <suggest><string>FINDME</string>Something I love to suggest is sugar with savory succulent limes.</suggest>),
    xdmp:document-set-permissions("/sample/suggestion.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"))
        ),
    xdmp:document-add-collections("/sample/suggestion.xml",("http://some.org/complexsuggestions")),
    xdmp:document-insert("/sample2/suggestion.xml",
        <suggest>Something I hate to suggest is liver with lard.</suggest>),
    xdmp:document-set-permissions("/sample2/suggestion.xml",
        (xdmp:permission("rest-reader","read"),
        xdmp:permission("rest-writer","update"))
            ),
    xdmp:document-add-collections("/sample2/suggestion.xml",("http://some.org/suggestions"))
'
    )
};

declare function bootstrap:load-search-data()
{
    ()
};

declare function bootstrap:post(
    $context as map:map,
    $params  as map:map,
    $input as document-node()*
) as document-node()*
{
    let $responses := (
        for $user in ("rest-admin", "rest-reader", "rest-writer", "valid")
        let $user-id :=
            try {
                xdmp:user($user)
            } catch($e) {
                xdmp:log("User "||$user||" not found.")
            }
        return
            if (exists($user-id)) then xdmp:log("User "|| $user || ", id "||$user-id|| "already exists")
            else if ($user eq "valid")
            then bootstrap:security-config('sec:create-user("valid", "valid unprivileged user", "x", (), (), (), ())')
            else bootstrap:security-config('sec:create-user("'||$user||'", "'||$user||' user", "x", ("'||$user||'"), (), (), () )'),

        let $dbid := xdmp:database("java-unittest")
        return (
            bootstrap:database-configure($dbid),
            xdmp:log(concat("Configured Java test database:", xdmp:database-name($dbid)))
            ),

        bootstrap:temporal-setup(),
        bootstrap:load-data()
    )
    return if ( $responses ) then
        document{<responses>{
            for $response in $responses
            return <response>{$response}</response>
        }</responses>}
    else ()
};


Fixed self link for feed.

Fixed self link for feed.

svn path=/trunk/eXist-1.0/; revision=3744

<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:atom="http://www.w3.org/2005/Atom">
   {
     "
",
     /atom:feed/atom:title,
     "
",
     /atom:feed/atom:id,
     "
",
     /atom:feed/atom:updated,
     "
"
   }
   {
      let $current := substring-before(base-uri(/atom:feed),'/.feed.atom'),
           $current-path := substring-after($current,'/db')
         return (
            <link rel="alternate" href="/atom/content{substring-after($current,'/db')}" type="application/atom+xml"/>,
           "
",
            let $parts := tokenize($current-path,'/')
               for $i in (1 to count($parts)-1)
                   let $apath := string-join(subsequence($parts,1,$i),'/'),
                       $feed := document(concat($apath,'/.feed.atom'))/atom:feed
                     return (<entry>
                            {
                                "
",
                                $feed/atom:id,
                                "
",
                                $feed/atom:title,
                                "
",
                                $feed/atom:updated,
                                "
",
                                <category scheme="http://www.smallx.com/Ontology/Atopic/2006/1/0/topic/relation" term="ancestor"/>,
                                "
",
                                <link rel="alternate" href="/atom/content{$apath}" type="application/atom+xml"/>,
                                "
",
                                <summary>
                                     {
                                         $feed/atom:subtitle/@type,
                                         $feed/atom:subtitle/node()
                                     }
                                </summary>,
                                "
"
                             }
                            </entry>,
                            "
"
                            ),
            for $i in (collection($current)/atom:feed)
               let $path :=  substring-before(base-uri($i),'/.feed.atom')
                  return if ($current!=$path)
                     then (<entry>
                            {
                                "
",
                                $i/atom:id,
                                "
",
                                $i/atom:title,
                                "
",
                                $i/atom:updated,
                                "
",
                                <category scheme="http://www.smallx.com/Ontology/Atopic/2006/1/0/topic/relation" term="subtopic"/>,
                                "
",
                                <link rel="alternate" href="/atom/content{substring-after($path,'/db')}" type="application/atom+xml"/>,
                                "
",
                                <summary>
                                     {
                                         $i/atom:subtitle/@type,
                                         $i/atom:subtitle/node()
                                     }
                                </summary>,
                                "
"
                             }
                            </entry>,
                            "
"
                            )
                     else ()
         )
   }
</feed>

<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:atom="http://www.w3.org/2005/Atom">
   {
     "
",
     /atom:feed/atom:title,
     "
",
     /atom:feed/atom:id,
     "
",
     /atom:feed/atom:updated,
     "
"
   }
   {
      let $current := substring-before(base-uri(/atom:feed),'/.feed.atom'),
           $current-path := substring-after($current,'/db')
         return (
            <link rel="alternate" href="../content{substring-after($current,'/db')}" type="application/atom+xml"/>,
           "
",
            let $parts := tokenize($current-path,'/')
               for $i in (1 to count($parts)-1)
                   let $apath := string-join(subsequence($parts,1,$i),'/'),
                       $feed := document(concat($apath,'/.feed.atom'))/atom:feed
                     return (<entry>
                            {
                                "
",
                                $feed/atom:id,
                                "
",
                                $feed/atom:title,
                                "
",
                                $feed/atom:updated,
                                "
",
                                <category scheme="http://www.smallx.com/Ontology/Atopic/2006/1/0/topic/relation" term="ancestor"/>,
                                "
",
                                <link rel="alternate" href="/atom/content{$apath}" type="application/atom+xml"/>,
                                "
",
                                <summary>
                                     {
                                         $feed/atom:subtitle/@type,
                                         $feed/atom:subtitle/node()
                                     }
                                </summary>,
                                "
"
                             }
                            </entry>,
                            "
"
                            ),
            for $i in (collection($current)/atom:feed)
               let $path :=  substring-before(base-uri($i),'/.feed.atom')
                  return if ($current!=$path)
                     then (<entry>
                            {
                                "
",
                                $i/atom:id,
                                "
",
                                $i/atom:title,
                                "
",
                                $i/atom:updated,
                                "
",
                                <category scheme="http://www.smallx.com/Ontology/Atopic/2006/1/0/topic/relation" term="subtopic"/>,
                                "
",
                                <link rel="alternate" href="/atom/content{substring-after($path,'/db')}" type="application/atom+xml"/>,
                                "
",
                                <summary>
                                     {
                                         $i/atom:subtitle/@type,
                                         $i/atom:subtitle/node()
                                     }
                                </summary>,
                                "
"
                             }
                            </entry>,
                            "
"
                            )
                     else ()
         )
   }
</feed>


fixed typos in duplicate webui

fixed typos in duplicate webui

module namespace page = 'http://basex.org/modules/web-page';

import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
import module namespace csd_webui =  "https://github.com/openhie/openinfoman/csd_webui";
import module namespace csr_proc = "https://github.com/openhie/openinfoman/csr_proc";
declare   namespace   csd = "urn:ihe:iti:csd:2013";

declare updating
  %rest:path("/CSD/duplicates/{$doc_name}/mark/{$entityID}")
  %rest:GET
  %rest:query-param("masterID", "{$masterID}")
  %output:method("xhtml")
  function page:mark_duplicate_get($doc_name,$entityID,$masterID)
{
  (
    let $doc := csd_dm:open_document($csd_webconf:db,$doc_name)
    let $requestParams :=
      <csd:requestParams function="urn:openhie.org:openinfoman:mark_duplicate"  resource="{$doc_name}" base_url="{csd_webui:generateURL()}">
	<masterEntity entityID="{$masterID}"/>
	<duplicateEntity entityID="{$entityID}"/>
      </csd:requestParams>

    return csr_proc:process_updating_CSR_stored_results($csd_webconf:db, $doc,$requestParams)
    ,
    csd_webui:redirect_out(("/CSD/duplicates/", $doc_name , "/manage/" ,  $entityID ))
  )

};

declare updating
  %rest:path("/CSD/duplicates/{$doc_name}/markPotential/{$entityID}")
  %rest:GET
  %rest:query-param("masterID", "{$masterID}")
  %output:method("xhtml")
  function page:mark_pot_duplicate_get($doc_name,$entityID,$masterID)
{
  (
    let $doc := csd_dm:open_document($csd_webconf:db,$doc_name)
    let $requestParams :=
      <csd:requestParams function="urn:openhie.org:openinfoman:mark_potential_duplicate"  resource="{$doc_name}" base_url="{csd_webui:generateURL()}">
	<masterEntity entityID="{$masterID}"/>
	<duplicateEntity entityID="{$entityID}"/>
      </csd:requestParams>

    return csr_proc:process_updating_CSR_stored_results($csd_webconf:db, $doc,$requestParams)
    ,
    csd_webui:redirect_out(("/CSD/duplicates/", $doc_name , "/manage/" ,  $entityID ))
  )

};

declare updating
  %rest:path("/CSD/duplicates/{$doc_name}/mark/{$entityID}/{$masterID}")
  %rest:GET
  %output:method("xhtml")
  function page:mark_duplicate($doc_name,$entityID,$masterID)
{
  (
    let $doc := csd_dm:open_document($csd_webconf:db,$doc_name)
    let $requestParams :=
      <csd:requestParams function="urn:openhie.org:openinfoman:mark_duplicate"  resource="{$doc_name}" base_url="{csd_webui:generateURL()}">
	<masterEntity entityID="{$masterID}"/>
	<duplicateEntity entityID="{$entityID}"/>
      </csd:requestParams>

    return csr_proc:process_updating_CSR_stored_results($csd_webconf:db, $doc,$requestParams)
    ,
    csd_webui:redirect_out(("/CSD/duplicates/", $doc_name , "/manage/" ,  $entityID ))
  )

};

declare updating
  %rest:path("/CSD/duplicates/{$doc_name}/markPotential/{$entityID}/{$masterID}")
  %rest:GET
  %output:method("xhtml")
  function page:mark_potential_duplicate($doc_name,$entityID,$masterID)
{
  (
    let $doc := csd_dm:open_document($csd_webconf:db,$doc_name)
    let $requestParams :=
      <csd:requestParams function="urn:openhie.org:openinfoman:mark_potential_duplicate"  resource="{$doc_name}" base_url="{csd_webui:generateURL()}">
	<masterEntity entityID="{$masterID}"/>
	<duplicateEntity entityID="{$entityID}"/>
      </csd:requestParams>

    return csr_proc:process_updating_CSR_stored_results($csd_webconf:db, $doc,$requestParams)
    ,
    csd_webui:redirect_out(("/CSD/duplicates/", $doc_name , "/manage/" ,$entityID ))
  )

};

declare updating
  %rest:path("/CSD/duplicates/{$doc_name}/remove/{$entityID}/{$masterID}")
  %rest:GET
  %output:method("xhtml")
  function page:remove_duplicate($doc_name,$entityID,$masterID)
{
  (
    let $doc := csd_dm:open_document($csd_webconf:db,$doc_name)
    let $requestParams :=
      <csd:requestParams function="urn:openhie.org:openinfoman:delete_duplicate"  resource="{$doc_name}" base_url="{csd_webui:generateURL()}">
	<masterEntity entityID="{$masterID}"/>
	<duplicateEntity entityID="{$entityID}"/>
      </csd:requestParams>

    return csr_proc:process_updating_CSR_stored_results($csd_webconf:db, $doc,$requestParams)
    ,
    csd_webui:redirect_out(("/CSD/duplicates/", $doc_name, "/manage/" , $entityID ))
  )

};

declare updating
  %rest:path("/CSD/duplicates/{$doc_name}/removePotential/{$entityID}/{$masterID}")
  %rest:GET
  %output:method("xhtml")
  function page:remove_potential_duplicate($doc_name,$entityID,$masterID)
{
  (
    let $doc := csd_dm:open_document($csd_webconf:db,$doc_name)
    let $requestParams :=
      <csd:requestParams function="urn:openhie.org:openinfoman:delete_potential_duplicate"  resource="{$doc_name}" base_url="{csd_webui:generateURL()}">
	<masterEntity entityID="{$masterID}"/>
	<duplicateEntity entityID="{$entityID}"/>
      </csd:requestParams>

    return csr_proc:process_updating_CSR_stored_results($csd_webconf:db, $doc,$requestParams)
    ,
    csd_webui:redirect_out(("/CSD/duplicates/", $doc_name, "/manage/"  , $entityID ))
  )

};

declare
  %rest:path("/CSD/duplicates/{$doc_name}/manage/{$entityID}")
  %rest:GET
  %output:method("xhtml")
  function page:manage($doc_name,$entityID)
{
  let $doc := csd_dm:open_document($csd_webconf:db,$doc_name)
  let $entityObj :=  ($doc/csd:CSD/*/*[@entityID = $entityID])[1]
  let $entity := local-name($entityObj)
  let $entities:=
    switch($entity)
    case "provider" return $doc/csd:CSD/csd:providerDirectory/csd:provider
    case "facility" return $doc/csd:CSD/csd:facilityDirectory/csd:facility
    case "organization" return $doc/csd:CSD/csd:organizationDirectory/csd:organization
    case "service" return $doc/csd:CSD/csd:serviceDirectory/csd:service
    default return ()

  let $url := csd_webui:generateURL(("CSD/directory", $doc_name, "get", $entity , $entityID))
  let $name :=
	  if (local-name($entityObj) = 'provider')
	  then (($entityObj/csd:demographic/csd:name/csd:commonName)[1])/text()
   	  else $entityObj/csd:primaryName/text()

  let $dlist :=

      {
	for $dup in $entities[csd:otherID[@assigningAuthorityName='urn:openhie.org:openinfoman' and @code='duplicate' and text() = $entityID]]
	let $did := string($dup/@entityID)
	let $dname :=
	  if (local-name($entityObj) = 'provider')
	  then (($dup/csd:demographic/csd:name/csd:commonName)[1])/text()
   	  else $dup/csd:primaryName/text()
	let $durl := csd_webui:generateURL(("CSD/directory/", $doc_name, "get", $entity , $did))
	return

Record duplicated by {$dname} [{$did}]

      }

  let $elist :=

      {
	for $edup_id in $entityObj/csd:otherID[@assigningAuthorityName='urn:openhie.org:openinfoman' and @code='duplicate']
	let $eid := $edup_id/text()
	let $e := $entities[@entityID = $eid]
	let $ename :=
	  if (local-name($e) = 'provider')
	  then (($e/csd:demographic/csd:name/csd:commonName)[1])/text()
	  else $e/csd:primaryName/text()
	let $eurl := csd_webui:generateURL(("/CSD/directory/", $doc_name, "get", $entity ,  $eid))
	return

Duplicates record  {$ename} [{$eid}]

      }

  let $plist :=

      {
	for $pdup_id in $entityObj/csd:otherID[@assigningAuthorityName='urn:openhie.org:openinfoman' and @code='potential-duplicate']
	let $pid := $pdup_id/text()
	let $e := $entities[@entityID = $pid]
	let $ename :=
	  if (local-name($e) = 'provider')
	  then (($e/csd:demographic/csd:name/csd:commonName)[1])/text()
	  else $e/csd:primaryName/text()
	let $purl := csd_webui:generateURL(("CSD/directory", $doc_name, "get", $entity ,  $pid)		  )
	let $rurl := csd_webui:generateURL(( "CSD/duplicates", $doc_name ,"removePotential" ,  $entityID , $pid))
	let $murl := csd_webui:generateURL(( "CSD/duplicates", $doc_name ,"mark" ,  $entityID , $pid))
	return

	    Potential duplicate with {$ename} [{$pid}]

Remove potential duplicate

Mark as duplicate

      }

  let $content :=

      Record for {$name} [{$entityID}]

Records which duplicate this record

      {$dlist}

Records which this record duplicates

      {$elist}

Manage potential duplicate information for this record

      {$plist}

Mark this record as a duplicate

      <form  action="/CSD/duplicates/{$doc_name}/mark/{$entityID}">
        CSD Entity ID of Master Record:
	<input name='masterID'/>
	<input type='submit' value='Mark Duplicate'/>
      </form>

Mark this record as a potential duplicate

      <form  action="/CSD/duplicates/{$doc_name}/markPotential/{$entityID}">
        CSD Entity ID of Master Record:
	<input name='masterID'/>
	<input type='submit' value='Mark Duplicate'/>
      </form>

	List {$entity}  information for {$doc_name}

	List {$entity} duplicate information for {$doc_name}

	List {$entity}  potential duplicate information for {$doc_name}

  return csd_webui:wrapper($content)
};

declare
  %rest:path("/CSD/duplicates/{$doc_name}/list/{$entity}")
  %rest:GET
  %output:method("xhtml")
  %rest:query-param("page", "{$page}", 0)
  function page:list($doc_name,$entity,$page)
{
  let $doc := csd_dm:open_document($csd_webconf:db,$doc_name)
  let $entities:=
    switch($entity)
    case "provider" return $doc/csd:CSD/csd:providerDirectory/csd:provider
    case "facility" return $doc/csd:CSD/csd:facilityDirectory/csd:facility
    case "organization" return $doc/csd:CSD/csd:organizationDirectory/csd:organization
    case "service" return $doc/csd:CSD/csd:serviceDirectory/csd:service
    default return ()

  let $first := $page * 50 + 1
  let $last := ($page +1) * 50
  let $p_entities := $entities[position() >= $first and position() <= $last]

  let $list :=

      {
	for $e in $p_entities
	let $url := csd_webui:generateURL(( "/CSD/duplicates", $doc_name ,"manage" , string($e/@entityID)))
	let $ename :=
	  if (local-name($e) = 'provider')
	  then (($e/csd:demographic/csd:name/csd:commonName)[1])/text()
	  else $e/csd:primaryName/text()
	return
Manage {$ename} [{string($e/@entityID)}]

      }

  let $next := csd_webui:generateURL(( "CSD/duplicates", $doc_name ,"list" , concat( $entity , "?page=" , ($page +1))))
  let $prev := csd_webui:generateURL(( "CSD/duplicates", $doc_name ,"list" , concat($entity , "?page=" , ($page -1))))
  let $content :=

Records

      {$list}

      { if (($page) >= 1 ) then   Previous Page else () }
      Next Page

  return csd_webui:wrapper($content)
};

declare
  %rest:path("/CSD/duplicates/{$doc_name}/list-dup/{$entity}")
  %rest:GET
  %output:method("xhtml")
  %rest:query-param("page", "{$page}", 0)
  function page:duplicate_list($doc_name,$entity,$page)
{
  let $doc := csd_dm:open_document($csd_webconf:db,$doc_name)
  let $entities:=
    switch($entity)
    case "provider" return $doc/csd:CSD/csd:providerDirectory/csd:provider
    case "facility" return $doc/csd:CSD/csd:facilityDirectory/csd:facility
    case "organization" return $doc/csd:CSD/csd:organizationDirectory/csd:organization
    case "service" return $doc/csd:CSD/csd:serviceDirectory/csd:service
    default return ()

  let $first := $page * 50 + 1
  let $last := ($page +1) * 50
  let $p_entities := $entities[csd:otherID[@assigningAuthorityName='urn:openhie.org:openinfoman' and @code='duplicate']][position() >= $first and position() <= $last]

  let $list :=

      {
	for $e in $p_entities
	let $url := csd_webui:generateURL( ("CSD/duplicates", $doc_name ,"manage" , string($e/@entityID)))
	let $ename :=
	  if (local-name($e) = 'provider')
	  then (($e/csd:demographic/csd:name/csd:commonName)[1])/text()
	  else $e/csd:primaryName/text()
	return
Manage {$ename} [{string($e/@entityID)}]

      }

  let $next := csd_webui:generateURL(( "CSD/duplicates", $doc_name ,"list-dup" , concat($entity , "?page=" , ($page +1))))
  let $prev := csd_webui:generateURL(( "CSD/duplicates", $doc_name ,"list-dup" , concat($entity , "?page=" , ($page -1))))
  let $content :=

Records With Duplicates

      {$list}

      { if (($page) >= 1 ) then   Previous Page else () }
      Next Page

  return csd_webui:wrapper($content)
};

declare
  %rest:path("/CSD/duplicates/{$doc_name}/list-pot-dup/{$entity}")
  %rest:GET
  %output:method("xhtml")
  %rest:query-param("page", "{$page}", 0)
  function page:potential_duplicate_list($doc_name,$entity,$page)
{
  let $doc := csd_dm:open_document($csd_webconf:db,$doc_name)
  let $entities:=
    switch($entity)
    case "provider" return $doc/csd:CSD/csd:providerDirectory/csd:provider
    case "facility" return $doc/csd:CSD/csd:facilityDirectory/csd:facility
    case "organization" return $doc/csd:CSD/csd:organizationDirectory/csd:organization
    case "service" return $doc/csd:CSD/csd:serviceDirectory/csd:service
    default return ()

  let $first := $page * 50 + 1
  let $last := ($page +1) * 50
  let $p_entities := $entities[csd:otherID[@assigningAuthorityName='urn:openhie.org:openinfoman' and @code='potential-duplicate']][position() >= $first and position() <= $last]

  let $list :=

      {
	for $e in $p_entities
	let $url := csd_webui:generateURL(("/CSD/duplicates/", $doc_name ,"/manage/" , string($e/@entityID)))
	let $ename :=
	  if (local-name($e) = 'provider')
	  then (($e/csd:demographic/csd:name/csd:commonName)[1])/text()
	  else $e/csd:primaryName/text()
	return
Manage {$ename} [{string($e/@entityID)}]

      }

  let $next := csd_webui:generateURL(( "/CSD/duplicates/", $doc_name ,"/list-pot-dup/" , concat($entity , "?page=" , ($page +1))))
  let $prev := csd_webui:generateURL(( "/CSD/duplicates/", $doc_name ,"/list-pot-dup/" , concat($entity , "?page=" , ($page -1))))
  let $content :=

Records With Potential Duplicates

      {$list}

      { if (($page) >= 1 ) then   Previous Page else () }
      Next Page

  return csd_webui:wrapper($content)
};

declare
  %rest:path("/CSD/duplicates/{$doc_name}/{$entity}")
  %rest:GET
  %output:method("xhtml")
  function page:duplicate_doc_entity($doc_name,$entity)
{
  let $pot := concat( "/CSD/duplicates/", $doc_name ,"/list-pot-dup/" , $entity)
  let $dup := concat( "/CSD/duplicates/", $doc_name ,"/list-dup/" , $entity)
  let $all := concat( "/CSD/duplicates/", $doc_name ,"/list/" , $entity)
  let $content :=

Manage {$entity} duplicate information on {$doc_name}

	List {$entity}  information for {$doc_name}

	List {$entity} duplicate information for {$doc_name}

	List {$entity}  potential duplicate information for {$doc_name}

  return csd_webui:wrapper($content)
};

declare
  %rest:path("/CSD/duplicates/{$doc_name}")
  %rest:GET
  %output:method("xhtml")
  function page:duplicate_doc($doc_name)
{
  let $content :=

Manage duplicate information for {$doc_name}

      {
	for $entity in ('provider','facility','organization','service')
	return

	    Manage {$entity} information

      }

  return csd_webui:wrapper($content)
};

declare
  %rest:path("/CSD/duplicates")
  %rest:GET
  %output:method("xhtml")
  function page:duplicate()
{
  let $content :=

Manage duplicate information on selected document

      {
	for $doc_name in csd_dm:registered_documents($csd_webconf:db)
	return

	    Manage {$doc_name} information

      }

  return csd_webui:wrapper($content)
};