adding csd to mcsd converter

adding csd to mcsd converter

module namespace page = 'http://basex.org/modules/web-page';
import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
import module namespace functx = 'http://www.functx.com';
import module namespace csr_proc = "https://github.com/openhie/openinfoman/csr_proc";
import module namespace csd_webui =  "https://github.com/openhie/openinfoman/csd_webui";
import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";
import module namespace svs_lsvs = "https://github.com/openhie/openinfoman/svs_lsvs";
declare namespace csd =  "urn:ihe:iti:csd:2013";
declare namespace svs = "urn:ihe:iti:svs:2008";
declare namespace UUID = "java.util.UUID";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $page:namespace_uuid := "10df44d2-55f4-11e4-af21-705681a860b7";

declare function page:uuid_tobits($tokens) {
  if (count($tokens) > 1)
  then  (
          bin:hex(concat($tokens[1],$tokens[2])),
          page:uuid_tobits(subsequence($tokens,3))
        )
  else $tokens
};

declare function page:getDayOfTheWeek ($day) {
  if($day = 1) then "mon"
  else if ($day = 2) then "tue"
  else if ($day = 3) then "wed"
  else if ($day = 4) then "thu"
  else if ($day = 5) then "fri"
  else if ($day = 6) then "sat"
  else if ($day = 7) then "sun"
  else ()
};

declare function page:uuid_generate($name,$namespace) {
  let $ns_bits := page:uuid_tobits(functx:chars(translate($namespace,'-','' )))
  let $n_bytes := convert:string-to-base64($name)
  let $uuid := UUID:nameUUIDFromBytes(  bin:join(($ns_bits, $n_bytes)))
  return lower-case($uuid)
};

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

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

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

declare
  %rest:path("/mcsd")
  %rest:GET
  function page:FHIR()
{
  let $output :=
                <json type='object'>
                  <issue type="array">
                    <_ type="object">
                      processing
                      <diagnostics>This is the base URL of FHIR server. Unable to handle this request, as it does not contain a resource type or operation name. to get Locations use http://localhost:8984/doc_name/mcsd/Location</diagnostics>

                        <text>Internal server error</text>

                      <severity>error</severity>
                    </_>
                  </issue>
                  <resourceType>OperationOutcome</resourceType>
                </json>
    return (
              <rest:response>
                <output:serialization-parameters>
                  <output:media-type value='application/json'/>
                </output:serialization-parameters>
              </rest:response>,
              json:serialize($output,map{"format":"direct",'escape': 'no'})
            )
};

