Fixed error when there are no feeds

Fixed error when there are no feeds

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

declare namespace atom="http://www.w3.org/2005/Atom";
<service xmlns="http://purl.org/atom/app#">
  {
   if (/atom:feed)
   then
   <workspace title="{/atom:feed/atom:title}">
   {
     "
",
     let $current := substring-before(base-uri(/atom:feed),'/.feed.atom'),
         $current-path := substring-after($current,'/db')
        for $i in (collection($current)/atom:feed)
           let $path :=  substring-after(substring-before(base-uri($i),'/.feed.atom'),'/db')
              return ( <collection title="{$i/atom:title}" href="/atom/edit{$path}">
                         <accept>text/*,image/*,application/*</accept>
                       </collection>,
                       "
"
                     )
   }
   </workspace>
   else ()
  }
</service>

declare namespace atom="http://www.w3.org/2005/Atom";
<service xmlns="http://purl.org/atom/app#">
   <workspace title="{/atom:feed/atom:title}">
   {
     "
",
     let $current := substring-before(base-uri(/atom:feed),'/.feed.atom'),
         $current-path := substring-after($current,'/db')
        for $i in (collection($current)/atom:feed)
           let $path :=  substring-after(substring-before(base-uri($i),'/.feed.atom'),'/db')
              return ( <collection title="{$i/atom:title}" href="/atom/edit{$path}">
                         <accept>text/*,image/*,application/*</accept>
                       </collection>,
                       "
"
                     )
   }
   </workspace>
</service>


All XQTS tests can now be performed without crashing eXist

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

declare namespace xqts="http://exist-db.org/xquery/xqts";
declare namespace catalog="http://www.w3.org/2005/02/query-test-XQTSCatalog";

declare namespace props="java:java.io.File";

import module namespace util="http://exist-db.org/xquery/util";
import module namespace xdb="http://exist-db.org/xquery/xmldb";
import module namespace xdiff="http://exist-db.org/xquery/xmldiff"
at "java:org.exist.xquery.modules.xmldiff.XmlDiffModule";
import module namespace request="http://exist-db.org/xquery/request";

(:~ ----------------------------------------------------------------------------------------
     W3C XQuery Test Suite

     This is the main module for running the XQTS on eXist. You can either
     run the whole test suite, a specific test group or a single test case.

     Setup:

     * Make sure the XmlDiff module is registered in conf.xml

     * Edit config.xml and change basedir to point to the directory into
     which you unzipped the XQTS sources. Note: it needs to be an URI.

     * Create a collection /db/XQTS in the database.

     * From the XQTS directory, upload XQTSCatalog.xml into the created
     collection.

     * Upload the "TestSources" directory so the source docs can be found
     in /db/XQTS/TestSources.

     * Run this script with the client.
     ------------------------------------------------------------------------------------------- :)
declare variable $xqts:CONFIG { xqts:initialize() };
declare variable $xqts:XQTS_HOME { xqts:path-to-uri($xqts:CONFIG/basedir/text()) };

declare function xqts:initialize() as element() {
    let $home := util:system-property("exist.home")
    let $path := concat($home, "/webapp/xqts")
    let $collection := xdb:create-collection("/db", "XQTS")
    let $config0 := doc("/db/XQTS")/config
    let $config :=
        if ($config0) then
            $config0
        else
            let $stored := xdb:store-files-from-pattern("/db/XQTS", $path, "*.xml", "text/xml")
            return
                doc("/db/XQTS/config.xml")/config
    let $xqtsHome := $config/basedir/text()
    let $catalog0 := doc("/db/XQTS/XQTSCatalog.xml")
    let $catalog :=
        if ($catalog0) then $catalog0
        else
            xdb:store($collection, "XQTSCatalog.xml",
                xs:anyURI(xqts:path-to-uri(concat($xqtsHome, "XQTSCatalog.xml"))))
    let $sources0 := collection("/db/XQTS/TestSources")
    let $sources :=
        if ($sources0) then
            $sources0
        else
            let $sourceCol := xdb:create-collection("/db/XQTS", "TestSources")
            return
                xdb:store-files-from-pattern($sourceCol, concat($xqtsHome, "TestSources"), "*.xml", "text/xml")
    return
        $config
};

declare function xqts:path-to-uri($path as xs:string) as xs:string {
        if (starts-with($path, "/")) then
            concat("file://", $path)
        else
            concat("file:///", $path)
};

declare function xqts:create-progress-file($testCount as xs:int) as empty() {
    let $results := xdb:store("/db/XQTS", "progress.xml",
        <progress total="{$testCount}" done="0" failed="0" passed="0"/>)
    return ()
};

declare function xqts:report-progress($test-case as element()) as empty() {
    let $result := string($test-case/@result)
    let $progress := doc("/db/XQTS/progress.xml")/progress
    let $counter := $progress/@done
    return (
        update value $counter with xs:int($counter + 1),
        if ($result eq 'fail') then
            update value $progress/@failed with xs:int($progress/@failed + 1)
        else
            update value $progress/@passed with xs:int($progress/@passed + 1)
    )
};

declare function xqts:create-collections($group as element(catalog:test-group)) as node() {
    let $rootColl := xdb:create-collection("/db/XQTS", "test-results")
    let $ancestors := reverse(($group/ancestor::catalog:test-group, $group))
    let $collection := xqts:create-collections($rootColl, $ancestors, "/db/XQTS/test-results")
    let $results := xdb:store($collection, "results.xml", <test-result failed="0" passed="0"/>)
    return
        doc($results)
};

declare function xqts:create-collections($parent as object,
    $pathElements as element()+, $currentPath as xs:string)
as object {
    let $next := $pathElements[last()]
    let $remainder := subsequence($pathElements, 1, count($pathElements) - 1)
    let $newColl := xdb:create-collection($parent, $next/@name)
    return
        if ($remainder) then
            xqts:create-collections($newColl, $remainder, concat($currentPath, "/", $next/@name))
        else
            $newColl
};

declare function xqts:get-query($case as element(catalog:test-case)) {
   let $query-name := $case//catalog:query/@name
   let $path := concat( $xqts:XQTS_HOME, "Queries/XQuery/", $case/@FilePath, $query-name, ".xq" )
   let $xq-string := util:file-read($path)
   return $xq-string
};

declare function xqts:print-result($test-name as xs:string, $passed as xs:boolean, $query as xs:string,
    $result as item()*, $expected as item()*, $case as element(catalog:test-case)) as element() {
    <test-case name="{$test-name}" result="{if ($passed) then 'pass' else 'fail'}">
    {
        if (not($passed)) then (
            <result>{$result}</result>,
            if ($expected instance of element() and count($expected/*) > 10) then
            	<expected truncated="">{$expected/*[position() < 10]}</expected>
            else
                <expected>{$expected}</expected>,
            (: element {$case/catalog:input-file/@variable} { xqts:getInputValue($case) }, :)
            <query>{$query}</query>
        ) else ()
    }
    </test-case>
};

declare function xqts:normalize-text($result as item()*) as xs:string {
    let $str := string-join(for $i in $result return string($i), " ")
    return
        (: Remove leading and trailing whitespace :)
        replace(replace($str, "^\s+", ""), "\s+$", "")
};

declare function xqts:check-output($query as xs:string, $result as item()*, $case as element(catalog:test-case)) {
    let $output := $case/catalog:output-file[last()]
    return
        (: Expected an error, but got a result :)
        if (exists($case/catalog:expected-error)) then
            <test-case name="{$case/@name}" result="fail">
                   <expected-error>{$case/catalog:expected-error/text()}</expected-error>
                   <query>{$query}</query>
            </test-case>
        (: Comparison method: "Text" :)
        else if ($output/@compare eq "Text") then
            let $text := util:file-read(concat($xqts:XQTS_HOME, "ExpectedTestResults/", $case/@FilePath,
                "/", $output/text()))
            let $test := xqts:normalize-text($text) eq xqts:normalize-text($result)
            return
                xqts:print-result($case/@name, $test, $query, $result, $text, $case)
        (: Comparison method: "XML" :)
        else if ($output/@compare eq "XML") then
            util:catch("java.lang.Exception",
                let $filePath := concat($xqts:XQTS_HOME, "ExpectedTestResults/", $case/@FilePath,
                    $output/text())
                let $expected := doc(xdb:store("/db", "temp.xml", xs:anyURI($filePath), "text/xml"))
                let $test := xdiff:compare($expected, $result)
                return
                    xqts:print-result($case/@name, $test, $query, $result, $expected, $case),
                (: Handle unexpected exceptions :)
                <test-case name="{$case/@name}" result="fail">
                   <exception>Exception while loading expected result: {$util:exception-message}</exception>
                   <query>{$query}</query>
                </test-case>
            )
        (: Comparison method: "Fragment" :)
        else if ($output/@compare eq "Fragment") then
            util:catch("java.lang.Exception",
                let $filePath := concat($xqts:XQTS_HOME, "ExpectedTestResults/", $case/@FilePath, $output/text())
                let $expectedFrag := util:file-read($filePath)
                let $xmlFrag := concat("<f>", $expectedFrag, "</f>")
                let $log := util:log("DEBUG", ("Frag stored: ", $xmlFrag))
                let $expected := doc(xdb:store("/db", "temp.xml", $xmlFrag, "text/xml"))
                let $test := xdiff:compare($expected, <f>{$result}</f>)
                return
                    xqts:print-result($case/@name, $test, $query, $result, $expected, $case),
                (: Handle unexpected exceptions :)
                <test-case name="{$case/@name}" result="fail">
                   <exception>Exception while loading expected result fragment: {$util:exception-message}</exception>
                   <query>{$query}</query>
                </test-case>
            )
        (: Comparison method: "Inspect" :)
        (: A text compare is sufficient in many test cases :)
        else if ($output/@compare eq "Inspect") then
            let $text := util:file-read(concat($xqts:XQTS_HOME, "ExpectedTestResults/", $case/@FilePath,
                "/", $output/text()))
            let $test := xqts:normalize-text($text) eq xqts:normalize-text($result)
            return
                xqts:print-result($case/@name, $test, $query, $result, $text, $case)

        (: Don't know how to compare :)
        else
            <error test="{$case/@name}">Unknown comparison method: {$output/@compare}.</error>
};

declare function xqts:run-test-case( $case as element(catalog:test-case)) as item()* {
   let $query := xqts:get-query($case)
   let $context :=
       <static-context>
       {
           for $input in $case/catalog:input-file
           return
               <variable name="{$input/@variable}">{xqts:get-input-value($input)}</variable>
       }
       </static-context>
   let $result :=
       util:catch("java.lang.Exception",
           let $result :=
               util:eval-with-context($query, $context, false())
           return
               xqts:check-output($query, $result, $case),
           if ($case//catalog:expected-error) then
               <test-case name="{$case/@name}" result="pass">
                   <exception>{$util:exception-message}</exception>
                   <expected-error>{$case//catalog:expected-error/text()}</expected-error>
                   <query>{$query}</query>
               </test-case>
           else
               <test-case name="{$case/@name}" result="fail">
                   <exception>{$util:exception-message}</exception>
                   <query>{$query}</query>
               </test-case>
       )
   return $result
};

declare function xqts:finish($result as element()) as empty() {
    let $passed := count($result//test-case[@result = 'pass'])
    let $failed := count($result//test-case[@result = 'fail'])
    return (
        update value $result/@passed with xs:int($passed),
        update value $result/@failed with xs:int($failed)
    )
};

declare function xqts:run-single-test-case($case as element(catalog:test-case),
    $resultRoot as element()?) as empty() {
    let $result := xqts:run-test-case($case)
    return (
        update insert $result into $resultRoot,
        let $added := $resultRoot/test-case[@name = $case/@name]
        return
            if ($added) then xqts:report-progress($added)
            else ()
    )
};

declare function xqts:run-test-group($group as element(catalog:test-group)) as empty() {
    (: Create the collection hierarchy for this group and get the results.xml doc to
        append to. :)
    let $resultsDoc := xqts:create-collections($group)
    let $tests := $group/catalog:test-case
(:
[
    	not(starts-with(@name, 'Constr-inscope-10')) and
    	not(starts-with(@name, 'Constr-inscope-12')) and
    	not(starts-with(@name, 'Constr-namespace-22'))
]
:)
    return (
        (: Execute the test cases :)
        for $test in $tests
        let $log := util:log("DEBUG", ("Running test case: ", string($test/@name)))
        return
            xqts:run-single-test-case($test, $resultsDoc/test-result),
        if ($tests) then
            xqts:finish($resultsDoc/test-result)
        else
            xdb:remove(util:collection-name($resultsDoc), util:document-name($resultsDoc)),
        (: Execute tests in child groups :)
        for $childGroup in $group/catalog:test-group
        let $log := util:log("DEBUG", ("Entering group: ", string($childGroup/@name)))
        return
            xqts:run-test-group($childGroup)
    )
};

declare function xqts:test-single($name as xs:string) as element() {
    let $test := //catalog:test-case[@name = $name]
    return
        if ($test) then
            let $resultsDoc := xqts:create-collections($test/parent::catalog:test-group)
            let $dummy := xqts:run-single-test-case($test, $resultsDoc/test-result)
            return
                $resultsDoc/test-result
        else
            <error>Test case not found: {$name}.</error>
};

declare function xqts:test-group($groupName as xs:string) as empty() {
    let $group := //catalog:test-group[@name = $groupName]
    return (
        xqts:create-progress-file(count($group//catalog:test-case)),
        xqts:run-test-group($group)
    )
};

declare function xqts:test-all() as empty() {
    for $test in /catalog:test-suite/catalog:test-group
    return
        xqts:test-group($test/@name)
};

declare function xqts:get-input-value($input as element(catalog:input-file)) as item()* {
   if ($input eq "emptydoc") then
       ()
   else (
       let $source := root($input)//catalog:source[@ID = $input/text()]
       return
           if (empty($source)) then
               concat("no input found: ", $input/text())
           else
               doc(concat("/db/XQTS/", $source/@FileName))
   )
};

declare function xqts:overall-result() {
    let $passed := count(//test-case[@result = "pass"])
    let $failed := count(//test-case[@result = "fail"])
    return
        <test-result failed="{$failed}" passed="{$passed}"
            percentage="{$passed div ($passed + $failed)}"/>
};

let $group := request:get-parameter('group', ())
return
    if ($group) then
        xqts:test-group($group)
    else
        ()

declare namespace xqts="http://exist-db.org/xquery/xqts";
declare namespace catalog="http://www.w3.org/2005/02/query-test-XQTSCatalog";

declare namespace props="java:java.io.File";

import module namespace util="http://exist-db.org/xquery/util";
import module namespace xdb="http://exist-db.org/xquery/xmldb";
import module namespace xdiff="http://exist-db.org/xquery/xmldiff"
at "java:org.exist.xquery.modules.xmldiff.XmlDiffModule";
import module namespace request="http://exist-db.org/xquery/request";

(:~ ----------------------------------------------------------------------------------------
     W3C XQuery Test Suite

     This is the main module for running the XQTS on eXist. You can either
     run the whole test suite, a specific test group or a single test case.

     Setup:

     * Make sure the XmlDiff module is registered in conf.xml

     * Edit config.xml and change basedir to point to the directory into
     which you unzipped the XQTS sources. Note: it needs to be an URI.

     * Create a collection /db/XQTS in the database.

     * From the XQTS directory, upload XQTSCatalog.xml into the created
     collection.

     * Upload the "TestSources" directory so the source docs can be found
     in /db/XQTS/TestSources.

     * Run this script with the client.
     ------------------------------------------------------------------------------------------- :)
declare variable $xqts:CONFIG { xqts:initialize() };
declare variable $xqts:XQTS_HOME { xqts:path-to-uri($xqts:CONFIG/basedir/text()) };

declare function xqts:initialize() as element() {
    let $home := util:system-property("exist.home")
    let $path := concat($home, "/webapp/xqts")
    let $collection := xdb:create-collection("/db", "XQTS")
    let $config0 := doc("/db/XQTS")/config
    let $config :=
        if ($config0) then
            $config0
        else
            let $stored := xdb:store-files-from-pattern("/db/XQTS", $path, "*.xml", "text/xml")
            return
                doc("/db/XQTS/config.xml")/config
    let $xqtsHome := $config/basedir/text()
    let $catalog0 := doc("/db/XQTS/XQTSCatalog.xml")
    let $catalog :=
        if ($catalog0) then $catalog0
        else
            xdb:store($collection, "XQTSCatalog.xml",
                xs:anyURI(xqts:path-to-uri(concat($xqtsHome, "XQTSCatalog.xml"))))
    let $sources0 := collection("/db/XQTS/TestSources")
    let $sources :=
        if ($sources0) then
            $sources0
        else
            let $sourceCol := xdb:create-collection("/db/XQTS", "TestSources")
            return
                xdb:store-files-from-pattern($sourceCol, concat($xqtsHome, "TestSources"), "*.xml", "text/xml")
    return
        $config
};

declare function xqts:path-to-uri($path as xs:string) as xs:string {
        if (starts-with($path, "/")) then
            concat("file://", $path)
        else
            concat("file:///", $path)
};

declare function xqts:create-progress-file($testCount as xs:int) as empty() {
    let $results := xdb:store("/db/XQTS", "progress.xml",
        <progress total="{$testCount}" done="0" failed="0" passed="0"/>)
    return ()
};

declare function xqts:report-progress($test-case as element()) as empty() {
    let $result := string($test-case/@result)
    let $progress := doc("/db/XQTS/progress.xml")/progress
    let $counter := $progress/@done
    return (
        update value $counter with xs:int($counter + 1),
        if ($result eq 'fail') then
            update value $progress/@failed with xs:int($progress/@failed + 1)
        else
            update value $progress/@passed with xs:int($progress/@passed + 1)
    )
};

declare function xqts:create-collections($group as element(catalog:test-group)) as node() {
    let $rootColl := xdb:create-collection("/db/XQTS", "test-results")
    let $ancestors := reverse(($group/ancestor::catalog:test-group, $group))
    let $collection := xqts:create-collections($rootColl, $ancestors, "/db/XQTS/test-results")
    let $results := xdb:store($collection, "results.xml", <test-result failed="0" passed="0"/>)
    return
        doc($results)
};

declare function xqts:create-collections($parent as object,
    $pathElements as element()+, $currentPath as xs:string)
as object {
    let $next := $pathElements[last()]
    let $remainder := subsequence($pathElements, 1, count($pathElements) - 1)
    let $newColl := xdb:create-collection($parent, $next/@name)
    return
        if ($remainder) then
            xqts:create-collections($newColl, $remainder, concat($currentPath, "/", $next/@name))
        else
            $newColl
};

declare function xqts:get-query($case as element(catalog:test-case)) {
   let $query-name := $case//catalog:query/@name
   let $path := concat( $xqts:XQTS_HOME, "Queries/XQuery/", $case/@FilePath, $query-name, ".xq" )
   let $xq-string := util:file-read($path)
   return $xq-string
};

declare function xqts:print-result($test-name as xs:string, $passed as xs:boolean, $query as xs:string,
    $result as item()*, $expected as item()*, $case as element(catalog:test-case)) as element() {
    <test-case name="{$test-name}" result="{if ($passed) then 'pass' else 'fail'}">
    {
        if (not($passed)) then (
            <result>{$result}</result>,
            if ($expected instance of element() and count($expected/*) > 10) then
            	<expected truncated="">{$expected/*[position() < 10]}</expected>
            else
                <expected>{$expected}</expected>,
            (: element {$case/catalog:input-file/@variable} { xqts:getInputValue($case) }, :)
            <query>{$query}</query>
        ) else ()
    }
    </test-case>
};

declare function xqts:normalize-text($result as item()*) as xs:string {
    let $str := string-join(for $i in $result return string($i), " ")
    return
        (: Remove leading and trailing whitespace :)
        replace(replace($str, "^\s+", ""), "\s+$", "")
};

declare function xqts:check-output($query as xs:string, $result as item()*, $case as element(catalog:test-case)) {
    let $output := $case/catalog:output-file[last()]
    return
        (: Expected an error, but got a result :)
        if (exists($case/catalog:expected-error)) then
            <test-case name="{$case/@name}" result="fail">
                   <expected-error>{$case/catalog:expected-error/text()}</expected-error>
                   <query>{$query}</query>
            </test-case>
        (: Comparison method: "Text" :)
        else if ($output/@compare eq "Text") then
            let $text := util:file-read(concat($xqts:XQTS_HOME, "ExpectedTestResults/", $case/@FilePath,
                "/", $output/text()))
            let $test := xqts:normalize-text($text) eq xqts:normalize-text($result)
            return
                xqts:print-result($case/@name, $test, $query, $result, $text, $case)
        (: Comparison method: "XML" :)
        else if ($output/@compare eq "XML") then
            util:catch("java.lang.Exception",
                let $filePath := concat($xqts:XQTS_HOME, "ExpectedTestResults/", $case/@FilePath,
                    $output/text())
                let $expected := doc(xdb:store("/db", "temp.xml", xs:anyURI($filePath), "text/xml"))
                let $test := xdiff:compare($expected, $result)
                return
                    xqts:print-result($case/@name, $test, $query, $result, $expected, $case),
                (: Handle unexpected exceptions :)
                <test-case name="{$case/@name}" result="fail">
                   <exception>Exception while loading expected result: {$util:exception-message}</exception>
                   <query>{$query}</query>
                </test-case>
            )
        (: Comparison method: "Fragment" :)
        else if ($output/@compare eq "Fragment") then
            util:catch("java.lang.Exception",
                let $filePath := concat($xqts:XQTS_HOME, "ExpectedTestResults/", $case/@FilePath, $output/text())
                let $expectedFrag := util:file-read($filePath)
                let $xmlFrag := concat("<f>", $expectedFrag, "</f>")
                let $log := util:log("DEBUG", ("Frag stored: ", $xmlFrag))
                let $expected := doc(xdb:store("/db", "temp.xml", $xmlFrag, "text/xml"))
                let $test := xdiff:compare($expected, <f>{$result}</f>)
                return
                    xqts:print-result($case/@name, $test, $query, $result, $expected, $case),
                (: Handle unexpected exceptions :)
                <test-case name="{$case/@name}" result="fail">
                   <exception>Exception while loading expected result fragment: {$util:exception-message}</exception>
                   <query>{$query}</query>
                </test-case>
            )
        (: Comparison method: "Inspect" :)
        (: A text compare is sufficient in many test cases :)
        else if ($output/@compare eq "Inspect") then
            let $text := util:file-read(concat($xqts:XQTS_HOME, "ExpectedTestResults/", $case/@FilePath,
                "/", $output/text()))
            let $test := xqts:normalize-text($text) eq xqts:normalize-text($result)
            return
                xqts:print-result($case/@name, $test, $query, $result, $text, $case)

        (: Don't know how to compare :)
        else
            <error test="{$case/@name}">Unknown comparison method: {$output/@compare}.</error>
};

declare function xqts:run-test-case( $case as element(catalog:test-case)) as item()* {
   let $query := xqts:get-query($case)
   let $context :=
       <static-context>
       {
           for $input in $case/catalog:input-file
           return
               <variable name="{$input/@variable}">{xqts:get-input-value($input)}</variable>
       }
       </static-context>
   let $result :=
       util:catch("java.lang.Exception",
           let $result :=
               util:eval-with-context($query, $context, false())
           return
               xqts:check-output($query, $result, $case),
           if ($case//catalog:expected-error) then
               <test-case name="{$case/@name}" result="pass">
                   <exception>{$util:exception-message}</exception>
                   <expected-error>{$case//catalog:expected-error/text()}</expected-error>
                   <query>{$query}</query>
               </test-case>
           else
               <test-case name="{$case/@name}" result="fail">
                   <exception>{$util:exception-message}</exception>
                   <query>{$query}</query>
               </test-case>
       )
   return $result
};

declare function xqts:finish($result as element()) as empty() {
    let $passed := count($result//test-case[@result = 'pass'])
    let $failed := count($result//test-case[@result = 'fail'])
    return (
        update value $result/@passed with xs:int($passed),
        update value $result/@failed with xs:int($failed)
    )
};

declare function xqts:run-single-test-case($case as element(catalog:test-case),
    $resultRoot as element()?) as empty() {
    let $result := xqts:run-test-case($case)
    return (
        update insert $result into $resultRoot,
        let $added := $resultRoot/test-case[@name = $case/@name]
        return
            if ($added) then xqts:report-progress($added)
            else ()
    )
};

declare function xqts:run-test-group($group as element(catalog:test-group)) as empty() {
    (: Create the collection hierarchy for this group and get the results.xml doc to
        append to. :)
    let $resultsDoc := xqts:create-collections($group)
    let $tests := $group/catalog:test-case[
    	not(starts-with(@name, 'Constr-inscope-10')) and
    	not(starts-with(@name, 'Constr-inscope-12')) and
    	not(starts-with(@name, 'Constr-namespace-22'))
    	]
    return (
        (: Execute the test cases :)
        for $test in $tests
        let $log := util:log("DEBUG", ("Running test case: ", string($test/@name)))
        return
            xqts:run-single-test-case($test, $resultsDoc/test-result),
        if ($tests) then
            xqts:finish($resultsDoc/test-result)
        else
            xdb:remove(util:collection-name($resultsDoc), util:document-name($resultsDoc)),
        (: Execute tests in child groups :)
        for $childGroup in $group/catalog:test-group
        let $log := util:log("DEBUG", ("Entering group: ", string($childGroup/@name)))
        return
            xqts:run-test-group($childGroup)
    )
};

declare function xqts:test-single($name as xs:string) as element() {
    let $test := //catalog:test-case[@name = $name]
    return
        if ($test) then
            let $resultsDoc := xqts:create-collections($test/parent::catalog:test-group)
            let $dummy := xqts:run-single-test-case($test, $resultsDoc/test-result)
            return
                $resultsDoc/test-result
        else
            <error>Test case not found: {$name}.</error>
};

declare function xqts:test-group($groupName as xs:string) as empty() {
    let $group := //catalog:test-group[@name = $groupName]
    return (
        xqts:create-progress-file(count($group//catalog:test-case)),
        xqts:run-test-group($group)
    )
};

declare function xqts:test-all() as empty() {
    for $test in /catalog:test-suite/catalog:test-group
    return
        xqts:test-group($test/@name)
};

declare function xqts:get-input-value($input as element(catalog:input-file)) as item()* {
   if ($input eq "emptydoc") then
       ()
   else (
       let $source := root($input)//catalog:source[@ID = $input/text()]
       return
           if (empty($source)) then
               concat("no input found: ", $input/text())
           else
               doc(concat("/db/XQTS/", $source/@FileName))
   )
};

declare function xqts:overall-result() {
    let $passed := count(//test-case[@result = "pass"])
    let $failed := count(//test-case[@result = "fail"])
    return
        <test-result failed="{$failed}" passed="{$passed}"
            percentage="{$passed div ($passed + $failed)}"/>
};

let $group := request:get-parameter('group', ())
return
    if ($group) then
        xqts:test-group($group)
    else
        ()


lets update the existing conceptual_domain, property and object_class id's

xquery version "1.0";

(: ~
 : Module Name:             edit DataElementConcept webpage and XQuery
 :
 : Module Version           3.0
 :
 : Date                     26th Aug 2009
 :
 : Copyright                The cagrid consortium
 :
 : Module overview          Creates and property and displays list
 :
 :)

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

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

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

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

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

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

declare function local:data_element_concept(
   $id as xs:string,
   $reg-auth as xs:string,
   $administrative-note as xs:string,
   $administrative-status as xs:string,
   $administered-by as xs:string,
   $submitted-by as xs:string,
   $registered-by as xs:string,
   $context-ids as xs:string*,
   $country-identifiers as xs:string*,
   $language-identifiers as xs:string*,
   $names as xs:string*,
   $definitions as xs:string*,
   $sources as xs:string*,
   $preferred as xs:string?,

   $conceptual_domain_id as xs:string?,
   $object_class_id as xs:string?,
   $property_id as xs:string?
   ) as xs:string
   {
   let $version := '0.1'

   let $object_class_uri := request:get-parameter('object_class_uri','')
   let $property_uri := request:get-parameter('property_uri','')

   let $data-identifier-oc := substring-after(lib-forms:substring-before-last($id,'-'),'-')
   let $data-identifier-pr := substring-after(lib-forms:substring-before-last($id,'-'),'-')
   let $full-identifier-oc := concat($reg-auth, '-', $data-identifier-oc, '-', $version)
   let $full-identifier-pr := concat($reg-auth, '-', $data-identifier-pr, '-', $version)
   let $data-identifier := substring-after(lib-forms:substring-before-last($id,'-'),'-')
   let $new-identifier := concat($reg-auth, '-', $data-identifier, '-', $version)

   let $content := (
           lib-make-admin-item:administration-record($administrative-note,$administrative-status,'Recorded'),
            lib-make-admin-item:custodians($administered-by,$registered-by,$submitted-by),
            lib-make-admin-item:havings(
                    $context-ids,
                    $country-identifiers,
                    $language-identifiers,
                    $names,
                    $definitions,
                    $preferred,
                    $sources),

                    element openMDR:data_element_concept_conceptual_domain {$conceptual_domain_id},
                    element openMDR:data_element_concept_object_class {$object_class_id},
                    element openMDR:data_element_concept_property {$property_id}
                    )

let $object-class :=
   (
   element openMDR:Object_Class {
        lib-make-admin-item:identifier-attributes($reg-auth,$data-identifier-oc,$version),
        lib-make-admin-item:administration-record($administrative-note,$administrative-status,'Recorded'),
        lib-make-admin-item:custodians($administered-by,$registered-by,$submitted-by),
        lib-make-admin-item:havings(
                    $context-ids,
                    $country-identifiers,
                    $language-identifiers,
                    $names,
                    $definitions,
                    $preferred,
                    $sources),
        element openMDR:reference_uri {$object_class_uri}
        }
   )

let $property :=
   (
    element openMDR:DataElementConcept {
        lib-make-admin-item:identifier-attributes($reg-auth,$data-identifier-pr,$version),
        lib-make-admin-item:administration-record($administrative-note,$administrative-status,'Recorded'),
        lib-make-admin-item:custodians($administered-by,$registered-by,$submitted-by),
        lib-make-admin-item:havings(
                    $context-ids,
                    $country-identifiers,
                    $language-identifiers,
                    $names,
                    $definitions,
                    $preferred,
                    $sources),
        element openMDR:reference_uri {$property_uri}
        }
   )

   (: compose the document :)
   let $document :=
      element openMDR:Data_Element_Concept {
            lib-make-admin-item:identifier-attributes($reg-auth,$data-identifier,$version),
            $content
           }
   let $collection := 'data_element_concept'
   let $message := lib-forms:store-document($document)

   return
   if ((
      if ($object_class_id > '')
      then 'stored'
      else lib-forms:store-document($object-class))='stored'
      )
   then (
      if ((
         if ($property_id > '')
         then 'stored'
         else lib-forms:store-document($property))='stored')
      then (
          if(lib-forms:store-document($document)='stored')
          then 'stored'
          else ( response:redirect-to(xs:anyURI(concat("login.xquery?calling_page=newDataElementConcept.xquery&","Could not store data element concept"))) )
          )
      else ( response:redirect-to(xs:anyURI(concat("login.xquery?calling_page=newDataElementConcept.xquery&","Could not store property"))) )
   )
   else ( response:redirect-to(xs:anyURI(concat("login.xquery?calling_page=newDataElementConcept.xquery&","Could not store object class"))) )

};

declare function local:input-page(
   $message as xs:string?,
   $id as xs:string,
   $reg-auth as xs:string,
   $administrative-note as xs:string,
   $administrative-status as xs:string,
   $administered-by as xs:string,
   $submitted-by as xs:string,
   $registered-by as xs:string,
   $context-ids as xs:string*,
   $country-identifiers as xs:string*,
   $language-identifiers as xs:string*,
   $names as xs:string*,
   $definitions as xs:string*,
   $sources as xs:string*,
   $preferred as xs:string?,
   $action as xs:string?,

   $conceptual_domain_id as xs:string?,
   $object_class_id as xs:string?,
   $property_id as xs:string?
   )

   {
   let $skip-name := substring-after($action,'delete naming entry')
   let $skip-name-index := if ($skip-name>'') then xs:int($skip-name) else 0

   return

                This form will allow you to Edit a DataElementConcept in the metadata repository

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

             {lib-forms:hidden-element('id',$id)}
             {lib-forms:hidden-element('updating','updating')}

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

                  Object Class URI

                     {lib-forms:find-concept-id('object_class_uri','get object class concept',request:get-parameter('object_class_uri',''))}

                   or select existing
                  {lib-forms:make-select-admin-item('object_class','object_class_id', $object_class_id)}

                  Property URI

                     {lib-forms:find-concept-id('property_uri','get property concept',request:get-parameter('property_uri',''))}

                   or select existing
                     {lib-forms:make-select-admin-item('property','property_id', $property_id)}

                  Conceptual Domain

                     {lib-forms:make-select-admin-item('conceptual_domain','conceptual_domain_id', $conceptual_domain_id)}

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

          </form>

{$message}

   };

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

Data Element Concept modified

Return to maintenance menu

Create another DataElementConcept

};

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

   session:create(),
   let $id := request:get-parameter('id','')

   let $updating := request:get-parameter('updating','')
   let $title as xs:string := "Editing DataElementConcept"
   let $element := lib-util:mdrElement("data_element_concept",$id)
   let $action := request:get-parameter('update','')

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

   let $conceptual_domain_id := request:get-parameter('conceptual_domain_id','')
   let $object_class_id := request:get-parameter('object_class_id','')
   let $property_id := request:get-parameter('property_id','')
   let $property_uri := request:get-parameter('property_uri','')
   let $object_class_uri := request:get-parameter('object_class_uri',())

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

   let $conceptual_domain_id := $element//openMDR:data_element_concept_conceptual_domain/text()
   let $log := util:log-system-err($conceptual_domain_id)

    let $object_class_id:=$element//openMDR:data_element_concept_object_class/text()
    let $log := util:log-system-err($object_class_id)

    let $property_id:=$element//openMDR:data_element_concept_property/text()
    let $log := util:log-system-err($property_id)

(:
   let $iproperty_uri := $element//openMDR:reference_uri
   let $log := util:log-system-err($iproperty_uri)

   let $iobject_class_uri := $element//openMDR:reference_uri
   let $log := util:log-system-err($iobject_class_uri)
   let $iproperty_uri := $element//openMDR:object_class_qualifier
   let $iobject_class_uri := $element//openMDR:property_qualifier

:)

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

    )

xquery version "1.0";

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

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

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

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

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

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

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

declare function local:data_element_concept(
   $id as xs:string,
   $reg-auth as xs:string,
   $administrative-note as xs:string,
   $administrative-status as xs:string,
   $administered-by as xs:string,
   $submitted-by as xs:string,
   $registered-by as xs:string,
   $context-ids as xs:string*,
   $country-identifiers as xs:string*,
   $language-identifiers as xs:string*,
   $names as xs:string*,
   $definitions as xs:string*,
   $sources as xs:string*,
   $preferred as xs:string?,

   $conceptual_domain_id as xs:string?,
   $object_class_id as xs:string?,
   $property_id as xs:string?,
   $property_uri as xs:string?,
   $object_class_uri as xs:string?
   ) as xs:string
   {
   let $version := '0.1'

(:
   let $object_class_id := request:get-parameter('object_class_id','')
   let $property_id := request:get-parameter('property_id','')
   let $conceptual_domain_id := request:get-parameter('conceptual_domain_id','')
   let $object_class_uri := request:get-parameter('object_class_uri','')
   let $property_uri := request:get-parameter('property_uri','')
:)

    let $object_class_id := substring-after(lib-forms:substring-before-last($id,'-'),'-')
    let $property_id := substring-after(lib-forms:substring-before-last($id,'-'),'-')

   let $data-identifier-oc := substring-after(lib-forms:substring-before-last($id,'-'),'-')
   let $data-identifier-pr := substring-after(lib-forms:substring-before-last($id,'-'),'-')

   let $full-identifier-oc := concat($reg-auth, '-', $data-identifier-oc, '-', $version)
   let $full-identifier-pr := concat($reg-auth, '-', $data-identifier-pr, '-', $version)

   let $data-identifier := substring-after(lib-forms:substring-before-last($id,'-'),'-')
   let $new-identifier := concat($reg-auth, '-', $data-identifier, '-', $version)

   let $content := (
           lib-make-admin-item:administration-record($administrative-note,$administrative-status,'Recorded'),
            lib-make-admin-item:custodians($administered-by,$registered-by,$submitted-by),
            lib-make-admin-item:havings(
                    $context-ids,
                    $country-identifiers,
                    $language-identifiers,
                    $names,
                    $definitions,
                    $preferred,
                    $sources),
                    (:
                    element openMDR:data_element_concept_conceptual_domain {$conceptual_domain_id},
                    element openMDR:data_element_concept_object_class
                    {
                        if ($object_class_id) then ($object_class_id) else ($full-identifier-oc)
                    },
                    element openMDR:data_element_concept_property
                    {
                        if ($property_id) then ($property_id) else ($full-identifier-pr)
                    }
                    :)

                    element openMDR:data_element_concept_conceptual_domain {$conceptual_domain_id},
                    element openMDR:data_element_concept_object_class {$object_class_id},
                    element openMDR:data_element_concept_property {$property_id}
                    )

let $object-class :=
   (
   element openMDR:Object_Class {
        lib-make-admin-item:identifier-attributes($reg-auth,$data-identifier-oc,$version),
        lib-make-admin-item:administration-record($administrative-note,$administrative-status,'Recorded'),
        lib-make-admin-item:custodians($administered-by,$registered-by,$submitted-by),
        lib-make-admin-item:havings(
                    $context-ids,
                    $country-identifiers,
                    $language-identifiers,
                    $names,
                    $definitions,
                    $preferred,
                    $sources),
        element openMDR:reference_uri {$object_class_uri}
        }
   )

let $property :=
   (
    element openMDR:DataElementConcept {
        lib-make-admin-item:identifier-attributes($reg-auth,$data-identifier-pr,$version),
        lib-make-admin-item:administration-record($administrative-note,$administrative-status,'Recorded'),
        lib-make-admin-item:custodians($administered-by,$registered-by,$submitted-by),
        lib-make-admin-item:havings(
                    $context-ids,
                    $country-identifiers,
                    $language-identifiers,
                    $names,
                    $definitions,
                    $preferred,
                    $sources),
        element openMDR:reference_uri {$property_uri}
        }
   )

   (: compose the document :)
   let $document :=
      element openMDR:Data_Element_Concept {
            lib-make-admin-item:identifier-attributes($reg-auth,$data-identifier,$version),
            $content
           }
   let $collection := 'data_element_concept'
   let $message := lib-forms:store-document($document)

   return
   if ((
      if ($object_class_id > '')
      then 'stored'
      else lib-forms:store-document($object-class))='stored'
      )
   then (
      if ((
         if ($property_id > '')
         then 'stored'
         else lib-forms:store-document($property))='stored')
      then (
          if(lib-forms:store-document($document)='stored')
          then 'stored'
          else ( response:redirect-to(xs:anyURI(concat("login.xquery?calling_page=newDataElementConcept.xquery&","Could not store data element concept"))) )
          )
      else ( response:redirect-to(xs:anyURI(concat("login.xquery?calling_page=newDataElementConcept.xquery&","Could not store property"))) )
   )
   else ( response:redirect-to(xs:anyURI(concat("login.xquery?calling_page=newDataElementConcept.xquery&","Could not store object class"))) )

};

declare function local:input-page(
   $message as xs:string?,
   $id as xs:string,
   $reg-auth as xs:string,
   $administrative-note as xs:string,
   $administrative-status as xs:string,
   $administered-by as xs:string,
   $submitted-by as xs:string,
   $registered-by as xs:string,
   $context-ids as xs:string*,
   $country-identifiers as xs:string*,
   $language-identifiers as xs:string*,
   $names as xs:string*,
   $definitions as xs:string*,
   $sources as xs:string*,
   $preferred as xs:string?,
   $action as xs:string?,

   $conceptual_domain_id as xs:string?,
   $object_class_id as xs:string?,
   $property_id as xs:string?,
   $property_uri as xs:string?,
   $object_class_uri as xs:string?
   )

   {
   let $skip-name := substring-after($action,'delete naming entry')
   let $skip-name-index := if ($skip-name>'') then xs:int($skip-name) else 0

   return

                This form will allow you to Edit a DataElementConcept in the metadata repository

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

             {lib-forms:hidden-element('id',$id)}
             {lib-forms:hidden-element('updating','updating')}

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

                  Object Class URI

                     {lib-forms:find-concept-id('object_class_uri','get object class concept',request:get-parameter('object_class_uri',''))}

                   or select existing
                  {lib-forms:make-select-admin-item('object_class','object_class_id', request:get-parameter('object_class_id',''))}

                  Property URI

                     {lib-forms:find-concept-id('property_uri','get property concept',request:get-parameter('property_uri',''))}

                   or select existing
                     {lib-forms:make-select-admin-item('property','property_id', request:get-parameter('property_id',''))}

                  Conceptual Domain

                     {lib-forms:make-select-admin-item('conceptual_domain','conceptual_domain_id', request:get-parameter('conceptual_domain_id',''))}

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

          </form>

{$message}

   };

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

Data Element Concept modified

Return to maintenance menu

Create another DataElementConcept

};

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

   session:create(),
   let $id := request:get-parameter('id','')

   let $updating := request:get-parameter('updating','')
   let $title as xs:string := "Editing DataElementConcept"
   let $element := lib-util:mdrElement("data_element_concept",$id)
   let $action := request:get-parameter('update','')

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

   (: adding next 5 lines:)
   let $conceptual_domain_id := request:get-parameter('conceptual_domain_id','')
   let $object_class_id := request:get-parameter('object_class_id','')
   let $property_id := request:get-parameter('property_id','')
   let $property_uri := request:get-parameter('property_uri','')
   let $object_class_uri := request:get-parameter('object_class_uri',())

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

   let $log := util:log-system-err($ipreferred)

   (: adding next 5 lines:)
   let $iconceptual_domain_id := $element//openMDR:data_element_concept_conceptual_domain/text()
   let $log := util:log-system-err($iconceptual_domain_id)
(:
   let $iobject_class_id := element//openMDR:data_element_concept_object_class/text()
   let $log := util:log-system-err($iobject_class_id)
:)
   let $iproperty_id := element//openMDR:data_element_concept_property/text()
   let $log := util:log-system-err($iproperty_id)

   let $iproperty_uri := string($element//openMDR:reference_uri)
   let $log := util:log-system-err($iproperty_uri)

   let $iobject_class_uri := $element//openMDR:reference_uri
   let $log := util:log-system-err($iobject_class_uri)

   (: print log testing :)
   let $log := util:log-system-err($iproperty_uri)
   let $log := util:log-system-err($iobject_class_uri)

(:
    let $iproperty_uri := $element//openMDR:object_class_qualifier
    let $iobject_class_uri := $element//openMDR:property_qualifier

    let $foo := util:log-system-out($iproperty_uri as item()*) empty()

    let $foo := util:log-system-out($iproperty_uri)
    let $bar := util:log-system-out($iobject_class_uri)
:)

   (:
    let $administered_item_name := administered-item:preferred-name($administered_item)
    let $conceptual_domain:=$administered_item//openMDR:data_element_concept_conceptual_domain
    let $object_class:=$administered_item//openMDR:data_element_concept_object_class
    let $property:=$administered_item//openMDR:data_element_concept_property
    let $object_class_qualifier:=$administered_item//openMDR:object_class_qualifier
    let $property_qualifier:=$administered_item//openMDR:property_qualifier
    let $title:=concat('Data Element Concept: ',$administered_item_name )
   :)

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

    )


fixed bug where only one sample directory could be present

(:~
: This is the Care Services Discovery stored query registry
: @version 1.0
: @see https://github.com/his-interop/openinfoman
:
:)
module namespace csd_lsd = "https://github.com/his-interop/openinfoman/csd_lsd";

declare variable $csd_lsd:base_path := "../service_directories/";

declare function csd_lsd:sample_directories() {
  let $files := file:list($csd_lsd:base_path,true(),'*.xml')
  for $file in $files
  return file:base-name($file,".xml")
};

declare function csd_lsd:get_document_names() {
  csd_lsd:get_document_name(csd_lsd:sample_directories())
};

declare function csd_lsd:get_document_name($name) {
  concat("service_directories/",$name,".xml")
};

declare function csd_lsd:get_document_source($name) {
  concat($csd_lsd:base_path, "/" , $name,".xml")
};

declare function csd_lsd:exists($db,$name) {
  db:is-xml($db,csd_lsd:get_document_name($name)) and csd_lsd:valid_doc($name)
};

declare function csd_lsd:valid_doc($name) {
  $name = csd_lsd:sample_directories()
};

declare updating function csd_lsd:load($db,$name) {
  if (not(csd_lsd:exists($db,$name)) and csd_lsd:valid_doc($name)) then
    db:add($db, csd_lsd:get_document_source($name),csd_lsd:get_document_name($name))
  else
    ()
};

declare function csd_lsd:get($db,$name) {
  if (csd_lsd:exists($db,$name)) then
    db:open($db,csd_lsd:get_document_name($name))
  else
    ()
};

declare updating function csd_lsd:reload($db,$name) {
  (if (csd_lsd:exists($db,$name)) then
     if (csd_lsd:valid_doc($name)) then
       db:delete($db,csd_lsd:get_document_name($name))
     else
      ()
    else ()
    ,
    csd_lsd:load($db,$name)
  )
};

(:~
: This is the Care Services Discovery stored query registry
: @version 1.0
: @see https://github.com/his-interop/openinfoman
:
:)
module namespace csd_lsd = "https://github.com/his-interop/openinfoman/csd_lsd";

declare variable $csd_lsd:base_path := "../service_directories/";

declare function csd_lsd:sample_directories() {
  file:base-name(file:list($csd_lsd:base_path,false(),'*.xml'),".xml")
};

declare function csd_lsd:get_document_names() {
  csd_lsd:get_document_name(csd_lsd:sample_directories())
};

declare function csd_lsd:get_document_name($name) {
  concat("service_directories/",$name,".xml")
};

declare function csd_lsd:get_document_source($name) {
  concat($csd_lsd:base_path, "/" , $name,".xml")
};

declare function csd_lsd:exists($db,$name) {
  db:is-xml($db,csd_lsd:get_document_name($name)) and csd_lsd:valid_doc($name)
};

declare function csd_lsd:valid_doc($name) {
  $name = csd_lsd:sample_directories()
};

declare updating function csd_lsd:load($db,$name) {
  if (not(csd_lsd:exists($db,$name)) and csd_lsd:valid_doc($name)) then
    db:add($db, csd_lsd:get_document_source($name),csd_lsd:get_document_name($name))
  else
    ()
};

declare function csd_lsd:get($db,$name) {
  if (csd_lsd:exists($db,$name)) then
    db:open($db,csd_lsd:get_document_name($name))
  else
    ()
};

declare updating function csd_lsd:reload($db,$name) {
  (if (csd_lsd:exists($db,$name)) then
     if (csd_lsd:valid_doc($name)) then
       db:delete($db,csd_lsd:get_document_name($name))
     else
      ()
    else ()
    ,
    csd_lsd:load($db,$name)
  )
};


local parametreler için ekleme yapıldı.

local parametreler için ekleme yapıldı.

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

import module namespace sq = "http://sq.tlos.com/" at "xmldb:exist://db/TLOSSW/modules/moduleSequenceOperations.xquery";

declare namespace agnt = "http://www.likyateknoloji.com/XML_agent_types";
declare namespace res = "http://www.likyateknoloji.com/resource-extension-defs";

declare function lk:getAgents() as element()*
{
	for $agents in doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents
	return  $agents
};

(:declare function lk:checkAgent($agent as element(agnt:SWAgent)) as xs:boolean
{
	let $swAgent := lk:searchAgent($agent/agnt:ipAddress, $agent/agnt:jmxPort)
	let $checkUser := if($swAgent/agnt:jmxUser = $agent/agnt:jmxUser and $swAgent/agnt:jmxPassword = $agent/agnt:jmxPassword)
        then true()
        else (false())
    return $checkUser
};
:)

declare function lk:checkAgent($agent as element(agnt:SWAgent)) as xs:int
{
	(:let $swAgent := lk:searchAgent($agent/agnt:ipAddress, $agent/agnt:jmxPort):)
	let $swAgent := lk:searchAgent($agent/res:Resource, $agent/agnt:jmxPort)
	let $checkUser := if($swAgent/agnt:jmxUser = $agent/agnt:jmxUser and $swAgent/agnt:jmxPassword = $agent/agnt:jmxPassword)
        then $swAgent/@id
        else (-1)
    return $checkUser
};

declare function lk:searchAgent($host as element(res:Resource), $jmxport as element(agnt:jmxPort))  as element(agnt:SWAgent)?
{
   doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent[res:Resource = $host and agnt:jmxPort = $jmxport]
};

(: eski versiyon , coklama hatasi veriyordu. hs. 10eylul2012
declare function lk:searchAgent($host as element(res:Resource), $jmxport as as element(res:Resource))  as element(agnt:SWAgent)?
{
	for $agent in doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent
        where $agent/res:Resource = $host and $agent/agnt:jmxPort = $jmxport
    return $agent
};
:)

(:
declare function lk:searchAgent($ip as xs:string, $jmxport as xs:int)  as element(agnt:SWAgent)?
{
	for $agent in doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent
        where $agent/agnt:ipAddress = $ip and $agent/agnt:jmxPort = $jmxport
    return $agent
};

:)

declare function lk:searchAgent($searchAgent as element(agnt:SWAgent)) as element(agnt:SWAgent)*
 {
	for $agent in doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent
	return if ((fn:contains(fn:lower-case($agent/res:Resource), fn:lower-case($searchAgent/res:Resource)) or data($searchAgent/res:Resource)="")
                   and
                   (fn:contains(fn:lower-case($agent/agnt:osType), fn:lower-case($searchAgent/agnt:osType)) or data($searchAgent/agnt:osType)="")
                   and
                   (fn:contains(fn:lower-case($agent/agnt:jmxUser), fn:lower-case($searchAgent/agnt:jmxUser)) or data($searchAgent/agnt:jmxUser)="")
                   and
                   (fn:contains(fn:lower-case($agent/agnt:inJmxAvailable), fn:lower-case($searchAgent/agnt:inJmxAvailable)) or data($searchAgent/agnt:inJmxAvailable)="")
                   and
                   (fn:contains(fn:lower-case($agent/agnt:jmxAvailable), fn:lower-case($searchAgent/agnt:jmxAvailable)) or data($searchAgent/agnt:jmxAvailable)="")
                   and
                   ($agent/agnt:jmxPort eq $searchAgent/agnt:jmxPort or data($searchAgent/agnt:jmxPort)="0")
             )
		then $agent
		else  ( )
};

(: ornek kullanim lk:agentList(1,2) ilk iki eleman :)
declare function lk:agentList($firstElement as xs:int, $lastElement as xs:int) as element(agnt:SWAgent)*
 {
	for $agent in doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent[position() = ($firstElement to $lastElement)]
	return $agent
};

(: ornek kullanim lk:searchAgentByjmxPort('5555') :)
declare function lk:searchAgentByjmxPort($searchjmxPort as xs:string) as element(agnt:SWAgent)*
 {
    for $agent in doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent
    where $agent/agnt:jmxPort=$searchjmxPort
    return $agent
};

declare function lk:searchAgentByAgentId($id as xs:integer) as element(agnt:SWAgent)?
 {
	for $agent in doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent
	where $agent/@id = $id
    return $agent
};

declare function lk:insertAgentLock($agent as element(agnt:SWAgent)) as xs:boolean
{
   let $sonuc := util:exclusive-lock(doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents, lk:insertAgent($agent))
   return true()
};

declare function lk:insertAgent($agent as element(agnt:SWAgent)) as node()*
{
    let $XXX := $agent
    let $nextId := sq:getNextId("agentId")
	let $localParameters := count($XXX/agnt:locals)
    let $locals := 	for $loc in $XXX/agnt:locals
	                  return
					    <agnt:locals>
	                    {
						for $par in $loc/par:parameter
						return
						 <par:parameter  id="{$nextId}">
                           <par:name>{data($par/par:name)}</par:name>
                           <par:valueString>{data($par/par:valueString)}</par:valueString>
                           <par:preValue type="{data($par/par:preValue/@type)}">{data($par/par:preValue)}</par:preValue>
                           <par:desc>{data($par/par:desc)}</par:desc>
                         </par:parameter>
						}
					    </agnt:locals>
	return update insert
	  <agnt:SWAgent id="{$nextId}">
        <res:Resource>{data($XXX/res:Resource)}</res:Resource>
        <agnt:osType>{data($XXX/agnt:osType)}</agnt:osType>
        <agnt:agentType>{data($XXX/agnt:agentType)}</agnt:agentType>
        <agnt:nrpePort>{data($XXX/agnt:nrpePort)}</agnt:nrpePort>
        <agnt:jmxPort>{data($XXX/agnt:jmxPort)}</agnt:jmxPort>
        <agnt:jmxUser>{data($XXX/agnt:jmxUser)}</agnt:jmxUser>
        <agnt:jmxPassword>{data($XXX/agnt:jmxPassword)}</agnt:jmxPassword>
        <agnt:inJmxAvailable>{data($XXX/agnt:inJmxAvailable)}</agnt:inJmxAvailable>
        <agnt:outJmxAvailable>{data($XXX/agnt:outJmxAvailable)}</agnt:outJmxAvailable>
        <agnt:jmxAvailable>{data($XXX/agnt:jmxAvailable)}</agnt:jmxAvailable>
        <agnt:userStopRequest>{data($XXX/agnt:userStopRequest)}</agnt:userStopRequest>
        <agnt:nrpeAvailable>{data($XXX/agnt:nrpeAvailable)}</agnt:nrpeAvailable>
        <agnt:lastHeartBeatTime>{data($XXX/agnt:lastHeartBeatTime)}</agnt:lastHeartBeatTime>
        <agnt:durationForUnavailability>{data($XXX/agnt:durationForUnavailability)}</agnt:durationForUnavailability>
        <agnt:lastJobTransfer>{data($XXX/agnt:lastJobTransfer)}</agnt:lastJobTransfer>
        <agnt:jobTransferFailureTime>{data($XXX/agnt:jobTransferFailureTime)}</agnt:jobTransferFailureTime>
        <agnt:workspacePath>{data($XXX/agnt:workspacePath)}</agnt:workspacePath>
        { $locals }
      </agnt:SWAgent>
	into doc("xmldb:exist:///db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents

} ;

declare function lk:deleteAgent($agent as element(agnt:SWAgent))
 {
	for $agentdon in doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent
	where $agentdon/@id = $agent/@id
	return update delete $agentdon
};

declare function lk:deleteAgentLock($agent as element(agnt:SWAgent))
{
   util:exclusive-lock(doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent, lk:deleteAgent($agent))
};

declare function lk:updateAgent($agent as element(agnt:SWAgent)) as xs:boolean
{
    let $varmi := 	for $agentdon in doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent
	                where $agentdon/@id = $agent/@id
                    return count(1)
    let $update :=
	  for $agentdon in doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent
	  where $agentdon/@id = $agent/@id
	  return update replace $agentdon with $agent

    let $sonuc := if ($varmi > 0) then true() else false()
  return $sonuc
};

declare function lk:updateAgentLock($agent as element(agnt:SWAgent))
{
   util:exclusive-lock(doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent, lk:updateAgent($agent))
};

declare function lk:updateUserStopRequestValueLock($agentId as xs:int, $userStopRequestValue as xs:string)
{
	util:exclusive-lock(doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents, lk:updateUserStopRequestValue($agentId, $userStopRequestValue))
};

declare function lk:updateUserStopRequestValue($agentId as xs:int, $userStopRequestValue as xs:string)
{
	let $doc := doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")
	let $update := update value $doc/agnt:SWAgents/agnt:SWAgent[@id=data($agentId)]/agnt:userStopRequest with $userStopRequestValue
	return true()
};

declare function lk:updateJmxValue($agentId as xs:int, $updateValue as xs:boolean, $islem as xs:string) as xs:boolean
{
let $doc := doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")
let $sonuc := if ($islem = "outJMX" and data($doc/agnt:SWAgents/agnt:SWAgent[@id=data($agentId)]/agnt:outJmxAvailable) != $updateValue) then
               update value $doc/agnt:SWAgents/agnt:SWAgent[@id=data($agentId)]/agnt:outJmxAvailable with $updateValue
               else if ($islem = "inJMX" and data($doc/agnt:SWAgents/agnt:SWAgent[@id=data($agentId)]/agnt:inJmxAvailable) != $updateValue) then
               update value $doc/agnt:SWAgents/agnt:SWAgent[@id=data($agentId)]/agnt:inJmxAvailable with $updateValue
               else if ($islem = "JMX" and data($doc/agnt:SWAgents/agnt:SWAgent[@id=data($agentId)]/agnt:jmxAvailable) != $updateValue) then
               update value $doc/agnt:SWAgents/agnt:SWAgent[@id=data($agentId)]/agnt:jmxAvailable with $updateValue
               else false()
let $result := true() (: burasi sonuca gore degismeli. sonra yap :)

    return $result
};
(: Kullanim -> local:updateJmxValue(1, true(), xs:string("inJMX")) :)

(:
declare function lk:updateJmxValue($agentId as xs:int, $jmxValue as xs:boolean)
{
	let $doc := doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")
	let $update := update value $doc/agnt:SWAgents/agnt:SWAgent[@id=data($agentId)]/agnt:jmxAvailable with $jmxValue
	return true()
};
:)

declare function lk:updateJmxValueLock($agentId as xs:int, $jmxValue as xs:boolean, $islem as xs:string)
{
	util:exclusive-lock(doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents, lk:updateJmxValue($agentId, $jmxValue, $islem))
};

(:
declare function lk:updateInJmxValue($agentId as xs:int, $inJmxValue as xs:boolean){
	let $doc := doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")
	let $update := update value $doc/agnt:SWAgents/agnt:SWAgent[@id=data($agentId)]/agnt:inJmxAvailable with $inJmxValue
	return true()
};

declare function lk:updateInJmxValueLock($agentId as xs:int, $inJmxValue as xs:boolean)
{
	util:exclusive-lock(doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents, lk:updateInJmxValue($agentId, $inJmxValue))
};

declare function lk:updateOutJmxValue($agentId as xs:int, $outJmxValue as xs:boolean){
	let $doc := doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")
	let $update := update value $doc/agnt:SWAgents/agnt:SWAgent[@id=data($agentId)]/agnt:outJmxAvailable with $outJmxValue
	return true()
};

declare function lk:updateOutJmxValueLock($agentId as xs:int, $outJmxValue as xs:boolean)
{
	util:exclusive-lock(doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents, lk:updateOutJmxValue($agentId, $outJmxValue))
};
:)

declare function lk:updateNrpeValue($host as element(res:Resource), $nrpeValue as xs:boolean){
	let $doc := doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")
	let $update := update value $doc/agnt:SWAgents/agnt:SWAgent[res:Resource=$host]/agnt:nrpeAvailable with $nrpeValue
	return true()
};

declare function lk:updateNrpeValueLock($host as element(res:Resource), $nrpeValue as xs:boolean)
{
	util:exclusive-lock(doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents, lk:updateNrpeValue($host, $nrpeValue))
};

declare function lk:updateAgentToAvailable($agentId as xs:int){
	let $updateJmx := lk:updateJmxValue($agentId, true(), xs:string("JMX"))
	let $updateInJmx := lk:updateJmxValue($agentId, true(), xs:string("inJMX"))
	let $updateOutJmx := lk:updateJmxValue($agentId, true(), xs:string("outJMX"))
	return true()
};

declare function lk:updateAgentToAvailableLock($agentId as xs:int)
{
	util:exclusive-lock(doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents, lk:updateAgentToAvailable($agentId))
};

declare function lk:updateAgentToUnAvailable($agentId as xs:int){
	let $updateJmx := lk:updateJmxValue($agentId, false(), xs:string("JMX"))
	let $updateInJmx := lk:updateJmxValue($agentId, false(), xs:string("inJMX"))
	let $updateOutJmx := lk:updateJmxValue($agentId, false(), xs:string("outJMX"))
	return true()
};

declare function lk:updateAgentToUnAvailableLock($agentId as xs:int)
{
	util:exclusive-lock(doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents, lk:updateAgentToUnAvailable($agentId))
};

declare function lk:getResorces() as element()*
{
	for $resources in distinct-values(doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent/res:Resource)
	return
	for $agent in doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent[res:Resource=$resources]
	where $agent/@id = min($agent/@id)
	return $agent
};

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

import module namespace sq = "http://sq.tlos.com/" at "xmldb:exist://db/TLOSSW/modules/moduleSequenceOperations.xquery";

declare namespace agnt = "http://www.likyateknoloji.com/XML_agent_types";
declare namespace res = "http://www.likyateknoloji.com/resource-extension-defs";

declare function lk:getAgents() as element()*
{
	for $agents in doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents
	return  $agents
};

(:declare function lk:checkAgent($agent as element(agnt:SWAgent)) as xs:boolean
{
	let $swAgent := lk:searchAgent($agent/agnt:ipAddress, $agent/agnt:jmxPort)
	let $checkUser := if($swAgent/agnt:jmxUser = $agent/agnt:jmxUser and $swAgent/agnt:jmxPassword = $agent/agnt:jmxPassword)
        then true()
        else (false())
    return $checkUser
};
:)

declare function lk:checkAgent($agent as element(agnt:SWAgent)) as xs:int
{
	(:let $swAgent := lk:searchAgent($agent/agnt:ipAddress, $agent/agnt:jmxPort):)
	let $swAgent := lk:searchAgent($agent/res:Resource, $agent/agnt:jmxPort)
	let $checkUser := if($swAgent/agnt:jmxUser = $agent/agnt:jmxUser and $swAgent/agnt:jmxPassword = $agent/agnt:jmxPassword)
        then $swAgent/@id
        else (-1)
    return $checkUser
};

declare function lk:searchAgent($host as element(res:Resource), $jmxport as element(agnt:jmxPort))  as element(agnt:SWAgent)?
{
   doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent[res:Resource = $host and agnt:jmxPort = $jmxport]
};

(: eski versiyon , coklama hatasi veriyordu. hs. 10eylul2012
declare function lk:searchAgent($host as element(res:Resource), $jmxport as as element(res:Resource))  as element(agnt:SWAgent)?
{
	for $agent in doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent
        where $agent/res:Resource = $host and $agent/agnt:jmxPort = $jmxport
    return $agent
};
:)

(:
declare function lk:searchAgent($ip as xs:string, $jmxport as xs:int)  as element(agnt:SWAgent)?
{
	for $agent in doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent
        where $agent/agnt:ipAddress = $ip and $agent/agnt:jmxPort = $jmxport
    return $agent
};

:)

declare function lk:searchAgent($searchAgent as element(agnt:SWAgent)) as element(agnt:SWAgent)*
 {
	for $agent in doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent
	return if ((fn:contains(fn:lower-case($agent/res:Resource), fn:lower-case($searchAgent/res:Resource)) or data($searchAgent/res:Resource)="")
                   and
                   (fn:contains(fn:lower-case($agent/agnt:osType), fn:lower-case($searchAgent/agnt:osType)) or data($searchAgent/agnt:osType)="")
                   and
                   (fn:contains(fn:lower-case($agent/agnt:jmxUser), fn:lower-case($searchAgent/agnt:jmxUser)) or data($searchAgent/agnt:jmxUser)="")
                   and
                   (fn:contains(fn:lower-case($agent/agnt:inJmxAvailable), fn:lower-case($searchAgent/agnt:inJmxAvailable)) or data($searchAgent/agnt:inJmxAvailable)="")
                   and
                   (fn:contains(fn:lower-case($agent/agnt:jmxAvailable), fn:lower-case($searchAgent/agnt:jmxAvailable)) or data($searchAgent/agnt:jmxAvailable)="")
                   and
                   ($agent/agnt:jmxPort eq $searchAgent/agnt:jmxPort or data($searchAgent/agnt:jmxPort)="0")
             )
		then $agent
		else  ( )
};

(: ornek kullanim lk:agentList(1,2) ilk iki eleman :)
declare function lk:agentList($firstElement as xs:int, $lastElement as xs:int) as element(agnt:SWAgent)*
 {
	for $agent in doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent[position() = ($firstElement to $lastElement)]
	return $agent
};

(: ornek kullanim lk:searchAgentByjmxPort('5555') :)
declare function lk:searchAgentByjmxPort($searchjmxPort as xs:string) as element(agnt:SWAgent)*
 {
    for $agent in doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent
    where $agent/agnt:jmxPort=$searchjmxPort
    return $agent
};

declare function lk:searchAgentByAgentId($id as xs:integer) as element(agnt:SWAgent)?
 {
	for $agent in doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent
	where $agent/@id = $id
    return $agent
};

declare function lk:insertAgentLock($agent as element(agnt:SWAgent)) as xs:boolean
{
   let $sonuc := util:exclusive-lock(doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents, lk:insertAgent($agent))
   return true()
};

declare function lk:insertAgent($agent as element(agnt:SWAgent)) as node()*
{
    let $XXX := $agent
    let $nextId := sq:getNextId("agentId")

	return update insert
	  <agnt:SWAgent id="{$nextId}">
        <res:Resource>{data($XXX/res:Resource)}</res:Resource>
        <agnt:osType>{data($XXX/agnt:osType)}</agnt:osType>
        <agnt:agentType>{data($XXX/agnt:agentType)}</agnt:agentType>
        <agnt:nrpePort>{data($XXX/agnt:nrpePort)}</agnt:nrpePort>
        <agnt:jmxPort>{data($XXX/agnt:jmxPort)}</agnt:jmxPort>
        <agnt:jmxUser>{data($XXX/agnt:jmxUser)}</agnt:jmxUser>
        <agnt:jmxPassword>{data($XXX/agnt:jmxPassword)}</agnt:jmxPassword>
        <agnt:inJmxAvailable>{data($XXX/agnt:inJmxAvailable)}</agnt:inJmxAvailable>
        <agnt:outJmxAvailable>{data($XXX/agnt:outJmxAvailable)}</agnt:outJmxAvailable>
        <agnt:jmxAvailable>{data($XXX/agnt:jmxAvailable)}</agnt:jmxAvailable>
        <agnt:userStopRequest>{data($XXX/agnt:userStopRequest)}</agnt:userStopRequest>
        <agnt:nrpeAvailable>{data($XXX/agnt:nrpeAvailable)}</agnt:nrpeAvailable>
        <agnt:lastHeartBeatTime>{data($XXX/agnt:lastHeartBeatTime)}</agnt:lastHeartBeatTime>
        <agnt:durationForUnavailability>{data($XXX/agnt:durationForUnavailability)}</agnt:durationForUnavailability>
        <agnt:lastJobTransfer>{data($XXX/agnt:lastJobTransfer)}</agnt:lastJobTransfer>
        <agnt:jobTransferFailureTime>{data($XXX/agnt:jobTransferFailureTime)}</agnt:jobTransferFailureTime>
        <agnt:workspacePath>{data($XXX/agnt:workspacePath)}</agnt:workspacePath>
      </agnt:SWAgent>
	into doc("xmldb:exist:///db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents

} ;

declare function lk:deleteAgent($agent as element(agnt:SWAgent))
 {
	for $agentdon in doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent
	where $agentdon/@id = $agent/@id
	return update delete $agentdon
};

declare function lk:deleteAgentLock($agent as element(agnt:SWAgent))
{
   util:exclusive-lock(doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent, lk:deleteAgent($agent))
};

declare function lk:updateAgent($agent as element(agnt:SWAgent)) as xs:boolean
{
    let $varmi := 	for $agentdon in doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent
	                where $agentdon/@id = $agent/@id
                    return count(1)
    let $update :=
	  for $agentdon in doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent
	  where $agentdon/@id = $agent/@id
	  return update replace $agentdon with $agent

    let $sonuc := if ($varmi > 0) then true() else false()
  return $sonuc
};

declare function lk:updateAgentLock($agent as element(agnt:SWAgent))
{
   util:exclusive-lock(doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent, lk:updateAgent($agent))
};

declare function lk:updateUserStopRequestValueLock($agentId as xs:int, $userStopRequestValue as xs:string)
{
	util:exclusive-lock(doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents, lk:updateUserStopRequestValue($agentId, $userStopRequestValue))
};

declare function lk:updateUserStopRequestValue($agentId as xs:int, $userStopRequestValue as xs:string)
{
	let $doc := doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")
	let $update := update value $doc/agnt:SWAgents/agnt:SWAgent[@id=data($agentId)]/agnt:userStopRequest with $userStopRequestValue
	return true()
};

declare function lk:updateJmxValue($agentId as xs:int, $updateValue as xs:boolean, $islem as xs:string) as xs:boolean
{
let $doc := doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")
let $sonuc := if ($islem = "outJMX" and data($doc/agnt:SWAgents/agnt:SWAgent[@id=data($agentId)]/agnt:outJmxAvailable) != $updateValue) then
               update value $doc/agnt:SWAgents/agnt:SWAgent[@id=data($agentId)]/agnt:outJmxAvailable with $updateValue
               else if ($islem = "inJMX" and data($doc/agnt:SWAgents/agnt:SWAgent[@id=data($agentId)]/agnt:inJmxAvailable) != $updateValue) then
               update value $doc/agnt:SWAgents/agnt:SWAgent[@id=data($agentId)]/agnt:inJmxAvailable with $updateValue
               else if ($islem = "JMX" and data($doc/agnt:SWAgents/agnt:SWAgent[@id=data($agentId)]/agnt:jmxAvailable) != $updateValue) then
               update value $doc/agnt:SWAgents/agnt:SWAgent[@id=data($agentId)]/agnt:jmxAvailable with $updateValue
               else false()
let $result := true() (: burasi sonuca gore degismeli. sonra yap :)

    return $result
};
(: Kullanim -> local:updateJmxValue(1, true(), xs:string("inJMX")) :)

(:
declare function lk:updateJmxValue($agentId as xs:int, $jmxValue as xs:boolean)
{
	let $doc := doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")
	let $update := update value $doc/agnt:SWAgents/agnt:SWAgent[@id=data($agentId)]/agnt:jmxAvailable with $jmxValue
	return true()
};
:)

declare function lk:updateJmxValueLock($agentId as xs:int, $jmxValue as xs:boolean, $islem as xs:string)
{
	util:exclusive-lock(doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents, lk:updateJmxValue($agentId, $jmxValue, $islem))
};

(:
declare function lk:updateInJmxValue($agentId as xs:int, $inJmxValue as xs:boolean){
	let $doc := doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")
	let $update := update value $doc/agnt:SWAgents/agnt:SWAgent[@id=data($agentId)]/agnt:inJmxAvailable with $inJmxValue
	return true()
};

declare function lk:updateInJmxValueLock($agentId as xs:int, $inJmxValue as xs:boolean)
{
	util:exclusive-lock(doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents, lk:updateInJmxValue($agentId, $inJmxValue))
};

declare function lk:updateOutJmxValue($agentId as xs:int, $outJmxValue as xs:boolean){
	let $doc := doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")
	let $update := update value $doc/agnt:SWAgents/agnt:SWAgent[@id=data($agentId)]/agnt:outJmxAvailable with $outJmxValue
	return true()
};

declare function lk:updateOutJmxValueLock($agentId as xs:int, $outJmxValue as xs:boolean)
{
	util:exclusive-lock(doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents, lk:updateOutJmxValue($agentId, $outJmxValue))
};
:)

declare function lk:updateNrpeValue($host as element(res:Resource), $nrpeValue as xs:boolean){
	let $doc := doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")
	let $update := update value $doc/agnt:SWAgents/agnt:SWAgent[res:Resource=$host]/agnt:nrpeAvailable with $nrpeValue
	return true()
};

declare function lk:updateNrpeValueLock($host as element(res:Resource), $nrpeValue as xs:boolean)
{
	util:exclusive-lock(doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents, lk:updateNrpeValue($host, $nrpeValue))
};

declare function lk:updateAgentToAvailable($agentId as xs:int){
	let $updateJmx := lk:updateJmxValue($agentId, true(), xs:string("JMX"))
	let $updateInJmx := lk:updateJmxValue($agentId, true(), xs:string("inJMX"))
	let $updateOutJmx := lk:updateJmxValue($agentId, true(), xs:string("outJMX"))
	return true()
};

declare function lk:updateAgentToAvailableLock($agentId as xs:int)
{
	util:exclusive-lock(doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents, lk:updateAgentToAvailable($agentId))
};

declare function lk:updateAgentToUnAvailable($agentId as xs:int){
	let $updateJmx := lk:updateJmxValue($agentId, false(), xs:string("JMX"))
	let $updateInJmx := lk:updateJmxValue($agentId, false(), xs:string("inJMX"))
	let $updateOutJmx := lk:updateJmxValue($agentId, false(), xs:string("outJMX"))
	return true()
};

declare function lk:updateAgentToUnAvailableLock($agentId as xs:int)
{
	util:exclusive-lock(doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents, lk:updateAgentToUnAvailable($agentId))
};

declare function lk:getResorces() as element()*
{
	for $resources in distinct-values(doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent/res:Resource)
	return
	for $agent in doc("//db/TLOSSW/xmls/tlosSWAgents10.xml")/agnt:SWAgents/agnt:SWAgent[res:Resource=$resources]
	where $agent/@id = min($agent/@id)
	return $agent
};