Camel Components

GitHub2

Since Camel 4.18

Both producer and consumer are supported

The GitHub2 component interacts with the GitHub API by encapsulating the kohsuke github-api library. It currently provides polling for new pull requests, pull request comments, tags, commits, and events. It is also able to produce comments on pull requests, as well as close the pull request entirely.

This component supports GitHub Enterprise by allowing you to specify a custom API URL.

Rather than webhooks, this endpoint relies on simple polling. Reasons include:

  • Concern for reliability/stability

  • The types of payloads we’re polling aren’t typically large (plus, paging is available in the API)

  • The need to support apps running somewhere not publicly accessible where a webhook would fail

Note that the GitHub API is fairly expansive. Therefore, this component could be easily expanded to provide additional interactions.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-github2</artifactId>
    <version>${camel-version}</version>
</dependency>

URI format

github2://endpoint[?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 GitHub2 component supports the following options which are listed below.

Name Description Default Type

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

apiUrl (advanced)

The URL of the GitHub REST API. Set it for GitHub Enterprise Server, such as https://github.example.com/api/v3. If not set, https://api.github.com is used.

String

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

healthCheckConsumerEnabled (health)

Used for enabling or disabling all consumer based health checks from this component.

true

boolean

healthCheckProducerEnabled (health)

Used for enabling or disabling all producer based health checks from this component. Notice: Camel has by default disabled all producer based health-checks. You can turn on producer checks globally by setting camel.health.producersEnabled=true.

true

boolean

oauthToken (security)

The GitHub token that authenticates the API requests, sent in the Authorization header: a personal access token (classic or fine-grained), an OAuth app token or a GitHub App installation token. Required, on the component or on the endpoint.

String

Endpoint Options

The GitHub2 endpoint is configured using URI syntax:

github2:type/branchName

With the following path and query parameters:

Path Parameters

Name Description Default Type

type (common)

Required What the consumer polls (commit, pullRequest, pullRequestComment, tag or event) or what the producer does (pullRequestComment, closePullRequest, pullRequestState, pullRequestFiles, getCommitFile or createIssue).

Enum values:

  • CLOSEPULLREQUEST

  • PULLREQUESTCOMMENT

  • COMMIT

  • PULLREQUEST

  • TAG

  • PULLREQUESTSTATE

  • PULLREQUESTFILES

  • GETCOMMITFILE

  • CREATEISSUE

  • EVENT

GitHub2Type

branchName (consumer)

The branch whose commits the commit consumer polls, such as main. Required for the commit consumer, and not used by the other types.

String

Query Parameters

Name Description Default Type

repoName (common)

Required The name of the repository, without the owner.

String

repoOwner (common)

Required The owner of the repository: the login of a user or of an organization.

String

commitMessageAsBody (consumer)

Whether the commit consumer sets the commit message as the body (true), or the org.kohsuke.github.GHCommit (false).

true

boolean

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

startingSha (consumer)

Where the commit consumer starts: last routes only the commits that are pushed after the consumer started, beginning routes up to the 100 newest commits of the branch on the first poll, and a commit SHA routes the commits that come after that commit on the branch. Applies again each time the consumer starts.

last

String

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

eventFetchStrategy (consumer (advanced))

A custom strategy that fetches the events for the event consumer. By default the consumer lists the events of the repository (GET /repos/{owner}/{repo}/events).

GitHub2EventFetchStrategy

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

encoding (producer)

The charset of the content of the file for the getCommitFile producer (the default charset of the JVM if not set).

String

state (producer)

The state of the commit status that the pullRequestState producer creates. GitHub rejects the request when it is not set.

Enum values:

  • error

  • failure

  • pending

  • success

String

targetUrl (producer)

The URL that the commit status of the pullRequestState producer links to, such as the page of a build.

String

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

apiUrl (advanced)

The URL of the GitHub REST API. Set it for GitHub Enterprise Server, such as https://github.example.com/api/v3. If not set, https://api.github.com is used.

String

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

oauthToken (security)

The GitHub token that authenticates the API requests, sent in the Authorization header: a personal access token (classic or fine-grained), an OAuth app token or a GitHub App installation token. Required, on the component or on the endpoint.

String

Message Headers

The GitHub2 component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelGitHubPullRequest (common)

Constant: GITHUB_PULLREQUEST

The number of the pull request. Set by the pullRequest and pullRequestComment consumers, and required by the pullRequestComment, closePullRequest and pullRequestFiles producers.

GHPullRequest or Integer

