Camel Components

DHIS2

Since Camel 4.0

Both producer and consumer are supported

The Camel DHIS2 component leverages the DHIS2 Java SDK to integrate Apache Camel with DHIS2. DHIS2 is a free, open-source, fully customizable platform for collecting, analyzing, visualizing, and sharing aggregate and individual-data for district-level, national, regional, and international system and program management in health, education, and other domains.

Maven users will need to add the following dependency to their pom.xml.

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-dhis2</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>

URI Format

dhis2://operation/method[?options]

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.

For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

You can configure components using:

  • the Component DSL.

  • in a configuration file (application.properties, *.yaml files, etc).

  • directly in the Java code.

Configuring Endpoint Options

You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders.

Property placeholders provide a few benefits:

  • They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.

  • They allow externalizing the configuration from the code.

  • They help the code to become more flexible and reusable.

The following two sections list all the options, firstly for the component followed by the endpoint.

Component Options

The DHIS2 component supports the following options which are listed below.

Name Description Default Type

baseApiUrl (common)

The base URL of the DHIS2 Web API, such as https://play.dhis2.org/2.39.1.1/api. The path of each call is resolved against it. Required unless the client option is set.

String

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

lazyStartProducer (producer)

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

client (advanced)

A custom org.hisp.dhis.integration.sdk.api.Dhis2Client of the DHIS2 Java SDK to use, instead of one built from baseApiUrl and the credentials. Cannot be combined with the baseApiUrl, username, password and personalAccessToken options.

Dhis2Client

configuration (advanced)

The shared configuration, whose options are the defaults of every endpoint of this component.

Dhis2Configuration

password (security)

The password of the DHIS2 user given by the username option, for HTTP Basic authentication.

String

personalAccessToken (security)

The personal access token to authenticate with DHIS2, sent as an ApiToken in the Authorization header. Cannot be combined with username and password.

String

username (security)

The username of the DHIS2 user to call the API as, with HTTP Basic authentication together with the password option. Cannot be combined with personalAccessToken.

String

Endpoint Options

The DHIS2 endpoint is configured using URI syntax:

dhis2:apiName/methodName

With the following path and query parameters:

Path Parameters

Name Description Default Type

apiName (common)

Required The API to call: get, post, put, delete or resourceTables.

Enum values:

  • POST

  • RESOURCE_TABLES

  • GET

  • DELETE

  • PUT

Dhis2ApiName

methodName (common)

Required The method of the API to call: resource or collection for get, resource for post, put and delete, and analytics for resourceTables.

String

Query Parameters

Name Description Default Type

baseApiUrl (common)

The base URL of the DHIS2 Web API, such as https://play.dhis2.org/2.39.1.1/api. The path of each call is resolved against it. Required unless the client option is set.

String

inBody (common)

Sets the name of a parameter to be passed in the exchange In Body.

String

sendEmptyMessageWhenIdle (consumer)

If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead.

false

boolean

bridgeErrorHandler (consumer (advanced))

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

exceptionHandler (consumer (advanced))

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored.

ExceptionHandler

exchangePattern (consumer (advanced))

Sets the exchange pattern when the consumer creates an exchange.

Enum values:

  • InOnly

  • InOut

ExchangePattern

pollStrategy (consumer (advanced))

A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel.

PollingConsumerPollStrategy

lazyStartProducer (producer (advanced))

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

client (advanced)

A custom org.hisp.dhis.integration.sdk.api.Dhis2Client of the DHIS2 Java SDK to use, instead of one built from baseApiUrl and the credentials. Cannot be combined with the baseApiUrl, username, password and personalAccessToken options.

Dhis2Client

backoffErrorThreshold (scheduler)

The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in.

int

backoffIdleThreshold (scheduler)

The number of subsequent idle polls that should happen before the backoffMultipler should kick-in.

int

backoffMultiplier (scheduler)

To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured.

int

delay (scheduler)

Milliseconds before the next poll.

500

long

greedy (scheduler)