declare
  %rest:path("/{$doc_name}/mcsd/Location")
  %rest:query-param("_id", "{$_id}")
  %rest:query-param("page", "{$page}")
  %rest:query-param("_count", "{$_count}")
  %rest:query-param("_since", "{$_since}")
  %rest:GET
  function page:FHIRLocation($_id,$page,$_count,$_since,$doc_name)
{
let $contents := page:get_location ($doc_name,$_id,$page,$_count,$_since)
let $location :=
<json type='object'>
<resourceType>Bundle</resourceType>
<total>{count($contents/facilityDirectory/facility) + count($contents/organizationDirectory/organization)}</total>
<type>batch</type>
<meta type="object">
  <lastUpdated>{current-dateTime()}</lastUpdated>
</meta>
<timestamp>{current-dateTime()}</timestamp>
<id>{concat('urn:uuid:', random:uuid())}</id>
<entry type="array">
{
for $content in ($contents/facilityDirectory/facility,$contents/organizationDirectory/organization)
let $entityType := $content/name()
let $orgUUID := concat('urn:uuid:', page:uuid_generate($content/@entityID, $page:namespace_uuid))
let $organizationResource :=
  if($entityType = "csd:facility" or $entityType = "facility") then
    (
      <_ type="object">
      <fullURL>{csd_webui:generateURL($doc_name || "/mcsd/Organization/" || $orgUUID)}</fullURL>
      <request type="object">
        <method>PUT</method>
        <url>Organization/{$orgUUID}</url>
      </request>
      <resource type="object">
        <resourceType>Organization</resourceType>
        <meta type="object">
          <profile>mCSDFacility</profile>
        </meta>
        <name>{$content/primaryName/text()}</name>
        <id>{$orgUUID}</id>
        <type type="array">
          <_ type="object">
            <coding type="array">
              <_ type="object">
                <system>urn:ietf:rfc:3986</system>
                urn:ihe:iti:mcsd:2019:facility
                <display>Facility</display>
                <userSelected>false</userSelected>
              </_>
            </coding>
          </_>
        </type>
      </resource>
      </_>
    )
  else ()
  let $locationResource :=
<_ type="object">
  <fullURL>{csd_webui:generateURL($doc_name || "/mcsd/Location/" || $content/@entityID)}</fullURL>
  <request type="object">
    <method>PUT</method>
    <url>Location/{$content/@entityID/string()}</url>
  </request>
  <resource type="object">
    <resourceType>Location</resourceType>
      <meta type="object">
        <lastUpdated>{$content/record/@updated/string()}</lastUpdated>
        {
          if($entityType = "csd:facility" or $entityType = "facility") then
          (<profile>mCSDFacility</profile>)
          else if($entityType = "csd:organization" or $entityType = "organization") then
          (<profile>mCSD</profile>)
          else()
        }
        <tag type="array">
        <_ type="object">
            {$content/record/@sourceDirectory/string()}
            <system>https://github.com/openhie/openinfoman/tags/fhir/sourceDirectory</system>
          </_>
        </tag>
      </meta>
    <id>{$content/@entityID/string()}</id>
    {
     if(exists($content/otherID))
     then
     <identifier type="array">
      {
      for $otherid in $content/otherID
      return
      <_ type="object">
        <value>{$otherid/text()}</value>
        {
          if($otherid/@code/string()) then
          (
            <type type="object">
              <text>{$otherid/@code/string()}</text>
            </type>
          )
          else ()
        }
        <assigner type="object">
          <display>{$otherid/@assigningAuthorityName/string()}</display>
        </assigner>
      </_>
      }
      <_ type="object">
        <system>urn:ihe:iti:csd:2013:entityID</system>
        <value>{$content/@entityID/string()}</value>
        <type type="object">
          <text>entityID</text>
        </type>
      </_>
     </identifier>
     else ()
    }
    {
      let $search_name := "urn:ihe:iti:csd:2014:stored-function:organization-search"
      let $parent :=
      if(exists($content/organizations/organization))
      then
      $content/organizations/organization/@entityID/string()
      else
      if (exists($content/parent))
      then $content/parent/@entityID/string()
      else ()

      return if($parent)
      then
      let $careServicesSubRequest :=
      <csd:careServicesRequest>
        <csd:function urn="{$search_name}" resource="{$doc_name}" base_url="{csd_webui:generateURL()}">
          <csd:requestParams>
            <csd:id entityID="{$parent}"/>
          </csd:requestParams>
        </csd:function>
      </csd:careServicesRequest>
      let $doc :=  csd_dm:open_document($doc_name)
      let $organization := csr_proc:process_CSR_stored_results( $doc , $careServicesSubRequest)
      return if(exists($organization/organizationDirectory/organization))
      then
      <partOf type="object">
        <reference>{csd_webui:generateURL($doc_name || "/mcsd/Location/" || $organization/organizationDirectory/organization/@entityID/string())}</reference>
        <display>{$organization/organizationDirectory/organization/primaryName/text()}</display>
      </partOf>
      else ()
      else ()
    }
    <physicalType type="object">
      <coding type="array">
        <_ type="object">
          <system>http://hl7.org/fhir/location-physical-type</system>
          {
            if($entityType = "csd:facility" or $entityType = "facility") then
            ( bu,
              <display>Building</display>
            )
            else if($entityType = "csd:organization" or $entityType = "organization") then
            (
              jdn,
              <display>Jurisdiction</display>
            )
            else ()
          }
        </_>
      </coding>
      {
        if($entityType = "csd:facility" or $entityType = "facility") then
          <text>Building</text>
        else if($entityType = "csd:organization" or $entityType = "organization") then
          <text>Jurisdiction</text>
        else ()
      }
    </physicalType>
    {
      if($entityType = "csd:facility" or $entityType = "facility") then
        <managingOrganization type="object">
          <reference>Organization/{$orgUUID}</reference>
        </managingOrganization>
      else ()
    }
    {
    if(exists($content/contactPoint))
    then
    <telecom type="array">
     {
      for $contactPoint in $content/contactPoint
      return
        <_ type="object">
        {
          <system>
            {
              let $code := $contactPoint/codedType/@code/string()
              return if($code = "BP") then "phone"
                else if ($code = "EMAIL") then "email"
                else if ($code = "FAX") then "fax"
                else "other"
            }
          </system>
        }
          <value>{$contactPoint/codedType/text()}</value>
        </_>
     }
    </telecom>
    else ()
    }
    {
    if(exists($content/address/addressLine))
        then
        <address type="array">
          {
            for $address in $content/address
            return
              if(exists($address/addressLine))
              then
              <_ type="object">
                {
                  let $csdtype := lower-case($address/@type/string())
                  let $fhirtype := if($csdtype = "mailing" or $csdtype = "mailing address") then "postal"
                                    else if ($csdtype = "physical" or $csdtype = "physical address") then "physical"
                                    else ()
                  return if($fhirtype)
                          then <type>{$fhirtype}</type>
                          else ()
                }
                {
                  for $addressLine in $address/addressLine
                  return if($addressLine/@component = "streetAddress")
                    then <line>{$addressLine/text()}</line>
                    else if($addressLine/@component = "city")
                    then <city>{$addressLine/text()}</city>
                    else if($addressLine/@component = "district")
                    then <district>{$addressLine/text()}</district>
                    else if($addressLine/@component = "stateProvince")
                    then <state>{$addressLine/text()}</state>
                    else if($addressLine/@component = "country")
                    then <country>{$addressLine/text()}</country>
                    else if($addressLine/@component = "postalCode")
                    then <postalCode>{$addressLine/text()}</postalCode>
                    else()
                }
              </_>
              else ()
          }
        </address>
        else ()
    }
    {
      if(exists($content/geocode))
      then
      <position type="object">
        <longitude>{$content/geocode/longitude/text()}</longitude>
        <latitude>{$content/geocode/latitude/text()}</latitude>
        {
          if($content/geocode/altitude/text()) then
            <altitude>{$content/geocode/altitude/text()}</altitude>
          else ()
        }
      </position>
      else ()
    }
    <type type="array">
      {
        if($entityType = "csd:facility" or $entityType = "facility") then
          <_ type="object">
            <coding type="array">
              <_ type="object">
                <system>urn:ietf:rfc:3986</system>
                urn:ihe:iti:mcsd:2019:facility
                <display>Facility</display>
                <userSelected>false</userSelected>
              </_>
            </coding>
          </_>
        else ()
      }
      {
        for $codedType in $content/codedType
          return
            <_ type="object">
              <coding type="array">
                <_ type="object">
                  {$codedType/@code/string()}
                  <system>{$codedType/@codingScheme/string()}</system>
                  {
                  if(functx:all-whitespace($codedType/text()))
                  then ()
                  else
                  <display>{$codedType/text()}</display>
                  }
                </_>
              </coding>
              <text>{$codedType/text()}</text>
            </_>
      }
    </type>
    <status>{$content/record/@status/string()}</status>
    <name>{$content/primaryName/text()}</name>
    {
      if($content/otherName) then
        <alias type="array">
        {
          for $otherName in $content/otherName
            return
              <_>{$otherName/string()}</_>
        }
        </alias>
      else ()
    }
    {
      if(exists($content/operatingHours))then
      <hoursOfOperation type="array">
      {
        for $operatingHours in $content/operatingHours
          return
          <_ type="object">
          {
            let $CSDdayOfTheWeek := $operatingHours/dayOfTheWeek/text()
              let $FHIRdayOfTheWeek := page:getDayOfTheWeek($CSDdayOfTheWeek)
              return (
                <daysOfWeek>{$FHIRdayOfTheWeek}</daysOfWeek>,
                <openingTime>{$operatingHours/beginningHour/text()}</openingTime>,
                <closingTime>{$operatingHours/endingHour/text()}</closingTime>
              )
          }
          </_>
      }
      </hoursOfOperation>
      else ()
    }
  </resource>
</_>
  return($organizationResource,$locationResource)
}
</entry>
</json>
return (
  <rest:response>
    <output:serialization-parameters>
      <output:media-type value='application/json'/>
    </output:serialization-parameters>
  </rest:response>,
  json:serialize($location,map{"format":"direct",'escape': 'no'})
  )

};

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