CamelGitHubInResponseTo (producer)

Constant: GITHUB_INRESPONSETO

The id of a comment to reply to. Not used: the pullRequestComment producer always adds a new comment to the conversation of the pull request.

Long

CamelGitHubPullRequestHeadCommitSha (common)

Constant: GITHUB_PULLREQUEST_HEAD_COMMIT_SHA

The SHA of the head commit of the pull request. Set by the pullRequest consumer, and required by the pullRequestState producer, which creates the commit status on this commit.

String

CamelGitHubIssueTitle (producer)

Constant: GITHUB_ISSUE_TITLE

The title of the issue that the createIssue producer creates (required).

String

CamelGitHubCommitAuthor (consumer)

Constant: GITHUB_COMMIT_AUTHOR

The name in the GitHub profile of the author of the commit, or the author name that git recorded when the user cannot be looked up. Not set when the author has no GitHub account.

String

CamelGitHubCommitCommitter (consumer)

Constant: GITHUB_COMMIT_COMMITTER

The name in the GitHub profile of the committer of the commit, or the committer name that git recorded when the user cannot be looked up. Not set when the committer has no GitHub account.

String

CamelGitHubCommitSha (common)

Constant: GITHUB_COMMIT_SHA

The SHA of the commit. Set by the commit consumer, and required by the getCommitFile producer, which reads the file at this commit: a full SHA of 40 hexadecimal characters, not a branch or tag name.

String

CamelGitHubFilePath (producer)

Constant: GITHUB_FILE_PATH

The path of the file in the repository for the getCommitFile producer. If not set, the body is the path.

String

CamelGitHubCommitUrl (consumer)

Constant: GITHUB_COMMIT_URL

The URL of the web page of the commit on GitHub.

String

CamelGitHubEventPayload (consumer)

Constant: GITHUB_EVENT_PAYLOAD

The org.kohsuke.github.GHEventInfo of the event, with its actor, repository and creation time; getPayload(Class) gives the payload of the event.

GHEventPayload

Message Body

The message body at each side of the GitHub2 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

text or null

One message per new item, oldest first. commit gives the commit message (null when the data of the commit cannot be loaded), or the GHCommit with commitMessageAsBody=false, and event the type of the event, such as PUSH, with the GHEventInfo in the CamelGitHubEventPayload header.

  • With commitMessageAsBody=false: pojo (org.kohsuke.github.GHCommit)

  • With type=PULLREQUEST: pojo (org.kohsuke.github.GHPullRequest)

  • With type=PULLREQUESTCOMMENT: pojo (org.kohsuke.github.GHIssueComment)

  • With type=TAG: pojo (org.kohsuke.github.GHTag)

  • With type=EVENT: text (java.lang.String)

Producer input

any

Read as text: the comment for pullRequestComment, which needs a body, and the description of the issue for createIssue and of the commit status for pullRequestState; a Map or a POJO is sent as its toString(), so marshal it first. getCommitFile reads the path of the file from the body when the CamelGitHubFilePath header is not set, and the other types read only headers.

  • With type=PULLREQUESTCOMMENT: text, bytes, stream or file

  • With type=CREATEISSUE: null, text, bytes, stream or file

  • With type=PULLREQUESTSTATE: null, text, bytes, stream or file

Producer output

unknown

The GHPullRequest as read before the close for closePullRequest, the GHIssueComment for pullRequestComment when the exchange expects a reply (InOut), otherwise the body is unchanged, the GHCommitStatus for pullRequestState, a List of GHPullRequestFileDetail for pullRequestFiles, the content of the file as text for getCommitFile, and the GHIssue for createIssue.

  • With type=CLOSEPULLREQUEST: pojo (org.kohsuke.github.GHPullRequest)

  • With type=PULLREQUESTCOMMENT: pojo or unchanged

  • With type=PULLREQUESTSTATE: pojo (org.kohsuke.github.GHCommitStatus)

  • With type=PULLREQUESTFILES: list (java.util.List<org.kohsuke.github.GHPullRequestFileDetail>)

  • With type=GETCOMMITFILE: text (java.lang.String)

  • With type=CREATEISSUE: pojo (org.kohsuke.github.GHIssue)

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.

Usage

Configuring authentication

The GitHub2 component requires to be configured with an authentication token on either the component or endpoint level.

For example, to set it on the component:

Java-only: programmatic component configuration
GitHub2Component ghc = context.getComponent("github2", GitHub2Component.class);
ghc.setOauthToken("mytoken");

GitHub Enterprise

