├── examples ├── automated-summary-report │ ├── .github │ │ └── README.md │ ├── Ballerina.toml │ ├── Slack automated summary report.md │ └── main.bal ├── survey-feedback-analysis │ ├── .github │ │ └── README.md │ ├── Ballerina.toml │ ├── Slack survey feedback anaysis.md │ └── main.bal ├── README.md ├── build.sh └── build.gradle ├── ballerina ├── icon.png ├── Ballerina.toml ├── tests │ ├── README.md │ ├── tests.bal │ └── mock_service.bal ├── build.gradle ├── README.md ├── Dependencies.toml └── utils.bal ├── docs ├── setup │ └── resources │ │ ├── sign-in.png │ │ ├── copy-token.jpg │ │ ├── add-features.png │ │ ├── create-slack-app.png │ │ ├── install-workspace.jpg │ │ ├── token-permissions.png │ │ └── create-slack-app-2.png ├── license.txt └── spec │ ├── build.gradle │ ├── sanitations.md │ └── sanitations.bal ├── gradle ├── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties └── libs.versions.toml ├── .github ├── pull_request_template.md ├── CODEOWNERS └── workflows │ ├── daily-build.yml │ ├── release.yml │ ├── ci.yml │ ├── pull-request.yml │ ├── dev-stg-release.yml │ └── regenerate-connector.yml ├── .gitattributes ├── gradle.properties ├── issue_template.md ├── .gitignore ├── pull_request_template.md ├── settings.gradle ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE /examples/automated-summary-report/.github/README.md: -------------------------------------------------------------------------------- 1 | ../Slack automated summary report.md -------------------------------------------------------------------------------- /examples/survey-feedback-analysis/.github/README.md: -------------------------------------------------------------------------------- 1 | ../Slack survey feedback anaysis.md -------------------------------------------------------------------------------- /ballerina/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ballerina-platform/module-ballerinax-slack/HEAD/ballerina/icon.png -------------------------------------------------------------------------------- /docs/setup/resources/sign-in.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ballerina-platform/module-ballerinax-slack/HEAD/docs/setup/resources/sign-in.png -------------------------------------------------------------------------------- /docs/setup/resources/copy-token.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ballerina-platform/module-ballerinax-slack/HEAD/docs/setup/resources/copy-token.jpg -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ballerina-platform/module-ballerinax-slack/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /docs/setup/resources/add-features.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ballerina-platform/module-ballerinax-slack/HEAD/docs/setup/resources/add-features.png -------------------------------------------------------------------------------- /docs/setup/resources/create-slack-app.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ballerina-platform/module-ballerinax-slack/HEAD/docs/setup/resources/create-slack-app.png -------------------------------------------------------------------------------- /docs/setup/resources/install-workspace.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ballerina-platform/module-ballerinax-slack/HEAD/docs/setup/resources/install-workspace.jpg -------------------------------------------------------------------------------- /docs/setup/resources/token-permissions.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ballerina-platform/module-ballerinax-slack/HEAD/docs/setup/resources/token-permissions.png -------------------------------------------------------------------------------- /docs/setup/resources/create-slack-app-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ballerina-platform/module-ballerinax-slack/HEAD/docs/setup/resources/create-slack-app-2.png -------------------------------------------------------------------------------- /examples/automated-summary-report/Ballerina.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | org = "wso2" 3 | name = "automated_summary_report" 4 | version = "0.1.0" 5 | distribution = "2201.9.0" 6 | -------------------------------------------------------------------------------- /examples/survey-feedback-analysis/Ballerina.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | org = "wso2" 3 | name = "survey_feedback_analysis" 4 | version = "0.1.0" 5 | distribution = "2201.9.0" 6 | -------------------------------------------------------------------------------- /gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | # This file was generated by the Gradle 'init' task. 2 | # https://docs.gradle.org/current/userguide/platforms.html#sub::toml-dependencies-format 3 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | ## Purpose 2 | 3 | ## Examples 4 | 5 | ## Checklist 6 | - [ ] Linked to an issue 7 | - [ ] Updated the changelog 8 | - [ ] Added tests 9 | - [ ] Updated the spec 10 | - [ ] Checked native-image compatibility 11 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # 2 | # https://help.github.com/articles/dealing-with-line-endings/ 3 | # 4 | # Linux start script should use lf 5 | /gradlew text eol=lf 6 | 7 | # These are Windows script files and should use crlf 8 | *.bat text eol=crlf 9 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Lines starting with '#' are comments. 2 | # Each line is a file pattern followed by one or more owners. 3 | 4 | # See: https://help.github.com/articles/about-codeowners/ 5 | 6 | # These owners will be the default owners for everything in the repo. 7 | * @NipunaRanasinghe 8 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.caching=true 2 | group=io.ballerina.lib 3 | version=5.0.0-SNAPSHOT 4 | 5 | checkstylePluginVersion=10.12.0 6 | spotbugsPluginVersion=5.0.14 7 | shadowJarPluginVersion=8.1.1 8 | downloadPluginVersion=5.4.0 9 | releasePluginVersion=2.8.0 10 | testngVersion=7.6.1 11 | eclipseLsp4jVersion=0.12.0 12 | ballerinaGradlePluginVersion=2.3.0 13 | ballerinaLangVersion=2201.12.2 14 | -------------------------------------------------------------------------------- /.github/workflows/daily-build.yml: -------------------------------------------------------------------------------- 1 | name: Daily build 2 | 3 | on: 4 | schedule: 5 | - cron: "30 2 * * *" 6 | 7 | jobs: 8 | call_workflow: 9 | name: Run Daily Build Workflow 10 | if: ${{ github.repository_owner == 'ballerina-platform' }} 11 | uses: ballerina-platform/ballerina-library/.github/workflows/daily-build-connector-template.yml@main 12 | secrets: inherit 13 | with: 14 | repo-name: module-ballerinax-slack 15 | -------------------------------------------------------------------------------- /ballerina/Ballerina.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | distribution = "2201.12.0" 3 | org = "ballerinax" 4 | name = "slack" 5 | version = "5.0.0" 6 | license = ["Apache-2.0"] 7 | authors = ["Ballerina"] 8 | keywords = ["Communication/Team Chat", "Cost/Freemium", "Vendor/Slack", "Area/Communication", "Type/Connector"] 9 | icon = "icon.png" 10 | repository = "https://github.com/ballerina-platform/module-ballerinax-slack" 11 | 12 | [build-options] 13 | observabilityIncluded = true 14 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Publish Release 2 | 3 | on: 4 | workflow_dispatch: 5 | repository_dispatch: 6 | types: [ stdlib-release-pipeline ] 7 | 8 | jobs: 9 | call_workflow: 10 | name: Run Release Workflow 11 | if: ${{ github.repository_owner == 'ballerina-platform' }} 12 | uses: ballerina-platform/ballerina-library/.github/workflows/release-package-connector-template.yml@main 13 | secrets: inherit 14 | with: 15 | package-name: slack 16 | package-org: ballerinax 17 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | - 2201.[0-9]+.x 8 | repository_dispatch: 9 | types: check_connector_for_breaking_changes 10 | 11 | jobs: 12 | call_workflow: 13 | name: Run Connector Build Workflow 14 | if: ${{ github.repository_owner == 'ballerina-platform' }} 15 | uses: ballerina-platform/ballerina-library/.github/workflows/build-connector-template.yml@main 16 | secrets: inherit 17 | with: 18 | repo-name: module-ballerinax-slack 19 | -------------------------------------------------------------------------------- /.github/workflows/pull-request.yml: -------------------------------------------------------------------------------- 1 | name: PR Build 2 | 3 | concurrency: 4 | group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }} 5 | cancel-in-progress: true 6 | 7 | on: pull_request 8 | 9 | jobs: 10 | call_workflow: 11 | name: Run PR Build Workflow 12 | if: ${{ github.repository_owner == 'ballerina-platform' }} 13 | uses: ballerina-platform/ballerina-library/.github/workflows/pr-build-connector-template.yml@main 14 | secrets: inherit 15 | with: 16 | additional-test-flags: ${{ github.event.pull_request.head.repo.full_name != github.repository && '-x test' || ''}} 17 | -------------------------------------------------------------------------------- /examples/automated-summary-report/Slack automated summary report.md: -------------------------------------------------------------------------------- 1 | # Automated summary report 2 | 3 | This use case demonstrates how the Slack API can be utilized to generate a summarized report of daily stand up chats in the general channel. 4 | 5 | ## Prerequisites 6 | 7 | 1. Generate a Slack token to authenticate the connector as described in the [Setup guide](https://central.ballerina.io/ballerinax/slack/latest#prerequisites). 8 | 9 | 2. For each example, create a `Config.toml` file with the related configuration. Here's an example of what your `Config.toml` file should look: 10 | 11 | ```toml 12 | token = "" 13 | ``` 14 | 15 | ## Run the example 16 | 17 | Execute the following command to run the example: 18 | 19 | ```ballerina 20 | bal run 21 | ``` -------------------------------------------------------------------------------- /docs/license.txt: -------------------------------------------------------------------------------- 1 | // AUTO-GENERATED FILE. DO NOT MODIFY. 2 | // This file is auto-generated by the Ballerina OpenAPI tool. 3 | 4 | // Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). 5 | // 6 | // WSO2 LLC. licenses this file to you under the Apache License, 7 | // Version 2.0 (the "License"); you may not use this file except 8 | // in compliance with the License. 9 | // You may obtain a copy of the License at 10 | // 11 | // http://www.apache.org/licenses/LICENSE-2.0 12 | // 13 | // Unless required by applicable law or agreed to in writing, 14 | // software distributed under the License is distributed on an 15 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | // KIND, either express or implied. See the License for the 17 | // specific language governing permissions and limitations 18 | // under the License. 19 | -------------------------------------------------------------------------------- /examples/survey-feedback-analysis/Slack survey feedback anaysis.md: -------------------------------------------------------------------------------- 1 | # Slack survey feedback analysis 2 | 3 | This use case demonstrates how the Slack API can be utilized to perform a company-wide survey by creating a dedicated channel to receive and track feedback replies. 4 | 5 | ## Prerequisites 6 | 7 | ### 1. Setup Slack account 8 | 9 | Generate Slack token to authenticate the connector as described in the [Setup guide](https://central.ballerina.io/ballerinax/slack/latest#prerequisites). 10 | 11 | ### 2. Configuration 12 | 13 | Create a `Config.toml` file in the example root directory, and update your Slack account token as follows: 14 | 15 | ```toml 16 | token = "" 17 | ``` 18 | 19 | ## Run the example 20 | 21 | Execute the following command to run the example: 22 | 23 | ```ballerina 24 | bal run 25 | ``` 26 | -------------------------------------------------------------------------------- /.github/workflows/dev-stg-release.yml: -------------------------------------------------------------------------------- 1 | name: Publish to the Ballerina Dev\Stage Central 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | environment: 7 | type: choice 8 | description: Select Environment 9 | required: true 10 | options: 11 | - DEV CENTRAL 12 | - STAGE CENTRAL 13 | 14 | jobs: 15 | call_workflow: 16 | name: Run Dev\Stage Central Publish Workflow 17 | if: ${{ github.repository_owner == 'ballerina-platform' }} 18 | uses: ballerina-platform/ballerina-library/.github/workflows/dev-stage-central-publish-connector-template.yml@main 19 | secrets: inherit 20 | with: 21 | environment: ${{ github.event.inputs.environment }} 22 | additional-publish-flags: "-x test" # temp workaround which must be removed once 2201.9.2 is released 23 | -------------------------------------------------------------------------------- /issue_template.md: -------------------------------------------------------------------------------- 1 | **Description:** 2 | 3 | 4 | **Suggested Labels:** 5 | 6 | 7 | **Suggested Assignees:** 8 | 9 | 10 | **Affected Product Version:** 11 | 12 | **OS, DB, other environment details and versions:** 13 | 14 | **Steps to reproduce:** 15 | 16 | 17 | **Related Issues:** 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | *.balx 4 | # Log file 5 | *.log 6 | 7 | generated 8 | #Config file 9 | Config.toml 10 | 11 | # BlueJ files 12 | *.ctxt 13 | 14 | # Mobile Tools for Java (J2ME) 15 | .mtj.tmp/ 16 | 17 | # .DS_Store files 18 | *.DS_Store 19 | 20 | # Package Files # 21 | *.jar 22 | !gradle/wrapper/gradle-wrapper.jar 23 | *.war 24 | *.ear 25 | *.zip 26 | *.tar.gz 27 | *.rar 28 | *.deb 29 | 30 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 31 | hs_err_pid* 32 | 33 | # Ignore everything in this directory 34 | target 35 | .classpath 36 | .settings 37 | .project 38 | *.iml 39 | *.iws 40 | *.ipr 41 | .idea 42 | .m2 43 | .vscode/ 44 | # Ignore ballerina files 45 | accessToken.bal 46 | temp.bal.ballerina/ 47 | target/ 48 | .DS_Store 49 | *Ballerina.lock 50 | .ballerina 51 | 52 | # Ignore Gradle project-specific cache directory 53 | .gradle 54 | 55 | # Ignore Gradle build output directory 56 | build 57 | 58 | # Ignore Docker env file 59 | docker.env 60 | -------------------------------------------------------------------------------- /pull_request_template.md: -------------------------------------------------------------------------------- 1 | # Description 2 | 3 | Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change. 4 | 5 | Fixes # (issue) 6 | 7 | Related Pull Requests (remove if not relevant) 8 | - Pull request 1 9 | - Pull request 2 10 | 11 | One line release note: 12 | - One line describing the feature/improvement/fix made by this PR 13 | 14 | ## Type of change 15 | 16 | Please delete options that are not relevant. 17 | 18 | - [ ] Bug fix (non-breaking change which fixes an issue) 19 | - [ ] New feature (non-breaking change which adds functionality) 20 | - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) 21 | - [ ] This change requires a documentation update 22 | 23 | # How Has This Been Tested? 24 | 25 | Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration 26 | 27 | - [ ] Test A 28 | - [ ] Test B 29 | 30 | **Test Configuration**: 31 | * Ballerina Version: 32 | * Operating System: 33 | * Java SDK: 34 | 35 | # Checklist: 36 | 37 | ### Security checks 38 | - [ ] Followed secure coding standards in http://wso2.com/technical-reports/wso2-secure-engineering-guidelines? 39 | - [ ] Confirmed that this PR doesn't commit any keys, passwords, tokens, usernames, or other secrets? 40 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # Examples 2 | 3 | The `ballerinax/slack` connector provides practical examples illustrating usage in various scenarios, covering use cases like cache management, session management, and rate limiting. 4 | 5 | ## Prerequisites 6 | 7 | 1. Generate Slack token to authenticate the connector as described in the [Setup guide](https://central.ballerina.io/ballerinax/slack/latest#prerequisites). 8 | 9 | 2. For each example, create a `Config.toml` file the related configuration. Here's an example of how your `Config.toml` file should look: 10 | 11 | ```toml 12 | token = "" 13 | ``` 14 | 15 | ## Running an Example 16 | 17 | Execute the following commands to build an example from the source: 18 | 19 | - To build an example: 20 | 21 | ```bash 22 | bal build 23 | ``` 24 | 25 | - To run an example: 26 | 27 | ```bash 28 | bal run 29 | ``` 30 | 31 | ## Building the Examples with the Local Module 32 | 33 | **Warning**: Due to the absence of support for reading local repositories for single Ballerina files, the Bala of the module is manually written to the central repository as a workaround. Consequently, the bash script may modify your local Ballerina repositories. 34 | 35 | Execute the following commands to build all the examples against the changes you have made to the module locally: 36 | 37 | - To build all the examples: 38 | 39 | ```bash 40 | ./build.sh build 41 | ``` 42 | 43 | - To run all the examples: 44 | 45 | ```bash 46 | ./build.sh run 47 | ``` 48 | -------------------------------------------------------------------------------- /docs/spec/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org). 3 | * 4 | * WSO2 LLC. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | import org.apache.tools.ant.taskdefs.condition.Os 20 | 21 | def files = ["sanitations.bal"]; 22 | 23 | task build { 24 | doLast { 25 | try { 26 | files.each { file -> 27 | println("Building ${file} ...") 28 | exec { 29 | workingDir project.projectDir 30 | if (Os.isFamily(Os.FAMILY_WINDOWS)) { 31 | commandLine 'sh', "/c", "bal build ${file} && exit %%ERRORLEVEL%%" 32 | } else { 33 | commandLine 'sh', "-c", "bal build ${file}" 34 | } 35 | } 36 | } 37 | } catch (Exception e) { 38 | println("Sanitation Script Build failed: " + e.message) 39 | throw e 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * This file was generated by the Gradle 'init' task. 3 | * 4 | * The settings file is used to specify which projects to include in your build. 5 | * For more detailed information on multi-project builds, please refer to https://docs.gradle.org/8.3/userguide/building_swift_projects.html in the Gradle documentation. 6 | */ 7 | 8 | pluginManagement { 9 | plugins { 10 | id "com.github.spotbugs-base" version "${spotbugsPluginVersion}" 11 | id "com.github.johnrengelman.shadow" version "${shadowJarPluginVersion}" 12 | id "de.undercouch.download" version "${downloadPluginVersion}" 13 | id "net.researchgate.release" version "${releasePluginVersion}" 14 | id "io.ballerina.plugin" version "${ballerinaGradlePluginVersion}" 15 | } 16 | 17 | repositories { 18 | gradlePluginPortal() 19 | maven { 20 | url = 'https://maven.pkg.github.com/ballerina-platform/*' 21 | credentials { 22 | username System.getenv("packageUser") 23 | password System.getenv("packagePAT") 24 | } 25 | } 26 | } 27 | } 28 | 29 | plugins { 30 | id "com.gradle.enterprise" version "3.2" 31 | } 32 | 33 | rootProject.name = 'module-ballerinax-slack' 34 | 35 | include ':slack-sanitation' 36 | include ':slack-ballerina' 37 | 38 | project(':slack-ballerina').projectDir = file("ballerina") 39 | project(':slack-sanitation').projectDir = file("docs/spec") 40 | gradleEnterprise { 41 | buildScan { 42 | termsOfServiceUrl = 'https://gradle.com/terms-of-service' 43 | termsOfServiceAgree = 'yes' 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /docs/spec/sanitations.md: -------------------------------------------------------------------------------- 1 | _Author_: @Chilliwiddit \ 2 | _Created_: 2024/06/25 \ 3 | _Edition_: Swan Lake 4 | 5 | # Sanitation for OpenAPI specification 6 | 7 | This document records the sanitation done on top of the official OpenAPI specification from Slack. The OpenAPI specification is obtained from the [APIs Guru website](https://api.apis.guru/v2/specs/slack.com/1.7.0/openapi.json). 8 | These changes are done in order to improve the overall usability, and to address some known language limitations. 9 | 10 | 1. Removed the token requirement from the parameter section of each endpoint in which it appeared. Endpoints in which it did not appear are: 11 | 12 | * admin.conversations.restrictAccess.addGroup 13 | * admin.conversations.restrictAccess.removeGroup 14 | * admin.emoji.add 15 | * admin.emoji.addAlias 16 | * admin.emoji.remove 17 | * admin.emoji.rename 18 | * admin.teams.settings.setDefaultChannels 19 | * admin.teams.settings.setIcon 20 | * dnd.setSnooze 21 | * files.remote.add 22 | * files.remote.remove 23 | * files.remote.update 24 | * files.upload 25 | * oauth.access 26 | * oauth.token 27 | * oauth.v2.access 28 | * users.deletePhoto 29 | * users.setPhoto 30 | 31 | 2. Sanitized the inline and component schema names by removing the whitespaces, special characters and, converting them to pascal case. 32 | * This was done using the `sanitations.bal` script under the `docs/spec` directory. 33 | 34 | ## OpenAPI cli command 35 | 36 | The following command was used to generate the Ballerina client from the OpenAPI specification. The command should be executed from the repository root directory. 37 | 38 | ```bash 39 | bal openapi -i docs/spec/openapi.json --mode client --license docs/license.txt -o ballerina/ 40 | ``` 41 | 42 | Note: The license year is hardcoded to 2024, change if necessary. 43 | -------------------------------------------------------------------------------- /ballerina/tests/README.md: -------------------------------------------------------------------------------- 1 | # Running Tests 2 | 3 | There are two test environments for running the Slack connector tests. The default test environment is the mock server for the Slack API. The other test environment is the actual Slack API. 4 | 5 | You can run the tests in either of these environments and each has its own compatible set of tests. 6 | 7 | | Test Groups | Environment | 8 | |-------------|-------------------------------------------------| 9 | | mock_tests | Mock server for Slack API (Default Environment) | 10 | | live_tests | Slack API | 11 | 12 | ## Running Tests in the Mock Server 13 | 14 | To execute the tests on the mock server, ensure that the `IS_LIVE_SERVER` environment variable is either set to `false` or unset before initiating the tests. 15 | 16 | This environment variable can be configured within the `Config.toml` file located in the tests directory or specified as an environmental variable. 17 | 18 | #### Using a Config.toml File 19 | 20 | Create a `Config.toml` file in the tests directory and the following content: 21 | 22 | ```toml 23 | isLiveServer = false 24 | ``` 25 | 26 | #### Using Environment Variables 27 | 28 | Alternatively, you can set your authentication credentials as environment variables: 29 | 30 | ```bash 31 | export IS_LIVE_SERVER=false 32 | ``` 33 | 34 | Then, run the following command to run the tests: 35 | 36 | ```bash 37 | ./gradlew clean test 38 | ``` 39 | 40 | ## Running Tests Against Slack Live API 41 | 42 | #### Using a Config.toml File 43 | 44 | Create a `Config.toml` file in the tests directory and add your authentication credentials. 45 | 46 | ```toml 47 | isTestOnLiveServer = true 48 | token = "" 49 | ``` 50 | 51 | #### Using Environment Variables 52 | 53 | Alternatively, you can set your authentication credentials as environment variables: 54 | 55 | ```bash 56 | export IS_LIVE_SERVER=true 57 | export token = "" 58 | ``` 59 | 60 | Then, run the following command to run the tests: 61 | 62 | ```bash 63 | ./gradlew clean test -Pgroups="live_tests" 64 | ``` 65 | -------------------------------------------------------------------------------- /examples/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | BAL_EXAMPLES_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" 4 | BAL_CENTRAL_DIR="$HOME/.ballerina/repositories/central.ballerina.io" 5 | BAL_HOME_DIR="$BAL_EXAMPLES_DIR/../ballerina" 6 | 7 | set -e 8 | 9 | case "$1" in 10 | build) 11 | BAL_CMD="build" 12 | ;; 13 | run) 14 | BAL_CMD="run" 15 | ;; 16 | *) 17 | echo "Invalid command provided: '$1'. Please provide 'build' or 'run' as the command." 18 | exit 1 19 | ;; 20 | esac 21 | 22 | # Read Ballerina package name 23 | BAL_PACKAGE_NAME=$(awk -F'"' '/^name/ {print $2}' "$BAL_HOME_DIR/Ballerina.toml") 24 | 25 | # Push the package to the local repository 26 | cd "$BAL_HOME_DIR" && 27 | bal pack && 28 | bal push --repository=local 29 | 30 | # Remove the cache directories in the repositories 31 | cacheDirs=$(ls -d $BAL_CENTRAL_DIR/cache-* 2>/dev/null) || true 32 | for dir in "${cacheDirs[@]}"; do 33 | [ -d "$dir" ] && rm -r "$dir" 34 | done 35 | echo "Successfully cleaned the cache directories" 36 | 37 | # Create the package directory in the central repository, this will not be present if no modules are pulled 38 | mkdir -p "$BAL_CENTRAL_DIR/bala/ballerinax/$BAL_PACKAGE_NAME" 39 | 40 | # Update the central repository 41 | BAL_DESTINATION_DIR="$HOME/.ballerina/repositories/central.ballerina.io/bala/ballerinax/$BAL_PACKAGE_NAME" 42 | BAL_SOURCE_DIR="$HOME/.ballerina/repositories/local/bala/ballerinax/$BAL_PACKAGE_NAME" 43 | [ -d "$BAL_DESTINATION_DIR" ] && rm -r "$BAL_DESTINATION_DIR" 44 | [ -d "$BAL_SOURCE_DIR" ] && cp -r "$BAL_SOURCE_DIR" "$BAL_DESTINATION_DIR" 45 | echo "Successfully updated the local central repositories" 46 | 47 | echo "$BAL_DESTINATION_DIR" 48 | echo "$BAL_SOURCE_DIR" 49 | 50 | # Loop through examples in the examples directory 51 | cd "$BAL_EXAMPLES_DIR" 52 | for dir in $(find "$BAL_EXAMPLES_DIR" -type d -maxdepth 1 -mindepth 1); do 53 | # Skip the build directory 54 | if [[ "$dir" == *build ]]; then 55 | continue 56 | fi 57 | (cd "$dir" && bal "$BAL_CMD" --offline && cd ..); 58 | done 59 | 60 | # Remove generated JAR files 61 | find "$BAL_HOME_DIR" -maxdepth 1 -type f -name "*.jar" | while read -r JAR_FILE; do 62 | rm "$JAR_FILE" 63 | done 64 | -------------------------------------------------------------------------------- /.github/workflows/regenerate-connector.yml: -------------------------------------------------------------------------------- 1 | name: Regenerate OpenAPI Connector 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | openapi-url: 7 | description: "URL of the OpenAPI JSON" 8 | required: false 9 | type: string 10 | flatten-openapi: 11 | description: "Enable OpenAPI Flattening" 12 | required: false 13 | type: boolean 14 | default: true 15 | additional-flatten-flags: 16 | description: "Additional flags for OpenAPI Flattening" 17 | required: false 18 | type: string 19 | default: "" 20 | align-openapi: 21 | description: "Enable OpenAPI Alignment" 22 | required: false 23 | type: boolean 24 | default: true 25 | additional-align-flags: 26 | description: "Additional flags for OpenAPI Alignment" 27 | required: false 28 | type: string 29 | default: "" 30 | additional-generation-flags: 31 | description: "Additional flags for OpenAPI Generation" 32 | required: false 33 | type: string 34 | default: "" 35 | distribution-zip: 36 | description: "Distribution of the Ballerina version to be used" 37 | required: false 38 | type: string 39 | default: "" 40 | auto-merge: 41 | description: "Enable auto-merge of the PR" 42 | required: false 43 | type: boolean 44 | default: true 45 | ballerina-version: 46 | description: "Ballerina Language Version" 47 | required: false 48 | type: string 49 | default: "" 50 | 51 | jobs: 52 | call_workflow: 53 | name: Run Regenerate Connector Workflow 54 | if: ${{ github.repository_owner == 'ballerina-platform' }} 55 | uses: ballerina-platform/ballerina-library/.github/workflows/regenerate-connector-template.yml@main 56 | secrets: inherit 57 | with: 58 | openapi-url: ${{ inputs.openapi-url }} 59 | flatten-openapi: ${{ inputs.flatten-openapi }} 60 | additional-flatten-flags: ${{ inputs.additional-flatten-flags }} 61 | align-openapi: ${{ inputs.align-openapi }} 62 | additional-align-flags: ${{ inputs.additional-align-flags }} 63 | additional-generation-flags: ${{ inputs.additional-generation-flags }} 64 | distribution-zip: ${{ inputs.distribution-zip }} 65 | auto-merge: ${{ inputs.auto-merge }} 66 | ballerina-version: ${{ inputs.ballerina-version }} 67 | -------------------------------------------------------------------------------- /examples/automated-summary-report/main.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2024 WSO2 LLC. (http://www.wso2.org). 2 | // 3 | // WSO2 LLC. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/http; 18 | import ballerina/io; 19 | import ballerina/log; 20 | import ballerinax/slack; 21 | 22 | configurable string token = ?; 23 | 24 | // Initialize the Slack client with the provided token. 25 | final slack:Client slack = check new Client({ 26 | auth: { 27 | token 28 | } 29 | }); 30 | 31 | public function main() returns error? { 32 | // Fetch the list of channels. 33 | slack:ConversationsListResponse channelResponse = check slack->/conversations\.list(); 34 | 35 | // Array to store the latest text messages from each channel. 36 | string[] latestText; 37 | 38 | // Iterate through each channel to get the latest message. 39 | foreach slack:ConversationObj channel in channelResponse.channels { 40 | // Fetch the conversation history for the current channel. 41 | slack:ConversationsHistoryResponse historyResponse = check slack->/conversations\.history({channel: channel.toString()}); 42 | 43 | // Get the latest text message from the conversation history. 44 | slack:MessageObj[] messages = historyResponse.messages; 45 | latestText.push(messages[0].text); 46 | } 47 | 48 | // Construct the stand-up report message. 49 | string textMessage = string `Automated Stand Up Report: ${"\n"}${ 50 | from [int, string] [index, text] in latestText.enumerate() 51 | select string `${index + 1}. ${text}${"\n"}` 52 | }`; 53 | 54 | // Post the stand-up report message to the "general" channel. 55 | slack:ChatPostMessageResponse|error postMessageResult = slack->/chat\.postMessage.post({channel: "general", text: textMessage}); 56 | 57 | if postMessageResult is error { 58 | log:printError("Failed to post message to Slack", postMessageResult); 59 | } else { 60 | log:printInfo("Message posted successfully"); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /examples/survey-feedback-analysis/main.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2024 WSO2 LLC. (http://www.wso2.org). 2 | // 3 | // WSO2 LLC. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/io; 18 | import ballerina/log; 19 | import ballerinax/slack; 20 | 21 | configurable string token = ?; 22 | 23 | const CHANNEL_NAME = "survey-coordination"; 24 | const SURVEY_REQUEST_MSG = "Reply to this survey message to give input on the company"; 25 | 26 | final slack:Client slack = check new ({ 27 | auth: { 28 | token 29 | } 30 | }); 31 | 32 | public function main() returns error? { 33 | 34 | // Create a new channel for the survey 35 | slack:ConversationsCreateResponse|error createChannelResponse = slack->/conversations\.create.post({name: CHANNEL_NAME}); 36 | if createChannelResponse is error { 37 | log:printError("Error creating the survey conversation: " + createChannelResponse.message()); 38 | return; 39 | } 40 | 41 | // Post a message to the conversation created and get the timestamp of the message 42 | slack:ChatPostMessageResponse|error sendMsgResponse = slack->/chat\.postMessage.post({channel: CHANNEL_NAME, text: SURVEY_REQUEST_MSG}); 43 | if sendMsgResponse is error { 44 | log:printError(sendMsgResponse.message()); 45 | return; 46 | } 47 | string messageTimestamp = sendMsgResponse.message.ts; 48 | 49 | // Check for replies to the survey message 50 | slack:ConversationsRepliesResponse|error repliesResponse = slack->/conversations\.replies({channel: CHANNEL_NAME, ts: messageTimestamp}); 51 | if repliesResponse is error { 52 | log:printError(repliesResponse.message()); 53 | return; 54 | } 55 | 56 | // Get the messages from the replies 57 | var messages = repliesResponse.messages; 58 | 59 | // Print the survey responses 60 | io:println("Replies to the survey message:"); 61 | io:println("-----------------------------"); 62 | int counter = 1; 63 | foreach var message in messages { 64 | io:println(string `Reply ${counter}: ${message.toString()}`); 65 | counter += 1; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /ballerina/tests/tests.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2024 WSO2 LLC. (http://www.wso2.org). 2 | // 3 | // WSO2 LLC. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerina/test; 20 | 21 | configurable boolean isLiveServer = os:getEnv("IS_LIVE_SERVER") == "true"; 22 | configurable string token = isLiveServer ? os:getEnv("SLACK_TOKEN") : "test"; 23 | configurable string serviceUrl = isLiveServer ? "https://slack.com/api" : "http://localhost:9090/"; 24 | 25 | ConnectionConfig slackConfig = { 26 | auth: { 27 | token 28 | } 29 | }; 30 | 31 | Client slack = test:mock(Client); 32 | 33 | @test:BeforeSuite 34 | function setup() returns error? { 35 | if (isLiveServer) { 36 | log:printInfo("Running tests on actual server"); 37 | } else { 38 | log:printInfo("Running tests on mock server"); 39 | } 40 | 41 | slack = check new (slackConfig, serviceUrl); 42 | } 43 | 44 | @test:Config { 45 | groups: ["live_tests", "mock_tests"] 46 | } 47 | function testGetPresence() returns error? { 48 | APIMethodUsersGetPresence response = check slack->/users\.getPresence(); 49 | test:assertTrue(response.ok, "The ok attribute was not equal to true"); 50 | } 51 | 52 | @test:Config { 53 | groups: ["live_tests", "mock_tests"] 54 | } 55 | function testPostMessage() returns error? { 56 | ChatPostMessageResponse response = check slack->/chat\.postMessage.post({channel: "general"}); 57 | test:assertTrue(response.ok, "The ok attribute should be true"); 58 | test:assertEquals(response.message.text, "This is a Test", "The message text is not equal to the expected value"); 59 | } 60 | 61 | @test:Config { 62 | groups: ["live_tests", "mock_tests"] 63 | } 64 | function testGetUsersList() returns error? { 65 | UsersListResponse response = check slack->/users\.list(); 66 | test:assertTrue(response.ok, "The ok attribute should be true"); 67 | } 68 | 69 | @test:Config { 70 | groups: ["live_tests", "mock_tests"] 71 | } 72 | function testGetUserProfiles() returns error? { 73 | UsersProfileGetResponse response = check slack->/users\.profile\.get(); 74 | test:assertTrue(response.ok, "The ok attribute should be true"); 75 | } 76 | -------------------------------------------------------------------------------- /examples/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). 3 | * 4 | * WSO2 LLC. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | import org.apache.tools.ant.taskdefs.condition.Os 20 | 21 | apply plugin: 'java' 22 | 23 | def graalvmFlag = "" 24 | 25 | task testExamples { 26 | if (project.hasProperty("balGraalVMTest")) { 27 | graalvmFlag = "--graalvm" 28 | } 29 | doLast { 30 | try { 31 | exec { 32 | workingDir project.projectDir 33 | println("Working dir: ${workingDir}") 34 | if (Os.isFamily(Os.FAMILY_WINDOWS)) { 35 | commandLine 'cmd', "/c", "chmod +x ./build.sh && ./build.sh run && exit %%ERRORLEVEL%%" 36 | } else { 37 | commandLine 'sh', "-c", "chmod +x ./build.sh && ./build.sh run" 38 | } 39 | } 40 | } catch (Exception e) { 41 | println("Example Build failed: " + e.message) 42 | throw e 43 | } 44 | } 45 | } 46 | 47 | task buildExamples { 48 | gradle.taskGraph.whenReady { graph -> 49 | if (graph.hasTask(":slack-examples:test")) { 50 | buildExamples.enabled = false 51 | } else { 52 | testExamples.enabled = false 53 | } 54 | } 55 | doLast { 56 | try { 57 | exec { 58 | workingDir project.projectDir 59 | println("Working dir: ${workingDir}") 60 | if (Os.isFamily(Os.FAMILY_WINDOWS)) { 61 | commandLine 'cmd', "/c", "chmod +x ./build.sh && ./build.sh build && exit %%ERRORLEVEL%%" 62 | } else { 63 | commandLine 'sh', "-c", "chmod +x ./build.sh && ./build.sh build" 64 | } 65 | } 66 | } catch (Exception e) { 67 | println("Example Build failed: " + e.message) 68 | throw e 69 | } 70 | } 71 | } 72 | 73 | buildExamples.dependsOn ":slack-ballerina:build" 74 | testExamples.dependsOn ":slack-ballerina:build" 75 | 76 | // TODO: Enable the examples build once https://github.com/ballerina-platform/ballerina-library/issues/6135 is fixed 77 | // test.dependsOn testExamples 78 | // build.dependsOn buildExamples 79 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 1>&2 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 48 | echo. 1>&2 49 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 50 | echo location of your Java installation. 1>&2 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 1>&2 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 62 | echo. 1>&2 63 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 64 | echo location of your Java installation. 1>&2 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /ballerina/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). 3 | * 4 | * WSO2 LLC. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | import org.apache.tools.ant.taskdefs.condition.Os 20 | 21 | plugins { 22 | id 'io.ballerina.plugin' 23 | } 24 | 25 | description = 'Slack - Ballerina' 26 | 27 | def packageName = "slack" 28 | def packageOrg = "ballerinax" 29 | def tomlVersion = stripBallerinaExtensionVersion("${project.version}") 30 | def ballerinaTomlFilePlaceHolder = new File("${project.rootDir}/build-config/resources/Ballerina.toml") 31 | def ballerinaTomlFile = new File("$project.projectDir/Ballerina.toml") 32 | 33 | def stripBallerinaExtensionVersion(String extVersion) { 34 | if (extVersion.matches(project.ext.timestampedVersionRegex)) { 35 | def splitVersion = extVersion.split('-') 36 | if (splitVersion.length > 3) { 37 | def strippedValues = splitVersion[0..-4] 38 | return strippedValues.join('-') 39 | } else { 40 | return extVersion 41 | } 42 | } else { 43 | return extVersion.replace("${project.ext.snapshotVersion}", "") 44 | } 45 | } 46 | 47 | ballerina { 48 | packageOrganization = packageOrg 49 | module = packageName 50 | testCoverageParam = "--code-coverage --coverage-format=xml" 51 | isConnector = true 52 | platform = "any" 53 | } 54 | 55 | task updateTomlFiles { 56 | doLast { 57 | def newBallerinaToml = ballerinaTomlFilePlaceHolder.text.replace("@project.version@", project.version) 58 | newBallerinaToml = newBallerinaToml.replace("@toml.version@", tomlVersion) 59 | ballerinaTomlFile.text = newBallerinaToml 60 | } 61 | } 62 | 63 | task commitTomlFiles { 64 | doLast { 65 | project.exec { 66 | ignoreExitValue true 67 | if (Os.isFamily(Os.FAMILY_WINDOWS)) { 68 | commandLine 'cmd', '/c', "git commit -m \"[Automated] Update the toml files\" Ballerina.toml Dependencies.toml" 69 | } else { 70 | commandLine 'sh', '-c', "git commit -m '[Automated] Update the toml files' Ballerina.toml Dependencies.toml" 71 | } 72 | } 73 | } 74 | } 75 | 76 | publishing { 77 | publications { 78 | maven(MavenPublication) { 79 | artifact source: createArtifactZip, extension: 'zip' 80 | } 81 | } 82 | repositories { 83 | maven { 84 | name = "GitHubPackages" 85 | url = uri("https://maven.pkg.github.com/ballerina-platform/module-${packageOrg}-${packageName}") 86 | credentials { 87 | username = System.getenv("publishUser") 88 | password = System.getenv("publishPAT") 89 | } 90 | } 91 | } 92 | } 93 | 94 | clean { 95 | delete 'build' 96 | } 97 | 98 | build.dependsOn "generatePomFileForMavenPublication" 99 | publishToMavenLocal.dependsOn build 100 | publish.dependsOn build 101 | -------------------------------------------------------------------------------- /ballerina/README.md: -------------------------------------------------------------------------------- 1 | ## Overview 2 | 3 | [Slack](https://slack.com/) is a collaboration platform for teams, offering real-time messaging, file sharing, and integrations with various tools. It helps streamline communication and enhance productivity through organized channels and direct messaging. 4 | 5 | ## Setup guide 6 | 7 | ### Step 1: Sign in to Slack 8 | 9 | 1. To use the Slack Connector you need to be signed in to [Slack](https://slack.com/). If you haven't created an account already, you can create it [here](https://slack.com/get-started#/createnew). 10 | 11 | Sign-In Page 12 | 13 | ### Step 2: Create a new Slack application 14 | 15 | 1. Navigate to your apps in [Slack API](https://api.slack.com/) and create a new Slack app. 16 | 17 | Create Slack App 18 | 19 | 2. Provide an app name and choose a workspace of your choice. 20 | 21 | Create Slack App Popup 22 | 23 | 3. Click on the "Create App" button. 24 | 25 | ### Step 3: Add scopes to the token 26 | 27 | 1. Once the application is created, go to the "Add Features and Functionality" section and click on "Permissions" to set the token scopes. 28 | 29 | Add features and functionality 30 | 31 | 2. In the **User Token Scopes** section set the following token scopes. 32 | 33 | User Token Scopes 34 | 35 | 3. Install the application to workspace. 36 | 37 | Install to workspace 38 | 39 | 4. Copy the OAuth token that is generated upon installation. 40 | 41 | Copy token 42 | 43 | 44 | ## Quickstart 45 | 46 | To use the `slack` connector in your Ballerina application, modify the `.bal` file as follows: 47 | 48 | ### Step 1: Import the module 49 | 50 | Import the `slack` module. 51 | 52 | ```ballerina 53 | import ballerinax/slack; 54 | ``` 55 | 56 | ### Step 2: Instantiate a new connector 57 | 58 | Assign the OAuth token obtained to the variable **token**, and then initialize a new instance of the slack client by passing the token. 59 | 60 | ```ballerina 61 | configurable string token = ?; 62 | 63 | slack:Client slack = check new({ 64 | auth: { 65 | token 66 | } 67 | }); 68 | ``` 69 | 70 | ### Step 3: Invoke the connector operation 71 | 72 | Now, utilize the available connector operations. 73 | 74 | #### Send a Text Message to General Channel 75 | 76 | ```ballerina 77 | slack:ChatPostMessageResponse postMessageResponse = check slack->/chat\.postMessage.post({channel: "general", text: "hello"}); 78 | ``` 79 | 80 | ### Step 4: Run the Ballerina application 81 | 82 | ```bash 83 | bal run 84 | ``` 85 | 86 | ## Examples 87 | 88 | The `Slack` connector provides practical examples illustrating usage in various scenarios. Explore these [examples](https://github.com/ballerina-platform/module-ballerinax-slack/tree/master/examples), covering the following use cases: 89 | 90 | 1. [Automated Summary Report](https://github.com/ballerina-platform/module-ballerinax-slack/tree/master/examples/automated-summary-report) - This use case demonstrates how the Slack API can be utilized to generate a summarized report of daily stand up chats in the general channel. 91 | 92 | 2. [Survey Feedback Analysis](https://github.com/ballerina-platform/module-ballerinax-slack/tree/master/examples/survey-feedback-analysis) - This use case demonstrates how the Slack API can be utilized to perform a company-wide survey by creating a dedicated channel to receive and track feedback replies. 93 | -------------------------------------------------------------------------------- /ballerina/tests/mock_service.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2024 WSO2 LLC. (http://www.wso2.org). 2 | // 3 | // WSO2 LLC. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/http; 18 | import ballerina/log; 19 | 20 | listener http:Listener httpListener = new (9090); 21 | 22 | http:Service mockAPI = service object { 23 | 24 | # Get Presence 25 | # 26 | # + return - Get Presence 27 | resource isolated function get users\.getPresence() returns json => { 28 | "ok": true, 29 | "presence": "away", 30 | "online": false, 31 | "auto_away": false, 32 | "manual_away": false, 33 | "connection_count": 0 34 | }; 35 | 36 | # Post Message 37 | # 38 | # + return - json 39 | resource isolated function post chat\.postMessage(@http:Payload http:Request request) returns ChatPostMessageResponse => { 40 | ok: true, 41 | channel: "C078KJ7SW78", 42 | ts: "1719830298.784769", 43 | message: { 44 | user: "U078KJ7RX1U", 45 | 'type: "message", 46 | ts: "1719830298.784769", 47 | botId: [], 48 | text: "This is a Test", 49 | team: "T078S42MC59", 50 | botProfile: { 51 | id: "B07986E3N4E", 52 | appId: "A079SKHD00Z", 53 | name: "test-app", 54 | icons: { 55 | image36: "https://a.slack-edge.com/80588/img/plugins/app/bot_36.png", 56 | image48: "https://a.slack-edge.com/80588/img/plugins/app/bot_48.png", 57 | image72: "https://a.slack-edge.com/80588/img/plugins/app/service_72.png" 58 | }, 59 | deleted: false, 60 | updated: 1719218992, 61 | teamId: "T078S42MC59" 62 | }, 63 | blocks: [ 64 | { 65 | "type": "rich_text", 66 | "block_id": "I/L", 67 | "elements": [ 68 | { 69 | "type": "rich_text_section", 70 | "elements": [ 71 | { 72 | "type": "text", 73 | "text": "This is a Test" 74 | } 75 | ] 76 | } 77 | ] 78 | } 79 | ] 80 | } 81 | }; 82 | 83 | # List Users 84 | # 85 | # + return - List Users 86 | resource isolated function get users\.list() returns UsersListResponse => { 87 | ok: true, 88 | cacheTs: 1697039999, 89 | members: [ 90 | [{ 91 | isAppUser: true, 92 | isBot: false, 93 | updated: 0, 94 | id: "U078KJ7RX1U", 95 | teamId: "T078S42MC59", 96 | name: "adib", 97 | deleted: false, 98 | color: "9c3b2a", 99 | realName: "Adib Samoon", 100 | tzLabel: "Sri Lanka Standard Time", 101 | tzOffset: 19800, 102 | profile: { 103 | avatarHash: "", 104 | statusText: "", 105 | statusEmoji: ":)", 106 | displayName: "", 107 | realNameNormalized: "Adib Samoon", 108 | displayNameNormalized: "Adib Samoon", 109 | skype: "", 110 | realName: "", 111 | phone: "", 112 | title: "", 113 | fields: () 114 | }, 115 | isAdmin: true, 116 | isOwner: true, 117 | isPrimaryOwner: true, 118 | isRestricted: false, 119 | isUltraRestricted: false, 120 | has2fa: false 121 | } 122 | ] 123 | ] 124 | }; 125 | 126 | # Get User Profile 127 | # 128 | # + return - Get User Profile 129 | resource isolated function get users\.profile\.get() returns UsersProfileGetResponse => { 130 | ok: true, 131 | profile: { 132 | avatarHash: "", 133 | displayNameNormalized: "Adib Samoon", 134 | realName: "Adib Samoon", 135 | realNameNormalized: "Adib Samoon", 136 | statusText: "", 137 | statusEmoji: ":)", 138 | displayName: "", 139 | title: "", 140 | phone: "", 141 | skype: "", 142 | fields: [], 143 | email: "adib@wso2.com" 144 | } 145 | }; 146 | }; 147 | 148 | function init() returns error? { 149 | if isLiveServer { 150 | log:printInfo("Skiping mock server initialization as the tests are running on live server"); 151 | return; 152 | } 153 | log:printInfo("Initiating mock server"); 154 | check httpListener.attach(mockAPI, "/"); 155 | check httpListener.'start(); 156 | } 157 | -------------------------------------------------------------------------------- /docs/spec/sanitations.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 LLC. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/io; 18 | import ballerina/lang.regexp; 19 | import ballerina/mime; 20 | 21 | type Specification record { 22 | map paths; 23 | Components components; 24 | }; 25 | 26 | type Path record { 27 | Get get?; 28 | Post post?; 29 | }; 30 | 31 | type Get record { 32 | string summary?; 33 | string description?; 34 | string[] tags?; 35 | map responses?; 36 | }; 37 | 38 | type Post record { 39 | string summary?; 40 | string description?; 41 | string[] tags?; 42 | json requestBody?; 43 | map responses?; 44 | }; 45 | 46 | type ResponseCode record { 47 | string description?; 48 | map content?; 49 | }; 50 | 51 | type ResponseHeader record { 52 | ResponseSchema schema?; 53 | }; 54 | 55 | type ResponseSchema record { 56 | string title?; 57 | string 'type?; 58 | string schemaType?; 59 | }; 60 | 61 | type Components record { 62 | map schemas; 63 | }; 64 | 65 | const SPEC_PATH = "openapi.json"; 66 | final regexp:RegExp MALFORMED_TITLE_REGEX = re `\w+[\.\s]\w+.*`; 67 | 68 | public function main() returns error? { 69 | json openAPISpec = check io:fileReadJson(SPEC_PATH); 70 | Specification spec = check openAPISpec.cloneWithType(Specification); 71 | 72 | spec = check sanitizeResponseSchemaNames(spec); 73 | string sanitizedSpecString = sanitizeSchemaNames(spec); 74 | check io:fileWriteString(SPEC_PATH, sanitizedSpecString); 75 | } 76 | 77 | function sanitizeResponseSchemaNames(Specification spec) returns Specification|error { 78 | map paths = spec.paths; 79 | foreach var [_, value] in paths.entries() { 80 | map? responses = (); 81 | if value.get !is () { 82 | responses = value?.get?.responses; 83 | } else if value.post !is () { 84 | responses = value?.post?.responses; 85 | } 86 | 87 | if responses !is map { 88 | continue; 89 | } 90 | foreach [string, ResponseCode] [_, item] in responses.entries() { 91 | map content = item.content ?: {}; 92 | ResponseHeader app = content[mime:APPLICATION_JSON] ?: {}; 93 | ResponseSchema schema = app.schema ?: {}; 94 | string? title = schema.title; 95 | if title !is string { 96 | continue; 97 | } 98 | 99 | // if the title is malformed, sanitize it by removing special characters and converting to pascal case 100 | if MALFORMED_TITLE_REGEX.isFullMatch(title) { 101 | string tempTitle = re `\.`.replaceAll(title, " "); 102 | string[] nameParts = re ` `.split(tempTitle); 103 | string[] capitalizedNameParts = from string namePart in nameParts 104 | select namePart[0].toUpperAscii() + namePart.substring(1, namePart.length()); 105 | 106 | string sanitizedTitle = string:'join("", ...capitalizedNameParts); 107 | sanitizedTitle = re `SuccessSchema`.replaceAll(sanitizedTitle, "Response"); 108 | sanitizedTitle = re `Schema`.replaceAll(sanitizedTitle, "Response"); 109 | schema.title = sanitizedTitle; 110 | } 111 | } 112 | } 113 | 114 | return spec; 115 | } 116 | 117 | function sanitizeSchemaNames(Specification spec) returns string { 118 | map updatedSchemas = {}; 119 | map updatedNames = {}; 120 | 121 | foreach [string, json] [schemaName, schema] in spec.components.schemas.entries() { 122 | if schemaName.includes("_") { 123 | string newName = getSanitizedSchemaName(schemaName); 124 | if updatedSchemas.hasKey(newName) { 125 | io:println("Error: Duplicate sanitized schema name found: " + newName + " for schema: " + schemaName); 126 | } 127 | updatedNames[schemaName] = newName; 128 | updatedSchemas[newName] = schema; 129 | } else { 130 | updatedSchemas[schemaName] = schema; 131 | } 132 | } 133 | spec.components.schemas = updatedSchemas; 134 | 135 | string updatedSpec = spec.toJsonString(); 136 | foreach [string, string] [oldName, newName] in updatedNames.entries() { 137 | regexp:RegExp oldRegex = re `#/components/schemas/${oldName}"`; 138 | regexp:Replacement replacement = string `#/components/schemas/${newName}"`; 139 | updatedSpec = oldRegex.replaceAll(updatedSpec, replacement); 140 | } 141 | 142 | return updatedSpec; 143 | } 144 | 145 | function getSanitizedSchemaName(string schemaName) returns string { 146 | string[] nameParts = re `_`.split(schemaName); 147 | if nameParts[0] == "defs" { 148 | string _ = nameParts.remove(0); 149 | nameParts.push("Def"); 150 | } 151 | 152 | if nameParts[0] == "objs" { 153 | string _ = nameParts.remove(0); 154 | nameParts.push("Obj"); 155 | } 156 | 157 | string[] capitalizedNameParts = from string namePart in nameParts 158 | select namePart[0].toUpperAscii() + namePart.substring(1, namePart.length()); 159 | return string:'join("", ...capitalizedNameParts); 160 | } 161 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Ballerina Slack Connector 2 | =================== 3 | 4 | [![Build](https://github.com/ballerina-platform/module-ballerinax-slack/workflows/CI/badge.svg)](https://github.com/ballerina-platform/module-ballerinax-slack/actions?query=workflow%3ACI) 5 | [![codecov](https://codecov.io/gh/ballerina-platform/module-ballerinax-slack/branch/master/graph/badge.svg)](https://codecov.io/gh/ballerina-platform/module-ballerinax-slack) 6 | [![GitHub Last Commit](https://img.shields.io/github/last-commit/ballerina-platform/module-ballerinax-slack.svg)](https://github.com/ballerina-platform/module-ballerinax-slack/commits/master) 7 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 8 | 9 | [Slack](https://api.slack.com/) is a channel-based messaging platform. With Slack, people can work together more effectively, connect all their software tools and services, and find the information they need to do their best work — all within a secure, enterprise-grade environment. 10 | 11 | This connector allows you to access the Slack Web API and Slack Events API through Ballerina. 12 | It provides the capability to query information from and perform some actions in a Slack workspace. 13 | 14 | For more information, go to the modules. 15 | - [`slack`](slack/Module.md) 16 | 17 | ## Overview 18 | 19 | [Slack](https://slack.com/) is a collaboration platform for teams, offering real-time messaging, file sharing, and integrations with various tools. It helps streamline communication and enhance productivity through organized channels and direct messaging. 20 | 21 | ## Setup guide 22 | 23 | ### Step 1: Sign in to Slack 24 | 25 | 1. To use the Slack Connector you need to be signed in to [Slack](https://slack.com/). If you haven't created an account already, you can create it [here](https://slack.com/get-started#/createnew). 26 | 27 | Sign-In Page 28 | 29 | ### Step 2: Create a new Slack application 30 | 31 | 1. Navigate to your apps in [Slack API](https://api.slack.com/) and create a new Slack app. 32 | 33 | Create Slack App 34 | 35 | 2. Provide an app name and choose a workspace of your choice. 36 | 37 | Create Slack App Popup 38 | 39 | 3. Click on the "Create App" button. 40 | 41 | ### Step 3: Add scopes to the token 42 | 43 | 1. Once the application is created, go to the "Add Features and Functionality" section and click on "Permissions" to set the token scopes. 44 | 45 | Add features and functionality 46 | 47 | 2. In the **User Token Scopes** section set the following token scopes. 48 | 49 | User Token Scopes 50 | 51 | 3. Install the application to workspace. 52 | 53 | Install to workspace 54 | 55 | 4. Copy the OAuth token that is generated upon installation. 56 | 57 | Copy token 58 | 59 | 60 | ## Quickstart 61 | 62 | To use the `slack` connector in your Ballerina application, modify the `.bal` file as follows: 63 | 64 | ### Step 1: Import the module 65 | 66 | Import the `slack` module. 67 | 68 | ```ballerina 69 | import ballerinax/slack; 70 | ``` 71 | 72 | ### Step 2: Instantiate a new connector 73 | 74 | Assign the OAuth token obtained to the variable **token**, and then initialize a new instance of the slack client by passing the token. 75 | 76 | ```ballerina 77 | configurable string token = ?; 78 | 79 | slack:Client slack = check new({ 80 | auth: { 81 | token 82 | } 83 | }); 84 | ``` 85 | 86 | ### Step 3: Invoke the connector operation 87 | 88 | Now, utilize the available connector operations. 89 | 90 | #### Send a Text Message to General Channel 91 | 92 | ```ballerina 93 | slack:ChatPostMessageResponse postMessageResponse = check slack->/chat\.postMessage.post({channel: "general", text: "hello"}); 94 | ``` 95 | 96 | ### Step 4: Run the Ballerina application 97 | 98 | ```bash 99 | bal run 100 | ``` 101 | 102 | ## Examples 103 | 104 | The `Slack` connector provides practical examples illustrating usage in various scenarios. Explore these [examples](https://github.com/ballerina-platform/module-ballerinax-slack/tree/master/examples), covering the following use cases: 105 | 106 | 1. [Automated Summary Report](https://github.com/ballerina-platform/module-ballerinax-slack/tree/master/examples/automated-summary-report) - This use case demonstrates how the Slack API can be utilized to generate a summarized report of daily stand up chats in the general channel. 107 | 108 | 2. [Survey Feedback Analysis](https://github.com/ballerina-platform/module-ballerinax-slack/tree/master/examples/survey-feedback-analysis) - This use case demonstrates how the Slack API can be utilized to perform a company-wide survey by creating a dedicated channel to receive and track feedback replies. 109 | 110 | ## Build from the source 111 | 112 | ### Prerequisites 113 | 114 | 1. Download and install Java SE Development Kit (JDK) version 17. You can download it from either of the following sources: 115 | 116 | * [Oracle JDK](https://www.oracle.com/java/technologies/downloads/) 117 | * [OpenJDK](https://adoptium.net/) 118 | 119 | > **Note:** After installation, remember to set the `JAVA_HOME` environment variable to the directory where JDK was installed. 120 | 121 | 2. Download and install [Ballerina Swan Lake](https://ballerina.io/). 122 | 123 | 3. Download and install [Docker](https://www.docker.com/get-started). 124 | 125 | > **Note**: Ensure that the Docker daemon is running before executing any tests. 126 | 127 | 4. Export Github Personal access token with read package permissions as follows, 128 | ```bash 129 | export packageUser= 130 | export packagePAT= 131 | ``` 132 | 133 | ### Build options 134 | 135 | Execute the commands below to build from the source. 136 | 137 | 1. To build the package: 138 | 139 | ```bash 140 | ./gradlew clean build 141 | ``` 142 | 143 | 2. To run the tests: 144 | 145 | ```bash 146 | ./gradlew clean test 147 | ``` 148 | 149 | 3. To build the without the tests: 150 | 151 | ```bash 152 | ./gradlew clean build -x test 153 | ``` 154 | 155 | 4. To run tests against different environment: 156 | 157 | ```bash 158 | ./gradlew clean test -Pgroups= 159 | ``` 160 | 161 | 5. To debug package with a remote debugger: 162 | 163 | ```bash 164 | ./gradlew clean build -Pdebug= 165 | ``` 166 | 167 | 6. To debug with the Ballerina language: 168 | 169 | ```bash 170 | ./gradlew clean build -PbalJavaDebug= 171 | ``` 172 | 173 | 7. Publish the generated artifacts to the local Ballerina Central repository: 174 | 175 | ```bash 176 | ./gradlew clean build -PpublishToLocalCentral=true 177 | ``` 178 | 179 | 8. Publish the generated artifacts to the Ballerina Central repository: 180 | 181 | ```bash 182 | ./gradlew clean build -PpublishToCentral=true 183 | ``` 184 | 185 | ## Contributing to Ballerina 186 | As an open source project, Ballerina welcomes contributions from the community. 187 | 188 | For more information, go to the [contribution guidelines](https://github.com/ballerina-platform/ballerina-lang/blob/master/CONTRIBUTING.md). 189 | 190 | ## Code of conduct 191 | All contributors are encouraged to read the [Ballerina Code of Conduct](https://ballerina.io/code-of-conduct). 192 | 193 | ## Useful links 194 | * Discuss the code changes of the Ballerina project in [ballerina-dev@googlegroups.com](mailto:ballerina-dev@googlegroups.com). 195 | * Chat live with us via our [Discord server](https://discord.gg/ballerinalang). 196 | * Post all technical questions on Stack Overflow with the [#ballerina](https://stackoverflow.com/questions/tagged/ballerina) tag. 197 | -------------------------------------------------------------------------------- /ballerina/Dependencies.toml: -------------------------------------------------------------------------------- 1 | # AUTO-GENERATED FILE. DO NOT MODIFY. 2 | 3 | # This file is auto-generated by Ballerina for managing dependency versions. 4 | # It should not be modified by hand. 5 | 6 | [ballerina] 7 | dependencies-toml-version = "2" 8 | distribution-version = "2201.12.2" 9 | 10 | [[package]] 11 | org = "ballerina" 12 | name = "auth" 13 | version = "2.14.0" 14 | dependencies = [ 15 | {org = "ballerina", name = "crypto"}, 16 | {org = "ballerina", name = "jballerina.java"}, 17 | {org = "ballerina", name = "lang.array"}, 18 | {org = "ballerina", name = "lang.string"}, 19 | {org = "ballerina", name = "log"} 20 | ] 21 | 22 | [[package]] 23 | org = "ballerina" 24 | name = "cache" 25 | version = "3.10.0" 26 | dependencies = [ 27 | {org = "ballerina", name = "constraint"}, 28 | {org = "ballerina", name = "jballerina.java"}, 29 | {org = "ballerina", name = "task"}, 30 | {org = "ballerina", name = "time"} 31 | ] 32 | 33 | [[package]] 34 | org = "ballerina" 35 | name = "constraint" 36 | version = "1.7.0" 37 | dependencies = [ 38 | {org = "ballerina", name = "jballerina.java"} 39 | ] 40 | modules = [ 41 | {org = "ballerina", packageName = "constraint", moduleName = "constraint"} 42 | ] 43 | 44 | [[package]] 45 | org = "ballerina" 46 | name = "crypto" 47 | version = "2.9.2" 48 | dependencies = [ 49 | {org = "ballerina", name = "jballerina.java"}, 50 | {org = "ballerina", name = "time"} 51 | ] 52 | 53 | [[package]] 54 | org = "ballerina" 55 | name = "data.jsondata" 56 | version = "1.1.3" 57 | dependencies = [ 58 | {org = "ballerina", name = "jballerina.java"}, 59 | {org = "ballerina", name = "lang.object"} 60 | ] 61 | modules = [ 62 | {org = "ballerina", packageName = "data.jsondata", moduleName = "data.jsondata"} 63 | ] 64 | 65 | [[package]] 66 | org = "ballerina" 67 | name = "file" 68 | version = "1.12.0" 69 | dependencies = [ 70 | {org = "ballerina", name = "io"}, 71 | {org = "ballerina", name = "jballerina.java"}, 72 | {org = "ballerina", name = "os"}, 73 | {org = "ballerina", name = "time"} 74 | ] 75 | 76 | [[package]] 77 | org = "ballerina" 78 | name = "http" 79 | version = "2.14.8" 80 | dependencies = [ 81 | {org = "ballerina", name = "auth"}, 82 | {org = "ballerina", name = "cache"}, 83 | {org = "ballerina", name = "constraint"}, 84 | {org = "ballerina", name = "crypto"}, 85 | {org = "ballerina", name = "data.jsondata"}, 86 | {org = "ballerina", name = "file"}, 87 | {org = "ballerina", name = "io"}, 88 | {org = "ballerina", name = "jballerina.java"}, 89 | {org = "ballerina", name = "jwt"}, 90 | {org = "ballerina", name = "lang.array"}, 91 | {org = "ballerina", name = "lang.decimal"}, 92 | {org = "ballerina", name = "lang.int"}, 93 | {org = "ballerina", name = "lang.regexp"}, 94 | {org = "ballerina", name = "lang.runtime"}, 95 | {org = "ballerina", name = "lang.string"}, 96 | {org = "ballerina", name = "lang.value"}, 97 | {org = "ballerina", name = "log"}, 98 | {org = "ballerina", name = "mime"}, 99 | {org = "ballerina", name = "oauth2"}, 100 | {org = "ballerina", name = "observe"}, 101 | {org = "ballerina", name = "time"}, 102 | {org = "ballerina", name = "url"} 103 | ] 104 | modules = [ 105 | {org = "ballerina", packageName = "http", moduleName = "http"}, 106 | {org = "ballerina", packageName = "http", moduleName = "http.httpscerr"} 107 | ] 108 | 109 | [[package]] 110 | org = "ballerina" 111 | name = "io" 112 | version = "1.8.0" 113 | dependencies = [ 114 | {org = "ballerina", name = "jballerina.java"}, 115 | {org = "ballerina", name = "lang.value"} 116 | ] 117 | 118 | [[package]] 119 | org = "ballerina" 120 | name = "jballerina.java" 121 | version = "0.0.0" 122 | 123 | [[package]] 124 | org = "ballerina" 125 | name = "jwt" 126 | version = "2.15.1" 127 | dependencies = [ 128 | {org = "ballerina", name = "cache"}, 129 | {org = "ballerina", name = "crypto"}, 130 | {org = "ballerina", name = "io"}, 131 | {org = "ballerina", name = "jballerina.java"}, 132 | {org = "ballerina", name = "lang.int"}, 133 | {org = "ballerina", name = "lang.string"}, 134 | {org = "ballerina", name = "log"}, 135 | {org = "ballerina", name = "time"} 136 | ] 137 | 138 | [[package]] 139 | org = "ballerina" 140 | name = "lang.__internal" 141 | version = "0.0.0" 142 | dependencies = [ 143 | {org = "ballerina", name = "jballerina.java"}, 144 | {org = "ballerina", name = "lang.object"} 145 | ] 146 | 147 | [[package]] 148 | org = "ballerina" 149 | name = "lang.array" 150 | version = "0.0.0" 151 | dependencies = [ 152 | {org = "ballerina", name = "jballerina.java"}, 153 | {org = "ballerina", name = "lang.__internal"} 154 | ] 155 | 156 | [[package]] 157 | org = "ballerina" 158 | name = "lang.decimal" 159 | version = "0.0.0" 160 | dependencies = [ 161 | {org = "ballerina", name = "jballerina.java"} 162 | ] 163 | 164 | [[package]] 165 | org = "ballerina" 166 | name = "lang.error" 167 | version = "0.0.0" 168 | scope = "testOnly" 169 | dependencies = [ 170 | {org = "ballerina", name = "jballerina.java"} 171 | ] 172 | 173 | [[package]] 174 | org = "ballerina" 175 | name = "lang.int" 176 | version = "0.0.0" 177 | dependencies = [ 178 | {org = "ballerina", name = "jballerina.java"}, 179 | {org = "ballerina", name = "lang.__internal"}, 180 | {org = "ballerina", name = "lang.object"} 181 | ] 182 | 183 | [[package]] 184 | org = "ballerina" 185 | name = "lang.object" 186 | version = "0.0.0" 187 | 188 | [[package]] 189 | org = "ballerina" 190 | name = "lang.regexp" 191 | version = "0.0.0" 192 | dependencies = [ 193 | {org = "ballerina", name = "jballerina.java"} 194 | ] 195 | 196 | [[package]] 197 | org = "ballerina" 198 | name = "lang.runtime" 199 | version = "0.0.0" 200 | dependencies = [ 201 | {org = "ballerina", name = "jballerina.java"} 202 | ] 203 | 204 | [[package]] 205 | org = "ballerina" 206 | name = "lang.string" 207 | version = "0.0.0" 208 | dependencies = [ 209 | {org = "ballerina", name = "jballerina.java"}, 210 | {org = "ballerina", name = "lang.regexp"} 211 | ] 212 | 213 | [[package]] 214 | org = "ballerina" 215 | name = "lang.value" 216 | version = "0.0.0" 217 | dependencies = [ 218 | {org = "ballerina", name = "jballerina.java"} 219 | ] 220 | 221 | [[package]] 222 | org = "ballerina" 223 | name = "log" 224 | version = "2.12.0" 225 | dependencies = [ 226 | {org = "ballerina", name = "io"}, 227 | {org = "ballerina", name = "jballerina.java"}, 228 | {org = "ballerina", name = "lang.value"}, 229 | {org = "ballerina", name = "observe"} 230 | ] 231 | modules = [ 232 | {org = "ballerina", packageName = "log", moduleName = "log"} 233 | ] 234 | 235 | [[package]] 236 | org = "ballerina" 237 | name = "mime" 238 | version = "2.12.1" 239 | dependencies = [ 240 | {org = "ballerina", name = "io"}, 241 | {org = "ballerina", name = "jballerina.java"}, 242 | {org = "ballerina", name = "lang.int"}, 243 | {org = "ballerina", name = "log"} 244 | ] 245 | 246 | [[package]] 247 | org = "ballerina" 248 | name = "oauth2" 249 | version = "2.14.1" 250 | dependencies = [ 251 | {org = "ballerina", name = "cache"}, 252 | {org = "ballerina", name = "crypto"}, 253 | {org = "ballerina", name = "jballerina.java"}, 254 | {org = "ballerina", name = "log"}, 255 | {org = "ballerina", name = "time"}, 256 | {org = "ballerina", name = "url"} 257 | ] 258 | 259 | [[package]] 260 | org = "ballerina" 261 | name = "observe" 262 | version = "1.5.1" 263 | dependencies = [ 264 | {org = "ballerina", name = "jballerina.java"} 265 | ] 266 | 267 | [[package]] 268 | org = "ballerina" 269 | name = "os" 270 | version = "1.10.1" 271 | dependencies = [ 272 | {org = "ballerina", name = "io"}, 273 | {org = "ballerina", name = "jballerina.java"} 274 | ] 275 | modules = [ 276 | {org = "ballerina", packageName = "os", moduleName = "os"} 277 | ] 278 | 279 | [[package]] 280 | org = "ballerina" 281 | name = "task" 282 | version = "2.7.0" 283 | dependencies = [ 284 | {org = "ballerina", name = "jballerina.java"}, 285 | {org = "ballerina", name = "time"} 286 | ] 287 | 288 | [[package]] 289 | org = "ballerina" 290 | name = "test" 291 | version = "0.0.0" 292 | scope = "testOnly" 293 | dependencies = [ 294 | {org = "ballerina", name = "jballerina.java"}, 295 | {org = "ballerina", name = "lang.array"}, 296 | {org = "ballerina", name = "lang.error"} 297 | ] 298 | modules = [ 299 | {org = "ballerina", packageName = "test", moduleName = "test"} 300 | ] 301 | 302 | [[package]] 303 | org = "ballerina" 304 | name = "time" 305 | version = "2.7.0" 306 | dependencies = [ 307 | {org = "ballerina", name = "jballerina.java"} 308 | ] 309 | 310 | [[package]] 311 | org = "ballerina" 312 | name = "url" 313 | version = "2.6.1" 314 | dependencies = [ 315 | {org = "ballerina", name = "jballerina.java"} 316 | ] 317 | modules = [ 318 | {org = "ballerina", packageName = "url", moduleName = "url"} 319 | ] 320 | 321 | [[package]] 322 | org = "ballerinai" 323 | name = "observe" 324 | version = "0.0.0" 325 | dependencies = [ 326 | {org = "ballerina", name = "jballerina.java"}, 327 | {org = "ballerina", name = "observe"} 328 | ] 329 | modules = [ 330 | {org = "ballerinai", packageName = "observe", moduleName = "observe"} 331 | ] 332 | 333 | [[package]] 334 | org = "ballerinax" 335 | name = "slack" 336 | version = "5.0.0" 337 | dependencies = [ 338 | {org = "ballerina", name = "constraint"}, 339 | {org = "ballerina", name = "data.jsondata"}, 340 | {org = "ballerina", name = "http"}, 341 | {org = "ballerina", name = "log"}, 342 | {org = "ballerina", name = "os"}, 343 | {org = "ballerina", name = "test"}, 344 | {org = "ballerina", name = "url"}, 345 | {org = "ballerinai", name = "observe"} 346 | ] 347 | modules = [ 348 | {org = "ballerinax", packageName = "slack", moduleName = "slack"} 349 | ] 350 | 351 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /ballerina/utils.bal: -------------------------------------------------------------------------------- 1 | // AUTO-GENERATED FILE. DO NOT MODIFY. 2 | // This file is auto-generated by the Ballerina OpenAPI tool. 3 | 4 | // Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). 5 | // 6 | // WSO2 LLC. licenses this file to you under the Apache License, 7 | // Version 2.0 (the "License"); you may not use this file except 8 | // in compliance with the License. 9 | // You may obtain a copy of the License at 10 | // 11 | // http://www.apache.org/licenses/LICENSE-2.0 12 | // 13 | // Unless required by applicable law or agreed to in writing, 14 | // software distributed under the License is distributed on an 15 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | // KIND, either express or implied. See the License for the 17 | // specific language governing permissions and limitations 18 | // under the License. 19 | 20 | import ballerina/http; 21 | import ballerina/url; 22 | 23 | type SimpleBasicType string|boolean|int|float|decimal; 24 | 25 | # Represents encoding mechanism details. 26 | type Encoding record { 27 | # Defines how multiple values are delimited 28 | string style = FORM; 29 | # Specifies whether arrays and objects should generate as separate fields 30 | boolean explode = true; 31 | # Specifies the custom content type 32 | string contentType?; 33 | # Specifies the custom headers 34 | map headers?; 35 | }; 36 | 37 | enum EncodingStyle { 38 | DEEPOBJECT, FORM, SPACEDELIMITED, PIPEDELIMITED 39 | } 40 | 41 | final Encoding & readonly defaultEncoding = {}; 42 | 43 | # Generate client request when the media type is given as application/x-www-form-urlencoded. 44 | # 45 | # + encodingMap - Includes the information about the encoding mechanism 46 | # + anyRecord - Record to be serialized 47 | # + return - Serialized request body or query parameter as a string 48 | isolated function createFormURLEncodedRequestBody(record {|anydata...;|} anyRecord, map encodingMap = {}) returns string { 49 | string[] payload = []; 50 | foreach [string, anydata] [key, value] in anyRecord.entries() { 51 | Encoding encodingData = encodingMap.hasKey(key) ? encodingMap.get(key) : defaultEncoding; 52 | if value is SimpleBasicType { 53 | payload.push(key, "=", getEncodedUri(value.toString())); 54 | } else if value is SimpleBasicType[] { 55 | payload.push(getSerializedArray(key, value, encodingData.style, encodingData.explode)); 56 | } else if (value is record {}) { 57 | if encodingData.style == DEEPOBJECT { 58 | payload.push(getDeepObjectStyleRequest(key, value)); 59 | } else { 60 | payload.push(getFormStyleRequest(key, value)); 61 | } 62 | } else if (value is record {}[]) { 63 | payload.push(getSerializedRecordArray(key, value, encodingData.style, encodingData.explode)); 64 | } 65 | payload.push("&"); 66 | } 67 | _ = payload.pop(); 68 | return string:'join("", ...payload); 69 | } 70 | 71 | # Serialize the record according to the deepObject style. 72 | # 73 | # + parent - Parent record name 74 | # + anyRecord - Record to be serialized 75 | # + return - Serialized record as a string 76 | isolated function getDeepObjectStyleRequest(string parent, record {} anyRecord) returns string { 77 | string[] recordArray = []; 78 | foreach [string, anydata] [key, value] in anyRecord.entries() { 79 | if value is SimpleBasicType { 80 | recordArray.push(parent + "[" + key + "]" + "=" + getEncodedUri(value.toString())); 81 | } else if value is SimpleBasicType[] { 82 | recordArray.push(getSerializedArray(parent + "[" + key + "]" + "[]", value, DEEPOBJECT, true)); 83 | } else if value is record {} { 84 | string nextParent = parent + "[" + key + "]"; 85 | recordArray.push(getDeepObjectStyleRequest(nextParent, value)); 86 | } else if value is record {}[] { 87 | string nextParent = parent + "[" + key + "]"; 88 | recordArray.push(getSerializedRecordArray(nextParent, value, DEEPOBJECT)); 89 | } 90 | recordArray.push("&"); 91 | } 92 | _ = recordArray.pop(); 93 | return string:'join("", ...recordArray); 94 | } 95 | 96 | # Serialize the record according to the form style. 97 | # 98 | # + parent - Parent record name 99 | # + anyRecord - Record to be serialized 100 | # + explode - Specifies whether arrays and objects should generate separate parameters 101 | # + return - Serialized record as a string 102 | isolated function getFormStyleRequest(string parent, record {} anyRecord, boolean explode = true) returns string { 103 | string[] recordArray = []; 104 | if explode { 105 | foreach [string, anydata] [key, value] in anyRecord.entries() { 106 | if value is SimpleBasicType { 107 | recordArray.push(key, "=", getEncodedUri(value.toString())); 108 | } else if value is SimpleBasicType[] { 109 | recordArray.push(getSerializedArray(key, value, explode = explode)); 110 | } else if value is record {} { 111 | recordArray.push(getFormStyleRequest(parent, value, explode)); 112 | } 113 | recordArray.push("&"); 114 | } 115 | _ = recordArray.pop(); 116 | } else { 117 | foreach [string, anydata] [key, value] in anyRecord.entries() { 118 | if value is SimpleBasicType { 119 | recordArray.push(key, ",", getEncodedUri(value.toString())); 120 | } else if value is SimpleBasicType[] { 121 | recordArray.push(getSerializedArray(key, value, explode = false)); 122 | } else if value is record {} { 123 | recordArray.push(getFormStyleRequest(parent, value, explode)); 124 | } 125 | recordArray.push(","); 126 | } 127 | _ = recordArray.pop(); 128 | } 129 | return string:'join("", ...recordArray); 130 | } 131 | 132 | # Serialize arrays. 133 | # 134 | # + arrayName - Name of the field with arrays 135 | # + anyArray - Array to be serialized 136 | # + style - Defines how multiple values are delimited 137 | # + explode - Specifies whether arrays and objects should generate separate parameters 138 | # + return - Serialized array as a string 139 | isolated function getSerializedArray(string arrayName, anydata[] anyArray, string style = "form", boolean explode = true) returns string { 140 | string key = arrayName; 141 | string[] arrayValues = []; 142 | if anyArray.length() > 0 { 143 | if style == FORM && !explode { 144 | arrayValues.push(key, "="); 145 | foreach anydata i in anyArray { 146 | arrayValues.push(getEncodedUri(i.toString()), ","); 147 | } 148 | } else if style == SPACEDELIMITED && !explode { 149 | arrayValues.push(key, "="); 150 | foreach anydata i in anyArray { 151 | arrayValues.push(getEncodedUri(i.toString()), "%20"); 152 | } 153 | } else if style == PIPEDELIMITED && !explode { 154 | arrayValues.push(key, "="); 155 | foreach anydata i in anyArray { 156 | arrayValues.push(getEncodedUri(i.toString()), "|"); 157 | } 158 | } else if style == DEEPOBJECT { 159 | foreach anydata i in anyArray { 160 | arrayValues.push(key, "[]", "=", getEncodedUri(i.toString()), "&"); 161 | } 162 | } else { 163 | foreach anydata i in anyArray { 164 | arrayValues.push(key, "=", getEncodedUri(i.toString()), "&"); 165 | } 166 | } 167 | _ = arrayValues.pop(); 168 | } 169 | return string:'join("", ...arrayValues); 170 | } 171 | 172 | # Serialize the array of records according to the form style. 173 | # 174 | # + parent - Parent record name 175 | # + value - Array of records to be serialized 176 | # + style - Defines how multiple values are delimited 177 | # + explode - Specifies whether arrays and objects should generate separate parameters 178 | # + return - Serialized record as a string 179 | isolated function getSerializedRecordArray(string parent, record {}[] value, string style = FORM, boolean explode = true) returns string { 180 | string[] serializedArray = []; 181 | if style == DEEPOBJECT { 182 | int arayIndex = 0; 183 | foreach var recordItem in value { 184 | serializedArray.push(getDeepObjectStyleRequest(parent + "[" + arayIndex.toString() + "]", recordItem), "&"); 185 | arayIndex = arayIndex + 1; 186 | } 187 | } else { 188 | if !explode { 189 | serializedArray.push(parent, "="); 190 | } 191 | foreach var recordItem in value { 192 | serializedArray.push(getFormStyleRequest(parent, recordItem, explode), ","); 193 | } 194 | } 195 | _ = serializedArray.pop(); 196 | return string:'join("", ...serializedArray); 197 | } 198 | 199 | # Get Encoded URI for a given value. 200 | # 201 | # + value - Value to be encoded 202 | # + return - Encoded string 203 | isolated function getEncodedUri(anydata value) returns string { 204 | string|error encoded = url:encode(value.toString(), "UTF8"); 205 | if encoded is string { 206 | return encoded; 207 | } else { 208 | return value.toString(); 209 | } 210 | } 211 | 212 | # Generate query path with query parameter. 213 | # 214 | # + queryParam - Query parameter map 215 | # + encodingMap - Details on serialization mechanism 216 | # + return - Returns generated Path or error at failure of client initialization 217 | isolated function getPathForQueryParam(map queryParam, map encodingMap = {}) returns string|error { 218 | map queriesMap = http:getQueryMap(queryParam); 219 | string[] param = []; 220 | if queriesMap.length() > 0 { 221 | param.push("?"); 222 | foreach var [key, value] in queriesMap.entries() { 223 | if value is () { 224 | _ = queriesMap.remove(key); 225 | continue; 226 | } 227 | Encoding encodingData = encodingMap.hasKey(key) ? encodingMap.get(key) : defaultEncoding; 228 | if value is SimpleBasicType { 229 | param.push(key, "=", getEncodedUri(value.toString())); 230 | } else if value is SimpleBasicType[] { 231 | param.push(getSerializedArray(key, value, encodingData.style, encodingData.explode)); 232 | } else if value is record {} { 233 | if encodingData.style == DEEPOBJECT { 234 | param.push(getDeepObjectStyleRequest(key, value)); 235 | } else { 236 | param.push(getFormStyleRequest(key, value, encodingData.explode)); 237 | } 238 | } else { 239 | param.push(key, "=", value.toString()); 240 | } 241 | param.push("&"); 242 | } 243 | _ = param.pop(); 244 | } 245 | string restOfPath = string:'join("", ...param); 246 | return restOfPath; 247 | } 248 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------