Adding edit functionality for DataElement

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:DataElement(
   $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?
) as xs:boolean
{
(:
   $data_element_concept_id?,
   $value_domain_id?,
   $example?,
   $precision?
:)
   let $version := lib-forms:substring-after-last($id,'-')

   let $data_element_concept_id := request:get-parameter('data_element_concept_id','')
   let $value_domain_id := request:get-parameter('value_domain_id','')
   let $example:= request:get-parameter('example','')
   let $precision := request:get-parameter('precision','')

   let $data-identifier := substring-after(lib-forms:substring-before-last($id,'-'),'-')
   let $doc-name := concat($id,'.xml')

   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_precision {$precision},
                    element openMDR:representing {$value_domain_id},
                    element openMDR:expressing {$data_element_concept_id},
                    element openMDR:exemplified_by {
                    element openMDR:data_element_example_item {$example} }
                    )

   (: compose the document :)
   let $document :=
        element openMDR:Data_Element {
            lib-make-admin-item:identifier-attributes($reg-auth,$data-identifier,$version),
            $content
           }
   (:
   let $collection := 'property'
   let $message := lib-forms:store-document($document)
   :)
   return
    if(lib-forms:store-document($document)='stored')
          then 'stored'
          else ( response:redirect-to(xs:anyURI(concat("login.xquery?calling_page=editDataElement.xquery&","Could not store data element"))) )
};

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*,
   $action as xs:string?,
   $preferred 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 DataElement in the metadata repository

          <form name="edit_dataelement" action="editDataElement.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)}

                  Data Element Concept

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

                  Value Domain

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

Example	{lib-forms:text-area-element('example', 5, 70, request:get-parameter('example',''))}

Precision	{lib-forms:input-element('precision', 70,request:get-parameter('precision',''))}

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

          </form>

{$message}

   };

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

DataElement modified

Return to maintenance menu

Create another DataElement class

};

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 := concat("Editing DataElement ", $id)
   let $element := lib-util:mdrElement("data_element",$id)
   let $action := request:get-parameter('update','')

   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 $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','')

   return

      lib-rendering:txfrm-webpage(
      $title,
      if ($action='Store Changes')
      then
         (
         if (
               local:DataElement
                  (
                     $id,
                     $reg-auth,
                     $administrative-note,
                     $administrative-status,
                     $administered-by,
                     $submitted-by,
                     $registered-by,
                     $context-ids,
                     $country-identifiers,
                     $language-identifiers,
                     $names,
                     $definitions,
                     $sources,
                     $preferred
                  )
            )
         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,
                     $action,
                     $preferred
                  )
               )
         )
      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,
               $action,
               $preferred
               )
         ) 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,
               $action,
               $ipreferred
               )
         )
       )

    )

error: pathspec 'grid-incubation/incubator/projects/mdr/projects/mdrCore/db/mdr/edit/editDataElement.xquery' did not match any file(s) known to git


Reorder stuff.

Reorder stuff.

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


adds publication and first performed dates

Using http client to scrape data from online resource and insert new
date and genre elements into the simplified tei.

xquery version "3.0";
declare namespace util="http://exist-db.org/xquery/util";
declare namespace tei="http://www.tei-c.org/ns/1.0";
declare namespace xqi="http://xqueryinstitute.org/ns";
declare namespace httpclient="http://exist-db.org/xquery/httpclient";