To use with GitHub Enterprise, set the apiUrl parameter to your GitHub Enterprise API endpoint:

  • Java

  • XML

  • YAML

from("github2:commit/main?repoOwner=myorg&repoName=myrepo&apiUrl=https://github.mycompany.com/api/v3")
    .to("log:commits");
<route>
  <from uri="github2:commit/main?repoOwner=myorg&amp;repoName=myrepo&amp;apiUrl=https://github.mycompany.com/api/v3"/>
  <to uri="log:commits"/>
</route>
- route:
    from:
      uri: github2:commit/main
      parameters:
        repoOwner: myorg
        repoName: myrepo
        apiUrl: "https://github.mycompany.com/api/v3"
      steps:
        - to:
            uri: log:commits

Consumer Endpoints

Endpoint Context Body Type

pullRequest

polling

org.kohsuke.github.GHPullRequest

pullRequestComment

polling

org.kohsuke.github.GHIssueComment

tag

polling

org.kohsuke.github.GHTag

commit

polling

org.kohsuke.github.GHCommit or String with commit message and headers with some metadata. This can be configured by the commitMessageAsBody option.

event

polling

String with the type of the event, such as PUSH, and the org.kohsuke.github.GHEventInfo in the CamelGitHubEventPayload header

Producer Endpoints

Endpoint Body Message Headers

pullRequestComment

String (comment text)

- CamelGitHubPullRequest (integer) (REQUIRED): Pull request number.

The comment is always added to the conversation of the pull request: the CamelGitHubInResponseTo header is not used.

closePullRequest

none

- CamelGitHubPullRequest (integer) (REQUIRED): Pull request number.

createIssue

String (issue body text)

- CamelGitHubIssueTitle (String) (REQUIRED): Issue Title.

pullRequestState

String (description of the status)

- CamelGitHubPullRequestHeadCommitSha (String) (REQUIRED): The sha of the commit to set the status on. Sets the commit status on a pull request.

pullRequestFiles

none

- CamelGitHubPullRequest (integer) (REQUIRED): Pull request number. Returns the list of files changed in a pull request.

getCommitFile

String (the path of the file, if the CamelGitHubFilePath header is not set)

- CamelGitHubCommitSha (String) (REQUIRED): The commit id (40 hexadecimal characters; a branch or tag name is not accepted). - CamelGitHubFilePath (String): The path of the file in the repository, such as docs/README.md. If not set, the body is the path. Returns the content of the file in the tree of that commit, as a String (decoded with the encoding option, or the default charset of the JVM).

Example: Consuming commits

  • Java

  • XML

  • YAML

from("github2:commit/main?repoOwner=apache&repoName=camel&oauthToken=mytoken")
    .log("New commit: ${header.CamelGitHubCommitSha} by ${header.CamelGitHubCommitAuthor}")
    .to("direct:processCommit");
<route>
  <from uri="github2:commit/main?repoOwner=apache&amp;repoName=camel&amp;oauthToken=mytoken"/>
  <log message="New commit: ${header.CamelGitHubCommitSha} by ${header.CamelGitHubCommitAuthor}"/>
  <to uri="direct:processCommit"/>
</route>
- route:
    from:
      uri: github2:commit/main
      parameters:
        repoOwner: apache
        repoName: camel
        oauthToken: mytoken
      steps:
        - log:
            message: "New commit: ${header.CamelGitHubCommitSha} by ${header.CamelGitHubCommitAuthor}"
        - to:
            uri: direct:processCommit

Example: Creating an issue

  • Java

  • XML

  • YAML

from("direct:createIssue")
    .setHeader("CamelGitHubIssueTitle", constant("Bug Report"))
    .setBody(constant("This is the issue description"))
    .to("github2:createIssue?repoOwner=apache&repoName=camel&oauthToken=mytoken");
<route>
  <from uri="direct:createIssue"/>
  <setHeader name="CamelGitHubIssueTitle">
    <constant>Bug Report</constant>
  </setHeader>
  <setBody>
    <constant>This is the issue description</constant>
  </setBody>
  <to uri="github2:createIssue?repoOwner=apache&amp;repoName=camel&amp;oauthToken=mytoken"/>
</route>
- route:
    from:
      uri: direct:createIssue
      steps:
        - setHeader:
            name: CamelGitHubIssueTitle
            constant: Bug Report
        - setBody:
            constant: This is the issue description
        - to:
            uri: github2:createIssue
            parameters:
              repoOwner: apache
              repoName: camel
              oauthToken: mytoken