If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages.

false

boolean

healthCheckMaxPollDuration (scheduler)

How long a poll may run before the health check of the consumer reports DOWN. The health check is otherwise based on the polls that are done, so it stays UP while a poll hangs, for example on a read without timeout from a connection that went silent. A poll includes routing the messages it polled, so set this above the longest poll you expect. The poll is not interrupted. The value is in millis (not affected by timeUnit). The default 0 turns this off.

0

long

initialDelay (scheduler)

Milliseconds before the first poll starts.

1000

long

repeatCount (scheduler)

Specifies a maximum limit of number of fires. So if you set it to 1, the scheduler will only fire once. If you set it to 5, it will only fire five times. A value of zero or negative means fire forever.

0

long

runLoggingLevel (scheduler)

The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that.

Enum values:

  • TRACE

  • DEBUG

  • INFO

  • WARN

  • ERROR

  • OFF

TRACE

LoggingLevel

scheduledExecutorService (scheduler)

Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool.

ScheduledExecutorService

scheduler (scheduler)

To use a cron scheduler from either camel-spring or camel-quartz component. Use value spring or quartz for built in scheduler.

none

Object

schedulerProperties (scheduler)

To configure additional properties when using a custom scheduler or any of the Quartz, Spring based scheduler. This is a multi-value option with prefix: scheduler.

Map

startScheduler (scheduler)

Whether the scheduler should be auto started.

true

boolean

timeUnit (scheduler)

Time unit for initialDelay and delay options.

Enum values:

  • NANOSECONDS

  • MICROSECONDS

  • MILLISECONDS

  • SECONDS

  • MINUTES

  • HOURS

  • DAYS

MILLISECONDS

TimeUnit

useFixedDelay (scheduler)

Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details.

true

boolean

password (security)

The password of the DHIS2 user given by the username option, for HTTP Basic authentication.

String

personalAccessToken (security)

The personal access token to authenticate with DHIS2, sent as an ApiToken in the Authorization header. Cannot be combined with username and password.

String

username (security)

The username of the DHIS2 user to call the API as, with HTTP Basic authentication together with the password option. Cannot be combined with personalAccessToken.

String

API Parameters (5 APIs)

The DHIS2 endpoint is an API-based component and has additional parameters based on which API name and API method is used. The API name and API method is located in the endpoint URI as the apiName/methodName path parameters:

dhis2:apiName/methodName

There are 5 API names as listed in the table below:

API Name Type Description

delete

Both

Delete resources in DHIS2 with HTTP DELETE

get

Both

Fetch resources from DHIS2 with HTTP GET

post

Both

Create resources and import data in DHIS2 with HTTP POST

put

Both

Update resources in DHIS2 with HTTP PUT

resourceTables

Both

Generate the DHIS2 analytics tables

Each API is documented in the following sections to come.

API: delete

Both producer and consumer are supported

The delete API is defined in the syntax as follows:

dhis2:delete/methodName?[parameters]

The 1 method(s) is(are) listed in the table below, followed by detailed syntax for each method. (API methods can have a shorthand alias name which can be used in the syntax instead of the name)

Method Alias Description

resource

Delete a resource in DHIS2 with HTTP DELETE

Method resource

Signatures:

  • java.io.InputStream resource(String path, Object resource, java.util.Map<String, Object> queryParams);

The dhis2/resource API method has the parameters listed in the table below:

Parameter Description Type

path

The path of the resource, relative to the base API URL, such as organisationUnits/jUb8gELQApl.

String

queryParams

Extra query parameters to add to the request URL. Each value is a String, or a List of String to repeat the parameter with each value.

Map

resource

An optional resource to send as the JSON body of the request: a String with the JSON as it is, or an object that is serialized to JSON. The message body is used only when inBody is set to resource; by default the request has an empty body.

Object

In addition to the parameters above, the dhis2 API can also use any of the Query Parameters.

Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format CamelDhis2.parameter. The inBody parameter overrides message header, i.e., the endpoint parameter inBody=myParameterNameHere would override a CamelDhis2.myParameterNameHere header.