(:~
 : Add dates from an external source to each tei record.
:)
declare function local:get-genre($plays){
let $url := 'http://www.opensourceshakespeare.org/views/plays/plays.php'
let $http-get-data := httpclient:get(xs:anyURI($url), true(), <Headers/>)
let $comedies := string-join($http-get-data//*:td[contains(descendant::*:h3,'COMEDIES')]/descendant::*:a/node())
let $tragedies := string-join($http-get-data//*:td[contains(descendant::*:h3,'TRAGEDIES')]/descendant::*:a/node())
let $histories := $http-get-data//*:td[contains(descendant::*:h3,'HISTORIES')]/descendant::*:a/node()
let $uri := base-uri($plays)
let $title := $plays/text()
let $doc := xmldb:document($uri)
return
    if(contains($comedies,$title)) then
        update insert
            <genre xmlns="http://xqueryinstitute.org/ns">comedy</genre>
            following $doc//tei:text[last()]
    else if(contains($tragedies,$title)) then
        update insert
            <genre xmlns="http://xqueryinstitute.org/ns">tragedy</genre>
            following $doc//tei:text[last()]
    else if(contains($histories,$title)) then
        update insert
            <genre xmlns="http://xqueryinstitute.org/ns">history</genre>
            following $doc//tei:text[last()]
    else ''

};

declare function local:attribute-changes(){
        <change xmlns="http://www.tei-c.org/ns/1.0" who="http://xqueryinstitute.org/wsalesky" when="{current-date()}">
        Added additional tei:witness for original publication date to tei:source, Added xqi:performed for first performance date, and xqi:genre for play genre. Source: http://www.opensourceshakespeare.org/views/plays/plays.php  For: XQueryInstitute
    </change>
};

declare function local:get-dates($plays){
let $url := 'http://www.shakespeare-online.com/keydates/playchron.html'
let $http-get-data := httpclient:get(xs:anyURI($url), true(), <Headers/>)
let $uri := base-uri($plays)
let $title := $plays/text()
let $doc := xmldb:document($uri)
return
    for $play in $http-get-data//*:TABLE[contains(descendant::*:TH,'First Performed')]/descendant::*/*:TR
    let $inlinetitle := $play/*:TD[2]/*:a/text()
    let $published := $play/*:TD[3]/text()
    let $performed := $play/*:TD[1]/text()
    return
        if(contains($title,$inlinetitle)) then
            if($published != '') then
            (
            update insert
            <witness xml:id="shakespeare-online" xmlns="http://www.tei-c.org/ns/1.0">
                <date>{$published}</date>
                <ptr target="http://www.shakespeare-online.com/keydates/playchron.html"/>
            </witness>
                into $doc//tei:teiHeader/tei:fileDesc/tei:sourceDesc/tei:listWit,
            update insert
                <performed xmlns="http://xqueryinstitute.org/ns">{$performed}</performed> following $doc//tei:text[last()],
            update insert local:attribute-changes() preceding $doc//tei:teiHeader/tei:revisionDesc/tei:change[1],
            update value $doc//tei:teiHeader/tei:fileDesc/tei:publicationStmt/tei:date with current-date()
            )
            else ''
        else ''
};

for $plays in collection('/db/apps/xq-institute/data/indexed-plays')//tei:titleStmt/tei:title
return (local:get-dates($plays),local:get-genre($plays))

error: pathspec 'modules/add-dates.xql' did not match any file(s) known to git


Adding dataElement Summary for openMDR service

xquery version "1.0";

(: ~
 : Module Name:             trial designer xml document
 :
 : Module Version           1.0
 :
 : Date                               31st October 2006
 :
 : Copyright                       The cagrid consortium
 :
 : Module overview          outputs the expected message for the trial designer plug-in
 :
 :)

(:~
 :    @author Steve Harris
 :    @author Andrew Tsui
 :    @author Maria Lin
 :    @version 0.1
~ :)

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

declare namespace request="http://exist-db.org/xquery/request";
declare namespace session="http://exist-db.org/xquery/session";
declare namespace response="http://exist-db.org/xquery/response";

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

session:create(),
let $term := request:get-parameter("term", "")
let $start as xs:integer := xs:integer(request:get-parameter("start", 0))
let $num as xs:integer := xs:integer(request:get-parameter("num", 10))
return
    lib-search:dataElementSummary($term,$start,$num)

error: pathspec 'grid-incubation/incubator/projects/mdr/projects/mdrCore/db/mdr/services/dataElementSummary.xquery' did not match any file(s) known to git


Added initial result of the SCXML interpreter in XQuery

module namespace scxq='http://www.w3.org/2005/07/scxml-xquery';

import module namespace functx='http://www.functx.com' at 'functx.xqm';

(: TODO import app, for being able to handle external events :)
(: import module namespace app='http://www.domain.org/myApp' at 'myApp.xqm';:)

(: --- -------------- --- :)
(: --- public methods --- :)
(: --- -------------- --- :)

(:
  Create the databases, which are needed for the SCXML-interpreter.
:)
declare
  updating function scxq:setup()
{
  scxq:_createDatabases()
};

(:
  Stores the initial configuration for the given SCXML in the database.
:)
declare
  updating function scxq:initialize()
{
  let $scxml := scxq:_getScxml()
  let $initialVariables := scxq:_createVariablesForScxml($scxml)
  let $initialConfig := scxq:_createScxmlConfig()
  return
    (
      scxq:_setVariables($initialVariables),
      scxq:_setConfig($initialConfig)
    )
};

(:
  Enters the initial state of the SCMXL.
:)
declare
  updating function scxq:goToInitialState()
{
  let $scxml := scxq:_getScxml()
  let $initialStateId := scxq:_getInitialStateId($scxml)
  return scxq:_goToStateWithId($initialStateId)
};

(:
  Handles and processes an event from the enviroment to the SCXML.
:)
declare
  updating function scxq:receiveEvent($event as xs:string)
{
  let $transition := scxq:_getTransitionForEvent($event)
  return scxq:_evaluateTransition($transition)
};

(:
  Sends an event from the SCXML.
  If the Target is 'external' then the webapp receives it. (Handler method must be implemented)
  Else the event is sent to the SCXML.
:)
declare
  updating function scxq:sendEvent($event, $target)
{
  if ($target = 'external') then
  	(: TODO call handler for external Events in app :)
    (: app:eventFromScxml($event) :)
  else
    scxq:receiveEvent($event)
};

(:
  Returns the ID of the current state.
:)
declare
  function scxq:getCurrentStateId()
{
  let $currentConfig := scxq:_getConfig()
  let $currentStateId := $currentConfig/scxmlConfig/currentStateId/text()
  return $currentStateId
};

(:
  Returns the currently active variables of the SCXML.
:)
declare
  function scxq:getCurrentVariables()
{
  let $currentStateId := scxq:getCurrentStateId()
  let $activeStateIdSequence := scxq:_getParentStateIdSequenceForStateWithId($currentStateId)
  let $variableList := scxq:_getVariables()

  for $stateId in $activeStateIdSequence
    let $stateVariables := $variableList//state[@id=$stateId]/variables/child::node()
    return $stateVariables
};

(:
  Returns the currently possible events of the SCXML.
:)
declare
  function scxq:getPossibleEvents()
{
  let $currentStateId := scxq:getCurrentStateId()
  let $activeStateIdSequence := reverse(scxq:_getParentStateIdSequenceForStateWithId($currentStateId))
  let $scxml := scxq:_getScxml()
  let $possibleEvents :=
    for $stateId in $activeStateIdSequence
      let $transitions := $scxml//state[@id=$stateId]/*[self::transition]
      let $events :=
        for $transition in $transitions
          let $event := string($transition/@event)
          return $event
      return $events
  let $eventsXml :=
    for $event in distinct-values($possibleEvents)
      let $eventXml := <event>{$event}</event>
      return $eventXml
  return <events>{$eventsXml}</events>
};

(: --- --------------- --- :)
(: --- private methods --- :)
(: --- --------------- --- :)

(:
  Creates all databases.
:)
declare
  updating function scxq:_createDatabases()
{
  let $scxml := doc("./static/blackjack-scxml.xml")
  let $scxmlConfig := doc("./static/scxml-config.xml")
  let $scxmlVariables := doc("./static/scxml-variables.xml")
  return
    (
      db:create('scxml', $scxml, '/scxml.xml'),
      db:create('scxmlConfig', $scxmlConfig, '/scxml-config.xml'),
      db:create('scxmlVariables', $scxmlVariables, '/scxml-variables.xml')
    )
};

(:
  Returns the SCXML.
:)
declare
  function scxq:_getScxml()
{
  let $scxml := db:open('scxml')/xml/*[self::scxml]
  return $scxml
};

(:
  Returns the configuration file of the SCXML.
:)
declare
  function scxq:_getConfig()
{
  let $config := db:open('scxmlConfig')
  return $config
};

(:
  Returns the list of currently set variables.
:)
declare
  function scxq:_getVariables()
{
  let $variables := db:open('scxmlVariables')
  return $variables
};

(:
  Stores the given SCXML in the database.
:)
declare
  updating function scxq:_setScxml($scxml)
{
  db:replace('scxml', '/scxml.xml', $scxml)
};

(:
  Stores the given configuration file in the database.
:)
declare
  updating function scxq:_setConfig($config)
{
  db:replace('scxmlConfig', '/scxml-config.xml', $config)
};

(:
  Stores the given list of variables in the database.
:)
declare
  updating function scxq:_setVariables($variables)
{
  db:replace('scxmlVariables', '/scxml-variables.xml', $variables)
};

(: --- States --- :)
(: /// Initial State /// :)

(:
  Returns the initial state of the SCXML.
:)
declare
  function scxq:_getInitialState($scxml)
{
  let $initialStateId := scxq:_getInitialStateId($scxml)
  let $initialState := scxq:_getStateWithId($initialStateId)
  return $initialState
};

(:
  Returns the ID of the initial state of the SCXML.
:)
declare
  function scxq:_getInitialStateId($scxml)
{
  let $initialStateId := string($scxml/@initialState)
  return($initialStateId)
};

(: /// Parent State /// :)

(:
  Returns the list of IDs for all parent states of the state with a given state ID.
  The first element is the upper most parent. The last element is the first parent.
:)
declare
  function scxq:_getParentStateIdSequenceForStateWithId($stateId)
{
  functx:value-union(reverse(scxq:_getReversedParentStateIdsForStateWithId($stateId)), ($stateId))
};

(:
  Returns the list of IDs for all parent states of the state with a given state ID.
  The first element is the first parent. The last element is the upper most parent.
:)
declare
  function scxq:_getReversedParentStateIdsForStateWithId($stateId)
{
  let $scxml := scxq:_getScxml()
  let $currentState := scxq:_getStateWithId($stateId)
  let $parentState := $scxml//state[@id=$stateId]/parent::state
  let $parentStateId := scxq:_getIdOfState($parentState)

  let $parentStatesSequence := ($parentStateId)
  let $resultSequence :=
    if (empty($parentStateId) or $parentStateId = '') then
      ()
    else
      let $moreSequence := scxq:_getReversedParentStateIdsForStateWithId($parentStateId)
      return functx:value-union($parentStatesSequence, $moreSequence)
  return $resultSequence
};

(: /// Current State /// :)

(:
  Sets the ID for the currently active state in the SCXML configuration file to the given state ID.
:)
declare
  updating function scxq:_setCurrentStateId($stateId)
{
  let $currentConfig := scxq:_getConfig()
  return replace value of node $currentConfig/scxmlConfig/currentStateId with $stateId
};

(:
  Returns the current state of the SCXML.
:)
declare
  function scxq:_getCurrentState()
{
  let $currentStateId := scxq:getCurrentStateId()
  let $currentState := scxq:_getStateWithId($currentStateId)
  return $currentState
};

(: /// General States /// :)

(:
  Returns the root level states of a given SCXML.
:)
declare
  function scxq:_getTopLevelStates($scxml)
{
  let $topLevelStates := scxq:_getChildStatesForState($scxml)
  return $topLevelStates
};

(:
  Returns the whole state for a given ID.
:)
declare
  function scxq:_getStateWithId($id)
{
  let $scxml := scxq:_getScxml()
  let $state := $scxml//state[@id=$id]
  return $state
};

(:
  Returns the ID for a given state.
:)
declare
  function scxq:_getIdOfState($state)
{
  let $stateId := string($state/@id)
  return $stateId
};

(:
  Returns the ID of the immediate parent state of the state with the given state ID.
:)
declare
  function scxq:_getIdOfParentStateForStateWithId($stateId)
{
  let $state := scxq:_getStateWithId($stateId)
  let $stateId := string($state/../@id)
  return $stateId
};

(:
  Returns the childstates of the state with the given state ID.
:)
declare
  function scxq:_getChildStatesForStateWithId($stateId)
{
  let $state := scxq:_getStateWithId($stateId)
  return scxq:_getChildStatesForState($state)
};

(:
  Returns the childstates of the given state.
:)
declare
  function scxq:_getChildStatesForState($state)
{
  let $childStates := $state/*[self::state]
  return $childStates
};

(: --- Execution --- :)

(:
  Triggers the execution of all states in a given state ID list.
:)
declare
 updating function scxq:_handleOnEntryForSequenceOfStateIds($stateIdSequence)
{
  for $oneStateId in $stateIdSequence
    return scxq:_handleOnEntryForStateWithId($oneStateId)
};

(:
  Extracts the recently handleable statements in the onentry statement of the state with the given ID.
  - Assignments (assign and var)
  - Events (send)
:)
declare
 updating function scxq:_handleOnEntryForStateWithId($stateId)
{
  let $state := scxq:_getStateWithId($stateId)
  let $onentry := $state/onentry
  let $assignments := $onentry/*[self::assign or self::var]
  let $sends := $onentry/*[self::send]
  return
    (
      scxq:_handleAssignmentsForStateWithId($assignments, $stateId),
      scxq:_handleSends($sends)
    )
};

(:
  Executes a list of assignments.
:)
declare
  updating function scxq:_handleAssignmentsForStateWithId($actionsSequence, $stateId)
{
  if (empty($actionsSequence)) then
    ()
  else
    let $variableList := scxq:_getVariables()
    let $actions := <actions>{$actionsSequence}</actions>
    let $vars := $actions/*[self::var]
    let $assigns := $actions/*[self::assign or self::var]
    for $variable in $assigns
      let $name := string($variable/@name)
      let $expression := string($variable/@expr)
      let $newContent := scxq:_evalExpression($expression, 'true')
      let $variableStateId := scxq:_getStateIdForVariableWithNameOfStateWithId($name, $stateId)
      return replace value of node $variableList//state[@id=$variableStateId]/variables/variable[@name=$name] with $newContent
};

(:
  Triggers the execution for a list of send events.
:)
declare
  updating function scxq:_handleSends($sends)
{
  for $send in $sends
    let $event := string($send/@event)
    let $target := string($send/@target)
    return scxq:sendEvent($event, $target)
};

(: --- Transitions --- :)

(:
  Returns the first valid transition for an event in the current state.
:)
declare
  function scxq:_getTransitionForEvent($event)
{
  let $currentStateId := scxq:getCurrentStateId()
  return scxq:_getTransitionForEventInStateWithId($event, $currentStateId)
};

(:
  Returns the first valid transition for an event in a given state.
  That means, the condition of an transition has to be true (if given).
  First the transitions in the active state are checked. Then the ones in its parent state and so on.
  If a single state has multiple valid Transitions, the first one is chosen.
:)
declare
  function scxq:_getTransitionForEventInStateWithId($event, $stateId)
{
  let $state := scxq:_getStateWithId($stateId)
  let $transitions := $state/transition[@event=$event]
  let $indices :=
    for $trans at $position in $transitions
      let $condition := string($trans/@cond)
      return
        if ($condition = '' or scxq:_evalCondition($condition) = 'true') then
          let $transition := $trans
          return $position
        else
          ()
  let $firstIndex := $indices[1]
  let $transition := $transitions[$firstIndex]
  let $result :=
    if (empty($transition)) then
      let $parentStateId := scxq:_getIdOfParentStateForStateWithId($stateId)
      let $parentTransition :=
        if ($parentStateId = '') then
          ()
        else
          scxq:_getTransitionForEventInStateWithId($event, $parentStateId)
      return $parentTransition
    else
      $transition
  return $result
};

(:
  Executes all the statements in a transition.
  Also triggers a change of the current state, if the transition has a target state.
:)
declare
  updating function scxq:_evaluateTransition($transition)
{
  let $currentStateId := scxq:getCurrentStateId()
  let $assignments := $transition/*[self::assign]
  let $nextStateId := string($transition/@target)
  return
    if ($nextStateId = '') then
      (
        scxq:_handleAssignmentsForStateWithId($assignments, $currentStateId)
      )
    else
      (
        scxq:_handleAssignmentsForStateWithId($assignments, $currentStateId),
        scxq:_goToStateWithId($nextStateId)
      )
};

(:
  Enters the state with a given ID.
:)
declare
  updating function scxq:_goToStateWithId($stateId)
{
  let $currentStateId := scxq:getCurrentStateId()
  let $parentStateIdsSequenceForOldState := scxq:_getParentStateIdSequenceForStateWithId($currentStateId)
  let $parentStateIdsSequence := scxq:_getParentStateIdSequenceForStateWithId($stateId)
  let $intercept := functx:value-intersect($parentStateIdsSequenceForOldState, $parentStateIdsSequence)
  let $except := functx:value-except($parentStateIdsSequence, $intercept)
  let $stateIdsSequence := functx:value-except($except, ($currentStateId))
  return
    (
      scxq:_handleOnEntryForSequenceOfStateIds($stateIdsSequence),
      scxq:_setCurrentStateId($stateId)
    )
};

(: --- Variables --- :)

(:
  Returns the variable with a given name in the current state.
:)
declare
  function scxq:_getVariableWithName($variableName)
{
  let $stateId := scxq:getCurrentStateId()
  let $variable := scxq:_getVariableWithNameInStateWithId($variableName, $stateId)
  return $variable
};

(:
  Returns the variable with a given name in the given state.
  If the variable cannot be found in this state, it is looked up in the parent state and so on.
  If no variable at all can be found an empty sequence is returned.
:)
declare
  function scxq:_getVariableWithNameInStateWithId($variableName, $stateId)
{
  let $variableStateId := scxq:_getStateIdForVariableWithNameOfStateWithId($variableName, $stateId)
  let $variable :=
    if (empty($variableStateId)) then
      ()
    else
      let $variablesOfState := scxq:_getVariablesForStateWithId($variableStateId)
      let $variableOfState := $variablesOfState/variable[@name=$variableName]
      return $variableOfState
  return $variable
};

(:
  Returns the variable with a given name in the given state.
  If no variable can be found, the parent state i
:)
declare
  updating function scxq:_setVariableWithName($variableName, $variable, $variableList)
{
  let $currentStateId := scxq:getCurrentStateId()
  return scxq:_setVariableWithNameInStateWithId($variableName, $currentStateId, $variable, $variableList)
};

(:
  Looks up the variable in the variable list and replaces its content.
:)
declare
  updating function scxq:_setVariableWithNameInStateWithId($variableName, $stateId, $variable, $variableList)
{
  let $variableStateId := scxq:_getStateIdForVariableWithNameOfStateWithId($variableName, $stateId)
  return scxq:_replaceVariableWithNameInStateWithId($variableName, $variableStateId, $variable, $variableList)
};

(:
  Replaces a variable.
:)
declare
  updating function scxq:_replaceVariableWithNameInStateWithId($variableName, $stateId, $variable, $variableList)
{
  replace node $variableList//state[@id=$stateId]/variables/variable[@name=$variableName] with $variable
};

(:
  Returns the ID of the state, a given variable is in.
  The search begins in the current state and continues in its parent states.
:)
declare
  function scxq:_getStateIdForVariableWithName($variableName)
{
  let $currentStateId := scxq:getCurrentStateId()
  let $stateId := scxq:_getStateIdForVariableWithNameOfStateWithId($variableName, $currentStateId)
  return $stateId
};

(:
  Returns the ID of the state, a given variable is in.
  The search begins in a given state. If the variable cannot be found in this state, the search continues in its parent states.
:)
declare
  function scxq:_getStateIdForVariableWithNameOfStateWithId($variableName, $stateId)
{
  let $variablesInState := scxq:_getVariablesForStateWithId($stateId)
  let $variable := $variablesInState/variable[@name=$variableName]
  let $result :=
    if (empty($variable)) then
      let $parentStateId := scxq:_getIdOfParentStateForStateWithId($stateId)
      let $parentVariable :=
        if ($parentStateId = '') then
          ()
        else
          scxq:_getStateIdForVariableWithNameOfStateWithId($variableName, $parentStateId)
      return $parentVariable
    else
      $stateId
  return $result
};

(:
  Returns the list of variables for a given state.
:)
declare
  function scxq:_getVariablesForStateWithId($stateId)
{
  let $variables := scxq:_getVariables()
  let $variablesInState := $variables//state[@id=$stateId]/variables
  return $variablesInState
};

(:
  Creates all variables for the given SCXML
:)
declare
  function scxq:_createVariablesForScxml($scxml)
{
  let $topLevelStates := scxq:_getTopLevelStates($scxml)
  let $variableList :=
    for $state in $topLevelStates
      return scxq:_createVariablesForStateAndChildStates($state)
  let $variableList2 := scxq:_createVariablesForStateAndChildStates($topLevelStates)
  return <variableList>{$variableList}</variableList>
};

(:
  Create all variables for a given state and its child states (recursively).
:)
declare
  function scxq:_createVariablesForStateAndChildStates($state)
{
  let $stateVariables := scxq:_createVariablesForState($state)
  let $childStates := scxq:_getChildStatesForState($state)
  let $childStateCount := count($childStates)
  let $childResult :=
    for $childState in $childStates
      let $childStateVariables := scxq:_createVariablesForStateAndChildStates($childState)
      return $childStateVariables
  let $stateId := scxq:_getIdOfState($state)
  let $variables :=
    <state id="{$stateId}">
      {$stateVariables}
      <childStateCount>{$childStateCount}</childStateCount>
      <childStates>{$childResult}</childStates>
    </state>
  return $variables
};

(:
  Create all variables for a given state
:)
declare
  function scxq:_createVariablesForState($state)
{
  let $variableTags :=
    for $variableTag in $state/onentry//var
      let $variableName := string($variableTag/@name)
      let $variable := scxq:_createVariable($variableName, ())
      return $variable
  let $variablesForState := <variables>{$variableTags}</variables>
  return $variablesForState
};

(:
  Create a new variable
:)
declare
  function scxq:_createVariable($name, $expression)
{
  let $emptyVariable := <variable name="{$name}"></variable>
  let $variable :=
    if (empty($expression)) then
      $emptyVariable
    else
      let $content := scxq:_evalExpression($expression, 'true')
      return scxq:_modifyVariable($emptyVariable, $content)
  return $variable
};

(:
  TODO
:)
declare
  updating function scxq:_replaceMultipleVariablesInStateWithId($stateId, $variables, $variableList)
{
  for $variable in $variables
    let $name := string($variable/@name)
    let $expression := string($variable/@expr)
    let $oldVariable := scxq:_getVariableWithNameInStateWithId($name, $stateId)
    let $newContent := scxq:_evalExpression($expression, 'true')
    let $newVariable := scxq:_modifyVariable($oldVariable, $newContent)
    return scxq:_setVariableWithNameInStateWithId($name, $stateId, $newVariable, $variableList)
};

(:
  Erases the content of a given variable
:)
declare
  function scxq:_emptyVariable($variable)
{
  let $newVariable := scxq:_modifyVariable($variable, '')
  return newVariable
};

(:
  Modifies the content of a variable
:)
declare
  function scxq:_modifyVariable($variable, $content)
{
  let $mymodifiedVariable := functx:replace-element-values($variable, $content)
  return $mymodifiedVariable
};

(: --- Expressions --- :)

(:
  Evaluates a SCXML expression. First it checks if "jexl" is set.
  - Yes: evaluate the condition and return the result
  - No: return the expression as is
:)
declare
  function scxq:_evalExpression($expression as xs:string, $jexl as xs:string)
{
  let $jexlBool := scxq:_boolean($jexl)
  let $result :=
    if ($jexlBool and not(empty($expression)) and not($expression = '')) then
      scxq:_evalCondition($expression)
    else
      $expression
  return $result
};

(:
  Evaluates a SCMXL condition
  This method checks what kind of condition is given:
  - String: return the string
  - Number: return the number
  - Comparison: returns bool
  - Arithmetic expression: returns result
:)
declare
  function scxq:_evalCondition($condition as xs:string)
{
  let $result :=
    if (scxq:_isStringInCondition($condition)) then
      scxq:_removeQuotes($condition)
    else if (functx:is-a-number($condition)) then
      $condition
    else if (scxq:_isActiveVariable($condition)) then
      scxq:_getContentIfVariable($condition)
    else if (contains($condition, '!=')) then
      not(scxq:_isEqual(scxq:_getContentIfVariable(tokenize($condition, '\s*!=\s*')[1]),
                        scxq:_getContentIfVariable(tokenize($condition, '\s*!=\s*')[2])))
    else if (contains($condition, '=')) then
      scxq:_isEqual(scxq:_getContentIfVariable(tokenize($condition, '\s*=\s*')[1]),
                    scxq:_getContentIfVariable(tokenize($condition, '\s*=\s*')[2]))
    else if (contains($condition, '<')) then
      scxq:_isGreater(scxq:_getContentIfVariable(tokenize($condition, '\s*<\s*')[2]),
                      scxq:_getContentIfVariable(tokenize($condition, '\s*<\s*')[1]))
    else if (contains($condition, '>')) then
      scxq:_isGreater(scxq:_getContentIfVariable(tokenize($condition, '\s*>\s*')[1]),
                      scxq:_getContentIfVariable(tokenize($condition, '\s*>\s*')[2]))
    else if (contains($condition, '+')) then
      scxq:_additionInCondition($condition)
    else if (contains($condition, '-')) then
      scxq:_arithmeticOperation($condition, '-')
    else if (contains($condition, '*')) then
      scxq:_arithmeticOperation($condition, '*')
    else if (contains($condition, '/')) then
      scxq:_arithmeticOperation($condition, '/')
    else
      scxq:_boolean($condition)

  return $result
};

(:
  Checks if the input is a variable.
  If yes: return content of variable
  If no: return input as is
:)
declare
  function scxq:_getContentIfVariable($variable)
{
  let $value :=
    if (scxq:_isActiveVariable($variable)) then
      let $variable := scxq:_getVariableWithName($variable)
      return $variable/text()
    else
      $variable
  return $value
};

(:
  Calculates the result of an arithmetic operation on a given condition.
  This is a special case since it could either be an arithmetic operation or a string concatenation.
:)
declare
  function scxq:_additionInCondition($condition as xs:string)
{
  let $tokens := tokenize($condition, '\s*\+\s*')
  let $left := scxq:_getContentIfVariable($tokens[1])
  let $right := scxq:_getContentIfVariable($tokens[2])
  let $isConcatination := (scxq:_isStringInCondition($left) or scxq:_isStringInCondition($right))
  let $result :=
    if ($isConcatination) then
      concat(scxq:_removeQuotes($left), scxq:_removeQuotes($right))
    else
      scxq:_arithmeticOperation($condition, '+')
  return $result
};

(:
  Calculates the result of an arithmetic operation on a given condition.
  Possible operations are:
  - '+' addition
  - '-' substraction
  - '*' multiplication
  - '/' division
:)
declare
  function scxq:_arithmeticOperation($condition as xs:string, $operation as xs:string)
{
  let $escapedOperation :=
    if ($operation = '+' or $operation = '*') then
      concat('\', $operation)
    else
      $operation
  let $tokens := tokenize($condition, concat("\s*", $escapedOperation, "\s*"))
  let $left := scxq:_getContentIfVariable($tokens[1])
  let $right := scxq:_getContentIfVariable($tokens[2])
  let $result :=
    if ($operation = '+') then
      xs:integer($left) + xs:integer($right)
    else if ($operation = '-') then
      xs:integer($left) - xs:integer($right)
    else if ($operation = '*') then
      xs:integer($left) * xs:integer($right)
    else if ($operation = '/' or $operation = ':') then
      xs:integer($left) div xs:integer($right)
    else
      xs:integer($left) + xs:integer($right)
  return $result
};

(:
  Checks if the content of a condition is a string.
:)
declare
  function scxq:_isStringInCondition($condition as xs:string)
{
  let $tokens := tokenize($condition, "\s*'\s*")
  let $result := scxq:_boolean(count($tokens) = 3 and starts-with($condition, "'") and ends-with($condition, "'"))
  return $result
};

(:
  Checks if the condition an active variable in the SCXML.
:)
declare
  function scxq:_isActiveVariable($condition)
{
  let $variable := scxq:_getVariableWithName($condition)
  let $isEmpty := empty($variable)
  return not($isEmpty)
};

(:
  Checks if two values equal by using custom boolean function.
  Also covers the case that the "values" could be variables.
:)
declare
  function scxq:_isEqual($valueOne, $valueTwo)
{
  scxq:_boolean(not(compare($valueOne, $valueTwo)))
};

(:
  Checks if one value is greater than another by using custom boolean function.
:)
declare
  function scxq:_isGreater($valueOne, $valueTwo)
{
  scxq:_boolean(compare(xs:string($valueOne), xs:string($valueTwo)))
};

(:
  Checks if the given value is true or false. Includes special SCXML cases.
:)
declare
  function scxq:_boolean($value)
{
  let $result :=
    if ((functx:sequence-type($value) = 'xs:string' and (lower-case($value) = 'true' or $value = '1')) or
        (functx:sequence-type($value) = 'xs:integer' and $value = 1)) then
      'true'
    else if ((functx:sequence-type($value) = 'xs:string' and (lower-case($value) = 'false' or $value = '0')) or
             (functx:sequence-type($value) = 'xs:integer' and $value = 0)) then
      'false'
    else
      boolean($value)
  return $result
};

(:
  Removes single Quotes from string.
:)
declare
  function scxq:_removeQuotes($string)
{
  replace(replace($string,"'$",""),"^'+","")
};

(:
  Creates the initial SCXML config.
:)
declare
  function scxq:_createScxmlConfig()
{
  <scxmlConfig>
    <currentStateId/>
  </scxmlConfig>
};

error: pathspec 'scxml-interpreter.xqm' did not match any file(s) known to git