API: get

Both producer and consumer are supported

The get API is defined in the syntax as follows:

dhis2:get/methodName?[parameters]

The 2 method(s) is(are) listed in the table below, followed by detailed syntax for each method. (API methods can have a shorthand alias name which can be used in the syntax instead of the name)

Method Alias Description

collection

Fetch the items of a DHIS2 collection, one Dhis2Resource per item

resource

Fetch a resource from DHIS2 as JSON

Method collection

Signatures:

  • java.util.Iterator<org.apache.camel.component.dhis2.api.Dhis2Resource> collection(String path, String arrayName, Boolean paging, String fields, java.util.List<String> filter, org.apache.camel.component.dhis2.api.RootJunctionEnum rootJunction, java.util.Map<String, Object> queryParams);

The dhis2/collection API method has the parameters listed in the table below:

Parameter Description Type

arrayName

The name of the JSON array in the response that holds the items, such as organisationUnits.

String

fields

The fields to return, in the DHIS2 field filter syntax of the fields query parameter, such as id,name or :all. DHIS2 returns its default fields when not set.

String

filter

The object filters, each in the DHIS2 syntax property:operator:value of the filter query parameter, such as phoneNumber:!null. Each filter is sent as its own filter parameter.

List

paging

Whether to fetch the collection one page at a time, with the page size of DHIS2, requesting the next page when the iterator reaches the end of the current one. By default the whole collection is fetched in one request with paging=false.

Boolean

path

The path of the collection, relative to the base API URL, such as organisationUnits.

String

queryParams

Extra query parameters to add to the request URL. Each value is a String, or a List of String to repeat the parameter with each value.

Map

rootJunction

How DHIS2 combines several filters: AND to match all of them, OR to match any of them. When not set, DHIS2 uses AND.

RootJunctionEnum

Method resource

Signatures:

  • java.io.InputStream resource(String path, String fields, java.util.List<String> filter, org.apache.camel.component.dhis2.api.RootJunctionEnum rootJunction, java.util.Map<String, Object> queryParams);

The dhis2/resource API method has the parameters listed in the table below:

Parameter Description Type

fields

The fields to return, in the DHIS2 field filter syntax of the fields query parameter, such as id,name or :all. DHIS2 returns its default fields when not set.

String

filter

The object filters, each in the DHIS2 syntax property:operator:value of the filter query parameter, such as phoneNumber:!null. Each filter is sent as its own filter parameter.

List

path

The path of the resource, relative to the base API URL, such as organisationUnits/O6uvpzGd5pu.

String

queryParams

Extra query parameters to add to the request URL. Each value is a String, or a List of String to repeat the parameter with each value.

Map

rootJunction

How DHIS2 combines several filters: AND to match all of them, OR to match any of them. When not set, DHIS2 uses AND.

RootJunctionEnum

In addition to the parameters above, the dhis2 API can also use any of the Query Parameters.

Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format CamelDhis2.parameter. The inBody parameter overrides message header, i.e., the endpoint parameter inBody=myParameterNameHere would override a CamelDhis2.myParameterNameHere header.

API: post

Both producer and consumer are supported

The post API is defined in the syntax as follows:

dhis2:post/methodName?[parameters]

The 1 method(s) is(are) listed in the table below, followed by detailed syntax for each method. (API methods can have a shorthand alias name which can be used in the syntax instead of the name)

Method Alias Description

resource

Send a resource to DHIS2 with HTTP POST

Method resource

Signatures:

  • java.io.InputStream resource(String path, Object resource, java.util.Map<String, Object> queryParams);

The dhis2/resource API method has the parameters listed in the table below:

Parameter Description Type

path

The path of the resource, relative to the base API URL, such as dataValueSets.

String

queryParams

Extra query parameters to add to the request URL. Each value is a String, or a List of String to repeat the parameter with each value.

Map

resource

The resource to send as the JSON body of the request: a String with the JSON as it is, or an object, such as a DHIS2 model class or a Map, that is serialized to JSON. When not set, the producer sends the message body. An empty body is sent when there is none.

Object

In addition to the parameters above, the dhis2 API can also use any of the Query Parameters.

Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format CamelDhis2.parameter. The inBody parameter overrides message header, i.e., the endpoint parameter inBody=myParameterNameHere would override a CamelDhis2.myParameterNameHere header.

API: put

Both producer and consumer are supported

The put API is defined in the syntax as follows:

dhis2:put/methodName?[parameters]

The 1 method(s) is(are) listed in the table below, followed by detailed syntax for each method. (API methods can have a shorthand alias name which can be used in the syntax instead of the name)

Method Alias Description

resource

Send a resource to DHIS2 with HTTP PUT

Method resource

Signatures:

  • java.io.InputStream resource(String path, Object resource, java.util.Map<String, Object> queryParams);

The dhis2/resource API method has the parameters listed in the table below:

Parameter Description Type

path

The path of the resource, relative to the base API URL, such as organisationUnits/jUb8gELQApl.

String

queryParams

Extra query parameters to add to the request URL. Each value is a String, or a List of String to repeat the parameter with each value.

Map

resource

The resource to send as the JSON body of the request: a String with the JSON as it is, or an object, such as a DHIS2 model class or a Map, that is serialized to JSON. When not set, the producer sends the message body. An empty body is sent when there is none.

Object

In addition to the parameters above, the dhis2 API can also use any of the Query Parameters.

Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format CamelDhis2.parameter. The inBody parameter overrides message header, i.e., the endpoint parameter inBody=myParameterNameHere would override a CamelDhis2.myParameterNameHere header.

API: resourceTables

Both producer and consumer are supported

The resourceTables API is defined in the syntax as follows:

dhis2:resourceTables/methodName?[parameters]

The 1 method(s) is(are) listed in the table below, followed by detailed syntax for each method. (API methods can have a shorthand alias name which can be used in the syntax instead of the name)

Method Alias Description

analytics

Start the generation of the DHIS2 analytics tables and, unless async is set, wait until it completes

Method analytics

Signatures:

  • void analytics(Boolean skipAggregate, Boolean skipEvents, Integer lastYears, Integer interval, Boolean async);

The dhis2/analytics API method has the parameters listed in the table below:

Parameter Description Type

async

Whether to return as soon as DHIS2 has started the analytics task. By default (false) the call waits until the task is completed and fails if DHIS2 reports an error for it. The wait has no time limit.

Boolean

interval

The time in milliseconds to wait between two checks of the status of the analytics task, when async is not true. Defaults to 30000.

Integer

lastYears

The number of last years of data to generate the tables for. When not set, DHIS2 generates them for all years.

Integer

skipAggregate

Whether DHIS2 skips the generation of the aggregate data and completeness data. When not set, DHIS2 does not skip it.

Boolean

skipEvents

Whether DHIS2 skips the generation of the event data. When not set, DHIS2 does not skip it.

Boolean

In addition to the parameters above, the dhis2 API can also use any of the Query Parameters.

Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format CamelDhis2.parameter. The inBody parameter overrides message header, i.e., the endpoint parameter inBody=myParameterNameHere would override a CamelDhis2.myParameterNameHere header.

Message Body

The message body at each side of the DHIS2 component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.

Side Body Description

Consumer

stream

The return value of the method: one message per poll with the JSON response of get/resource as a stream; get/collection gives one message per item, a Dhis2Resource, which is a Map of the JSON fields.

  • With methodName=collection: map

  • With apiName=RESOURCE_TABLES: null

Producer input

text, bytes, stream, file, map, list, pojo or null

post and put send the body as the JSON resource of the request, also without inBody: text, bytes, a stream or a file as the JSON it holds, and a Map, a List or a POJO, such as a DHIS2 model class, serialized to JSON by Jackson; no body sends none. delete sends a resource only when given by inBody=resource or the CamelDhis2.resource header. get and resourceTables do not use the body.

  • With apiName=GET: any

  • With apiName=DELETE: any

  • With apiName=RESOURCE_TABLES: any

Producer output

stream

The JSON response of DHIS2 as a stream, such as the resource of get/resource or the import summary of post, put and delete: unmarshal it with json. get/collection gives an Iterator of Dhis2Resource, read once, which are Maps of the JSON fields that convertBodyTo turns into a class of org.hisp.dhis.api.model; resourceTables/analytics gives null.

  • With methodName=collection: iterator

  • With apiName=RESOURCE_TABLES: null

The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.

This is an API-based component, so per-call parameters can be supplied through Camel-prefixed exchange headers in addition to the endpoint options. If the route consumes messages from untrusted producers, strip these internal headers at the trust boundary — for example with removeHeaders("Camel*") — before the message reaches this component, so that a sender cannot override the API call. See the Camel security model for details.

Message body

post/resource and put/resource send the message body as the JSON resource of the request: text, bytes, a stream or a file as the JSON they hold, and a Map, a List or a POJO, such as a DHIS2 model class, serialized to JSON. delete/resource does not send the message body: set inBody=resource or the CamelDhis2.resource header to send a resource with the delete.

The get/collection consumer sends one message per item of the collection, a Dhis2Resource, which is a Map of the JSON fields of the item.

Examples

  • Fetch an organisation unit by ID:

    • Java

    • YAML

    from("direct:getResource")
        .to("dhis2:get/resource?path=organisationUnits/O6uvpzGd5pu&username=admin&password=district&baseApiUrl=https://play.im.dhis2.org/stable-2-40-5/api")
        .unmarshal()
        .json(org.hisp.dhis.api.model.v40_2_2.OrganisationUnit.class);
    - route:
        from:
          uri: direct:getResource
          steps:
            - to:
                uri: dhis2:get/resource
                parameters:
                  path: organisationUnits/O6uvpzGd5pu
                  username: admin
                  password: district
                  baseApiUrl: https://play.im.dhis2.org/stable-2-40-5/api
            - unmarshal:
                json:
                  unmarshalType: org.hisp.dhis.api.model.v40_2_2.OrganisationUnit
  • Fetch all organisation units:

    • Java

    • YAML

    from("direct:getCollection")
        .to("dhis2:get/collection?path=organisationUnits&arrayName=organisationUnits&username=admin&password=district&baseApiUrl=https://play.im.dhis2.org/stable-2-40-5/api")
        .split().body()
        .convertBodyTo(org.hisp.dhis.api.model.v40_2_2.OrganisationUnit.class).log("${body}");
    - route:
        from:
          uri: direct:getCollection
          steps:
            - to:
                uri: dhis2:get/collection
                parameters:
                  path: organisationUnits
                  arrayName: organisationUnits
                  username: admin
                  password: district
                  baseApiUrl: https://play.im.dhis2.org/stable-2-40-5/api
            - split:
                expression:
                  simple:
                    expression: ${body}
                steps:
                  - convertBodyTo:
                      type: org.hisp.dhis.api.model.v40_2_2.OrganisationUnit
                  - log:
                      message: ${body}
  • Fetch all organisation unit codes:

    • Java

    • YAML

    from("direct:getCollection")
        .to("dhis2:get/collection?path=organisationUnits&arrayName=organisationUnits&username=admin&password=district&baseApiUrl=https://play.im.dhis2.org/stable-2-40-5/api")
        .split().body()
        .convertBodyTo(org.hisp.dhis.api.model.v40_2_2.OrganisationUnit.class).log("${body}");
    - route:
        from:
          uri: direct:getCollection
          steps:
            - to:
                uri: dhis2:get/collection
                parameters:
                  path: organisationUnits
                  arrayName: organisationUnits
                  username: admin
                  password: district
                  baseApiUrl: https://play.im.dhis2.org/stable-2-40-5/api
                  fields: code
            - split:
                expression:
                  simple:
                    expression: ${body}
                steps:
                  - convertBodyTo:
                      type: org.hisp.dhis.api.model.v40_2_2.OrganisationUnit
                  - log:
                      message: ${body}
  • Fetch users with a phone number:

    • Java

    • YAML

    from("direct:getCollection")
        .to("dhis2://get/collection?path=users&filter=phoneNumber:!null:&arrayName=users&username=admin&password=district&baseApiUrl=https://play.im.dhis2.org/stable-2-40-5/api")
        .split().body()
        .convertBodyTo(org.hisp.dhis.api.model.v40_2_2.User.class)
        .log("${body}");
    - route:
        from:
          uri: direct:getCollection
          steps:
            - to:
                uri: dhis2:get/collection
                parameters:
                  path: users
                  arrayName: users
                  username: admin
                  password: district
                  baseApiUrl: https://play.im.dhis2.org/stable-2-40-5/api
                  filter: "phoneNumber:!null:"
            - split:
                expression:
                  simple:
                    expression: ${body}
                steps:
                  - convertBodyTo:
                      type: org.hisp.dhis.api.model.v40_2_2.User
                  - log:
                      message: ${body}
  • Save a data value set

    • Java

    • YAML

    from("direct:postResource")
        .setBody(exchange -> new DataValueSet().withCompleteDate(
                ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_LOCAL_DATE))
            .withOrgUnit("O6uvpzGd5pu")
            .withDataSet("lyLU2wR22tC").withPeriod(PeriodBuilder.monthOf(new Date(), -1))
            .withDataValues(
                List.of(new DataValue().withDataElement("aIJZ2d2QgVV").withValue("20"))))
        .to("dhis2://post/resource?path=dataValueSets&username=admin&password=district&baseApiUrl=https://play.im.dhis2.org/stable-2-40-5/api")
        .unmarshal().json()
        .choice()
        .when().groovy("body.status != 'OK'")
            .log(LoggingLevel.ERROR, "Import error from DHIS2 while saving data value set => ${body}")
        .end();
    - route:
        from:
          uri: direct:postResource
          steps:
            - setBody:
                groovy: |
                  new org.hisp.dhis.api.model.v40_2_2.DataValueSet()
                    .withCompleteDate(java.time.ZonedDateTime.now(java.time.ZoneOffset.UTC).format(java.time.format.DateTimeFormatter.ISO_LOCAL_DATE))
                    .withOrgUnit('O6uvpzGd5pu')
                    .withDataSet('lyLU2wR22tC')
                    .withPeriod(org.hisp.dhis.integration.sdk.support.period.PeriodBuilder.monthOf(new Date(), -1))
                    .withDataValues([new org.hisp.dhis.api.model.v40_2_2.DataValue().withDataElement('aIJZ2d2QgVV').withValue('20')])
            - to:
                uri: dhis2:post/resource
                parameters:
                  path: dataValueSets
                  username: admin
                  password: district
                  baseApiUrl: https://play.im.dhis2.org/stable-2-40-5/api
            - unmarshal:
                json: {}
            - choice:
                when:
                  - groovy: body.status != 'OK'
                    steps:
                      - log:
                          loggingLevel: ERROR
                          message: Import error from DHIS2 while saving data value set => ${body}
  • Update an organisation unit

    • Java

    • YAML

    from("direct:putResource")
        .setBody(exchange -> new OrganisationUnit().withName("Acme").withShortName("Acme").withOpeningDate(new Date()))
        .to("dhis2://put/resource?path=organisationUnits/jUb8gELQApl&username=admin&password=district&baseApiUrl=https://play.im.dhis2.org/stable-2-40-5/api")
        .unmarshal().json()
        .choice()
        .when().groovy("body.status != 'OK'")
            .log(LoggingLevel.ERROR, "Import error from DHIS2 while updating org unit => ${body}")
        .end();
    - route:
        from:
          uri: direct:putResource
          steps:
            - setBody:
                groovy: |
                  new org.hisp.dhis.api.model.v40_2_2.OrganisationUnit()
                    .withName('Acme')
                    .withShortName('Acme')
                    .withOpeningDate(new Date())
            - to:
                uri: dhis2:put/resource
                parameters:
                  path: organisationUnits/jUb8gELQApl
                  username: admin
                  password: district
                  baseApiUrl: https://play.im.dhis2.org/stable-2-40-5/api
            - unmarshal:
                json: {}
            - choice:
                when:
                  - groovy: body.status != 'OK'
                    steps:
                      - log:
                          loggingLevel: ERROR
                          message: Import error from DHIS2 while updating org unit => ${body}
  • Delete an organisation unit

    • Java

    • YAML

    from("direct:deleteResource")
        .to("dhis2://delete/resource?path=organisationUnits/jUb8gELQApl&username=admin&password=district&baseApiUrl=https://play.im.dhis2.org/stable-2-40-5/api")
        .unmarshal().json()
        .choice()
        .when().groovy("body.status != 'OK'")
            .log(LoggingLevel.ERROR, "Import error from DHIS2 while deleting org unit => ${body}")
        .end();
    - route:
        from:
          uri: direct:deleteResource
          steps:
            - to:
                uri: dhis2:delete/resource
                parameters:
                  path: organisationUnits/jUb8gELQApl
                  username: admin
                  password: district
                  baseApiUrl: https://play.im.dhis2.org/stable-2-40-5/api
            - unmarshal:
                json: {}
            - choice:
                when:
                  - groovy: body.status != 'OK'
                    steps:
                      - log:
                          loggingLevel: ERROR
                          message: Import error from DHIS2 while deleting org unit => ${body}
  • Run analytics

    • Java

    • YAML

    from("direct:resourceTablesAnalytics")
        .to("dhis2://resourceTables/analytics?skipAggregate=false&skipEvents=true&lastYears=1&username=admin&password=district&baseApiUrl=https://play.im.dhis2.org/stable-2-40-5/api");
    - route:
        from:
          uri: direct:resourceTablesAnalytics
          steps:
            - to:
                uri: dhis2:resourceTables/analytics
                parameters:
                  skipAggregate: false
                  skipEvents: true
                  lastYears: 1
                  username: admin
                  password: district
                  baseApiUrl: https://play.im.dhis2.org/stable-2-40-5/api
  • Reference DHIS2 client

    • Java

    • YAML

    Dhis2Client dhis2Client = Dhis2ClientBuilder.newClient("https://play.im.dhis2.org/stable-2-40-5/api", "admin", "district").build();
    getCamelContext().getRegistry().bind("dhis2Client", dhis2Client);
    
    from("direct:resourceTablesAnalytics")
        .to("dhis2://resourceTables/analytics?skipAggregate=true&skipEvents=true&lastYears=1&client=#dhis2Client");
    - beans:
      - name: dhis2Client
        type: org.hisp.dhis.integration.sdk.api.Dhis2Client
        scriptLanguage: groovy
        script: >
          org.hisp.dhis.integration.sdk.Dhis2ClientBuilder.newClient('https://play.im.dhis2.org/stable-2-40-5/api', 'admin', 'district').build()
    
    - route:
        from:
          uri: direct:resourceTablesAnalytics
          steps:
            - to:
                uri: dhis2:resourceTables/analytics
                parameters:
                  skipAggregate: true
                  skipEvents: true
                  lastYears: 1
                  client: "#dhis2Client"
  • Set custom query parameters

    • Java

    • YAML

    from("direct:clearCache")
        .setHeader("CamelDhis2.queryParams", constant(Map.of("cacheClear", "true")))
        .to("dhis2://post/resource?path=maintenance&client=#dhis2Client");
    - route:
        from:
          uri: direct:clearCache
          steps:
            - setHeader:
                name: CamelDhis2.queryParams
                groovy: "['cacheClear':'true']"
            - to:
                uri: dhis2:post/resource
                parameters:
                  path: maintenance
                  client: "#dhis2Client"