diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 00000000..c440bcde --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,10 @@ +## Purpose + +## Examples + +## Checklist +- [ ] Linked to an issue +- [ ] Updated the changelog +- [ ] Added tests +- [ ] Updated the spec +- [ ] Checked native-image compatibility diff --git a/.github/workflows/build-timestamped-master.yml b/.github/workflows/build-timestamped-master.yml new file mode 100644 index 00000000..f95fcbc0 --- /dev/null +++ b/.github/workflows/build-timestamped-master.yml @@ -0,0 +1,50 @@ +name: Build + +on: + push: + branches: + - master + paths-ignore: + - '*.md' + - 'docs/**' + - 'load-tests/**' + + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + if: github.repository_owner == 'ballerina-platform' + steps: + - name: Checkout Repository + uses: actions/checkout@v2 + - name: Set up JDK 11 + uses: actions/setup-java@v2 + with: + distribution: 'temurin' + java-version: 11 + - name: Change to Timestamped Version + run: | + startTime=$(TZ="Asia/Kolkata" date +'%Y%m%d-%H%M00') + latestCommit=$(git log -n 1 --pretty=format:"%h") + VERSION=$((grep -w 'version' | cut -d= -f2) < gradle.properties | rev | cut --complement -d- -f1 | rev) + updatedVersion=$VERSION-$startTime-$latestCommit + echo $updatedVersion + sed -i "s/version=\(.*\)/version=$updatedVersion/g" gradle.properties + - name: Grant execute permission for gradlew + run: chmod +x gradlew + - name: Build with Gradle + env: + packageUser: ${{ secrets.BALLERINA_BOT_USERNAME }} + packagePAT: ${{ secrets.BALLERINA_BOT_TOKEN }} + publishUser: ${{ secrets.BALLERINA_BOT_USERNAME }} + publishPAT: ${{ secrets.BALLERINA_BOT_TOKEN }} + run: | + ./gradlew publish --scan --no-daemon + - name: Generate Codecov Report + uses: codecov/codecov-action@v2 + - name: Upload Artifact + uses: actions/upload-artifact@v2 + with: + name: ballerina-runtime + path: target/ballerina-runtime/ diff --git a/.github/workflows/build-with-bal-test-graalvm.yml b/.github/workflows/build-with-bal-test-graalvm.yml new file mode 100644 index 00000000..b3a15155 --- /dev/null +++ b/.github/workflows/build-with-bal-test-graalvm.yml @@ -0,0 +1,39 @@ +name: GraalVM Check + +on: + workflow_dispatch: + inputs: + lang_tag: + description: Branch/Release Tag of the Ballerina Lang + required: true + default: master + lang_version: + description: Ballerina Lang Version (If given ballerina lang buid will be skipped) + required: false + default: '' + native_image_options: + description: Default native-image options + required: false + default: '' + schedule: + - cron: '30 18 * * *' + pull_request: + branches: + - master + types: [ opened, synchronize, reopened, labeled, unlabeled ] + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }} + cancel-in-progress: true + +jobs: + call_stdlib_workflow: + name: Run StdLib Workflow + if: ${{ github.event_name != 'schedule' || (github.event_name == 'schedule' && github.repository_owner == 'ballerina-platform') }} + uses: ballerina-platform/ballerina-standard-library/.github/workflows/build-with-bal-test-graalvm-template.yml@main + with: + lang_tag: ${{ inputs.lang_tag }} + lang_version: ${{ inputs.lang_version }} + native_image_options: ${{ inputs.native_image_options }} +# additional_ubuntu_build_flags: '-x :email-compiler-plugin-tests:test' +# additional_windows_build_flags: '-x :email-compiler-plugin-tests:test' diff --git a/.github/workflows/central-publish.yml b/.github/workflows/central-publish.yml new file mode 100644 index 00000000..2d1aea76 --- /dev/null +++ b/.github/workflows/central-publish.yml @@ -0,0 +1,77 @@ +name: Publish to the Ballerina central + +on: + workflow_dispatch: + inputs: + environment: + type: choice + description: Select environment + required: true + options: + - CENTRAL + - DEV CENTRAL + - STAGE CENTRAL + +jobs: + publish-release: + runs-on: ubuntu-latest + if: github.repository_owner == 'ballerina-platform' + steps: + - name: Checkout Repository + uses: actions/checkout@v2 + - name: Set up JDK 11 + uses: actions/setup-java@v2 + with: + distribution: 'temurin' + java-version: 11 + - name: Build with Gradle + env: + packageUser: ${{ github.actor }} + packagePAT: ${{ secrets.GITHUB_TOKEN }} + run: ./gradlew build -x check -x test + - name: Create lib directory if not exists + run: mkdir -p ballerina/lib + - name: Run Trivy vulnerability scanner + uses: aquasecurity/trivy-action@master + with: + scan-type: 'rootfs' + scan-ref: '/github/workspace/ballerina/lib' + format: 'table' + timeout: '10m0s' + exit-code: '1' + + - name: Ballerina Central Push + if: ${{ github.event.inputs.environment == 'CENTRAL' }} + env: + BALLERINA_DEV_CENTRAL: false + BALLERINA_STAGE_CENTRAL: false + BALLERINA_CENTRAL_ACCESS_TOKEN: ${{ secrets.BALLERINA_CENTRAL_ACCESS_TOKEN }} + packageUser: ${{ secrets.BALLERINA_BOT_USERNAME }} + packagePAT: ${{ secrets.BALLERINA_BOT_TOKEN }} + GITHUB_TOKEN: ${{ secrets.BALLERINA_BOT_TOKEN }} + run: | + ./gradlew clean build -PpublishToCentral=true + - name: Ballerina Central Dev Push + if: ${{ github.event.inputs.environment == 'DEV CENTRAL' }} + env: + BALLERINA_DEV_CENTRAL: true + BALLERINA_STAGE_CENTRAL: false + BALLERINA_CENTRAL_ACCESS_TOKEN: ${{ secrets.BALLERINA_CENTRAL_DEV_ACCESS_TOKEN }} + packageUser: ${{ secrets.BALLERINA_BOT_USERNAME }} + packagePAT: ${{ secrets.BALLERINA_BOT_TOKEN }} + GITHUB_TOKEN: ${{ secrets.BALLERINA_BOT_TOKEN }} + run: | + sed -i 's/version=\(.*\)-SNAPSHOT/version=\1/g' gradle.properties + ./gradlew clean build -PpublishToCentral=true + - name: Ballerina Central Stage Push + if: ${{ github.event.inputs.environment == 'STAGE CENTRAL' }} + env: + BALLERINA_DEV_CENTRAL: false + BALLERINA_STAGE_CENTRAL: true + BALLERINA_CENTRAL_ACCESS_TOKEN: ${{ secrets.BALLERINA_CENTRAL_STAGE_ACCESS_TOKEN }} + packageUser: ${{ secrets.BALLERINA_BOT_USERNAME }} + packagePAT: ${{ secrets.BALLERINA_BOT_TOKEN }} + GITHUB_TOKEN: ${{ secrets.BALLERINA_BOT_TOKEN }} + run: | + sed -i 's/version=\(.*\)-SNAPSHOT/version=\1/g' gradle.properties + ./gradlew clean build -PpublishToCentral=true diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml deleted file mode 100644 index 57348132..00000000 --- a/.github/workflows/ci.yml +++ /dev/null @@ -1,21 +0,0 @@ -name: CI - -on: [push] - -jobs: - build: - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v2 - - run: mvn clean install -pl !java.jms - - run: cd java.jms - - name: Ballerina Build - uses: ballerina-platform/ballerina-action/@swan-lake-release - with: - args: - build -a -c --sourceroot java.jms - env: - JAVA_OPTS: -DBALLERINA_DEV_COMPILE_BALLERINA_ORG=true - diff --git a/.github/workflows/process-load-test-result.yml b/.github/workflows/process-load-test-result.yml new file mode 100644 index 00000000..ca77e3b5 --- /dev/null +++ b/.github/workflows/process-load-test-result.yml @@ -0,0 +1,15 @@ +name: Process load test results + +on: + repository_dispatch: + types: [java.jms-load-test] + +jobs: + call_stdlib_process_load_test_results_workflow: + name: Run StdLib Process Load Test Results Workflow + uses: ballerina-platform/ballerina-standard-library/.github/workflows/process-load-test-results-template.yml@main + with: + results: ${{ toJson(github.event.client_payload.results) }} + secrets: + ballerina_bot_token: ${{ secrets.BALLERINA_BOT_TOKEN }} + ballerina_reviewer_bot_token: ${{ secrets.BALLERINA_REVIEWER_BOT_TOKEN }} diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml new file mode 100644 index 00000000..702762c8 --- /dev/null +++ b/.github/workflows/publish-release.yml @@ -0,0 +1,70 @@ +name: Publish release + +on: + workflow_dispatch: + repository_dispatch: + types: [ stdlib-release-pipeline ] + +jobs: + publish-release: + runs-on: ubuntu-latest + if: github.repository_owner == 'ballerina-platform' + steps: + - name: Checkout Repository + uses: actions/checkout@v2 + - name: Set up JDK 11 + uses: actions/setup-java@v2 + with: + distribution: 'temurin' + java-version: 11 + - name: Build with Gradle + env: + packageUser: ${{ github.actor }} + packagePAT: ${{ secrets.GITHUB_TOKEN }} + run: | + git config --global user.name ${{ secrets.BALLERINA_BOT_USERNAME }} + git config --global user.email ${{ secrets.BALLERINA_BOT_EMAIL }} + ./gradlew build -x check -x test + - name: Create lib directory if not exists + run: mkdir -p ballerina/lib + - name: Run Trivy vulnerability scanner + uses: aquasecurity/trivy-action@master + with: + scan-type: 'rootfs' + scan-ref: '/github/workspace/ballerina/lib' + format: 'table' + timeout: '10m0s' + exit-code: '1' + - name: Set version env variable + run: echo "VERSION=$((grep -w 'version' | cut -d= -f2) < gradle.properties | rev | cut --complement -d- -f1 | rev)" >> $GITHUB_ENV + - name: Pre release dependency version update + env: + GITHUB_TOKEN: ${{ secrets.BALLERINA_BOT_TOKEN }} + run: | + echo "Version: ${VERSION}" + git checkout -b release-${VERSION} + sed -i 's/ballerinaLangVersion=\(.*\)-SNAPSHOT/ballerinaLangVersion=\1/g' gradle.properties + sed -i 's/ballerinaLangVersion=\(.*\)-[0-9]\{8\}-[0-9]\{6\}-.*$/ballerinaLangVersion=\1/g' gradle.properties + sed -i 's/stdlib\(.*\)=\(.*\)-SNAPSHOT/stdlib\1=\2/g' gradle.properties + sed -i 's/stdlib\(.*\)=\(.*\)-[0-9]\{8\}-[0-9]\{6\}-.*$/stdlib\1=\2/g' gradle.properties + sed -i 's/observe\(.*\)=\(.*\)-SNAPSHOT/observe\1=\2/g' gradle.properties + sed -i 's/observe\(.*\)=\(.*\)-[0-9]\{8\}-[0-9]\{6\}-.*$/observe\1=\2/g' gradle.properties + git add gradle.properties + git commit -m "Move dependencies to stable version" || echo "No changes to commit" + - name: Publish artifact + env: + GITHUB_TOKEN: ${{ secrets.BALLERINA_BOT_TOKEN }} + BALLERINA_CENTRAL_ACCESS_TOKEN: ${{ secrets.BALLERINA_CENTRAL_ACCESS_TOKEN }} + packageUser: ${{ secrets.BALLERINA_BOT_USERNAME }} + packagePAT: ${{ secrets.BALLERINA_BOT_TOKEN }} + publishUser: ${{ secrets.BALLERINA_BOT_USERNAME }} + publishPAT: ${{ secrets.BALLERINA_BOT_TOKEN }} + run: | + ./gradlew clean release -Prelease.useAutomaticVersion=true + ./gradlew -Pversion=${VERSION} publish -x test -PpublishToCentral=true + - name: GitHub Release and Release Sync PR + env: + GITHUB_TOKEN: ${{ secrets.BALLERINA_BOT_TOKEN }} + run: | + gh release create v$VERSION --title "module-ballerina-java.jms-v$VERSION" + gh pr create --title "[Automated] Sync master after $VERSION release" --body "Sync master after $VERSION release" diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml new file mode 100644 index 00000000..f8dc307c --- /dev/null +++ b/.github/workflows/pull-request.yml @@ -0,0 +1,44 @@ +name: PR build + +on: [pull_request] + +jobs: + ubuntu-build: + name: Build on Ubuntu + runs-on: ubuntu-latest + steps: + - name: Checkout Repository + uses: actions/checkout@v2 + - name: Set up JDK 11 + uses: actions/setup-java@v2 + with: + distribution: 'temurin' + java-version: 11 + - name: Build with Gradle + env: + packageUser: ${{ github.actor }} + packagePAT: ${{ secrets.GITHUB_TOKEN }} + run: ./gradlew build --scan --no-daemon + - name: Generate CodeCov Report + if: github.event_name == 'pull_request' + uses: codecov/codecov-action@v2 + with: + token: ${{ secrets.CODECOV_TOKEN }} + + windows-build: + name: Build on Windows + runs-on: windows-latest + steps: + - name: Checkout Repository + uses: actions/checkout@v2 + - name: Set up JDK 11 + uses: actions/setup-java@v2 + with: + distribution: 'temurin' + java-version: 11 + - name: Build with Gradle + env: + packageUser: ${{ github.actor }} + packagePAT: ${{ secrets.GITHUB_TOKEN }} + JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF8 + run: ./gradlew.bat build --scan --no-daemon diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index c6793bf7..00000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,30 +0,0 @@ -name: Deployment - -on: - release: - types: [published] - -jobs: - build: - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v2 - - run: mvn clean install -pl !java.jms - - run: cd java.jms - - name: Ballerina Build - uses: ballerina-platform/ballerina-action/@swan-lake-release - with: - args: - build -a -c --sourceroot java.jms - env: - JAVA_OPTS: -DBALLERINA_DEV_COMPILE_BALLERINA_ORG=true - - name: Ballerina Push - uses: ballerina-platform/ballerina-action/@master - with: - args: - push -a - env: - WORKING_DIR: ./java.jms - BALLERINA_CENTRAL_ACCESS_TOKEN: ${{ secrets.BALLERINA_CENTRAL_ACCESS_TOKEN }} diff --git a/.github/workflows/stale_check.yml b/.github/workflows/stale_check.yml new file mode 100644 index 00000000..8763360a --- /dev/null +++ b/.github/workflows/stale_check.yml @@ -0,0 +1,19 @@ +name: 'Close stale pull requests' + +on: + schedule: + - cron: '30 19 * * *' + workflow_dispatch: + +jobs: + stale: + runs-on: ubuntu-latest + steps: + - uses: actions/stale@v3 + with: + stale-pr-message: 'This PR has been open for more than 15 days with no activity. This will be closed in 3 days unless the `stale` label is removed or commented.' + close-pr-message: 'Closed PR due to inactivity for more than 18 days.' + days-before-pr-stale: 15 + days-before-pr-close: 3 + days-before-issue-stale: -1 + days-before-issue-close: -1 diff --git a/.github/workflows/trigger-load-tests.yml b/.github/workflows/trigger-load-tests.yml new file mode 100644 index 00000000..3d6303ba --- /dev/null +++ b/.github/workflows/trigger-load-tests.yml @@ -0,0 +1,34 @@ +name: Trigger Load Tests + +on: + workflow_dispatch: + inputs: + tests: + description: > + List of test names. This needs to be filled only if you want to run a specific set of tests. Example: foo,bar + required: false + clusterName: + description: 'Cluster name' + default: 'java.jms-perf-cluster-test' + required: false + branch: + description: 'Branch of the given repository' + default: '' + required: false + schedule: + - cron: '30 15 * * *' + +jobs: + call_stdlib_trigger_load_test_workflow: + name: Run StdLib Load Test Workflow + if: ${{ github.event_name != 'schedule' || (github.event_name == 'schedule' && github.repository_owner == 'ballerina-platform') }} + uses: ballerina-platform/ballerina-standard-library/.github/workflows/trigger-load-tests-template.yml@main + with: + repo_name: 'module-ballerina-java.jms' + runtime_artifacts_url: 'https://api.github.com/repos/ballerina-platform/module-ballerina-java.jms/actions/artifacts' + dispatch_type: 'java.jms-load-test' + cluster_name: ${{ inputs.clusterName }} + tests: ${{ inputs.tests }} + branch: ${{ inputs.branch }} + secrets: + ballerina_bot_token: ${{ secrets.BALLERINA_BOT_TOKEN }} diff --git a/.github/workflows/trivy-scan.yml b/.github/workflows/trivy-scan.yml new file mode 100644 index 00000000..3e3b3389 --- /dev/null +++ b/.github/workflows/trivy-scan.yml @@ -0,0 +1,33 @@ +name: Trivy + +on: + workflow_dispatch: + schedule: + - cron: '30 20 * * *' + +jobs: + ubuntu-build: + name: Build on Ubuntu + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 11 + uses: actions/setup-java@v2 + with: + distribution: 'temurin' + java-version: 11 + - name: Build with Gradle + env: + packageUser: ${{ github.actor }} + packagePAT: ${{ secrets.GITHUB_TOKEN }} + run: ./gradlew build -x check -x test + - name: Create lib directory if not exists + run: mkdir -p ballerina/lib + - name: Run Trivy vulnerability scanner + uses: aquasecurity/trivy-action@master + with: + scan-type: 'rootfs' + scan-ref: '/github/workspace/ballerina/lib' + format: 'table' + timeout: '10m0s' + exit-code: '1' diff --git a/.github/workflows/update_specs.yml b/.github/workflows/update_specs.yml new file mode 100644 index 00000000..3af6d4a4 --- /dev/null +++ b/.github/workflows/update_specs.yml @@ -0,0 +1,48 @@ +name: Update Specifications + +env: + SPEC_FOLDER_PATH: 'docs/spec' + +on: + workflow_dispatch: + push: + branches: + - master + paths: + - 'docs/spec/**' + +jobs: + update_specs: + name: Update Specifications + if: github.repository_owner == 'ballerina-platform' + runs-on: ubuntu-latest + + steps: + - name: Checkout Repository + uses: actions/checkout@v2 + + - name: Get current date + id: date + run: echo "::set-output name=date::$(date +'%Y-%m-%d')" + + - name: Get Repo Name + id: repo_name + run: | + MODULE=${{ github.event.repository.name }} + echo "::set-output name=short_name::${MODULE##*-}" + + - name: Trigger Workflow + run: | + curl --request POST \ + 'https://api.github.com/repos/ballerina-platform/ballerina-dev-website/dispatches' \ + -H 'Accept: application/vnd.github.v3+json' \ + -H 'Authorization: Bearer ${{ secrets.BALLERINA_BOT_TOKEN }}' \ + --data "{ + \"event_type\": \"update-stdlib-specs\", + \"client_payload\": { + \"module_name\": \"${{ github.event.repository.name }}\", + \"short_name\": \"${{ steps.repo_name.outputs.short_name }}\", + \"file_dir\": \"${{ github.event.repository.name }}/${{ env.SPEC_FOLDER_PATH }}\", + \"release_date\": \"${{ steps.date.outputs.date }}\" + } + }" diff --git a/.gitignore b/.gitignore index a292a45a..8e055018 100644 --- a/.gitignore +++ b/.gitignore @@ -1,16 +1,18 @@ -# Compiled class file -*.class +# Ignore Gradle project-specific cache directory +.gradle -# Log file -*.log +# Build Files +target +build -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ +# IDEA Files +.idea/ +*.iml +*.ipr +*.iws # Package Files # +!gradle/wrapper/gradle-wrapper.jar *.jar *.war *.nar @@ -19,20 +21,25 @@ *.tar.gz *.rar -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* +# MacOS +*.DS_Store -# ignore Intellij-IDEA files -*.iml -.idea/ -.DS_Store -.classpath -.settings +# Ballerina +velocity.log* +*Ballerina.lock -# Eclipse files +# VSCode +.vscode .project - -#VSCode -.vscode/ -# Temporary directories -target/ +.settings/ +ballerina/.project +ballerina/.settings/ +build-config/checkstyle/.classpath +build-config/checkstyle/.project +build-config/checkstyle/.settings/ +native/.classpath +native/.project +native/.settings/ +test-utils/.classpath +test-utils/.project +test-utils/.settings/ diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index bf369636..00000000 --- a/.travis.yml +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright (c) 2019, WSO2 Inc. (http://wso2.com) All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -script: - - wget http://dist.ballerina.io/downloads/swan-lake-preview1/ballerina-linux-installer-x64-swan-lake-preview1.deb - - sudo dpkg -i ballerina-linux-installer-x64-swan-lake-preview1.deb - - sudo apt-get install -f - - export JAVA_OPTS="-DBALLERINA_DEV_COMPILE_BALLERINA_ORG=true" - - mvn clean install -DskipTests=true - diff --git a/README.md b/README.md index 94a207e8..a348b002 100644 --- a/README.md +++ b/README.md @@ -1,70 +1,72 @@ -[![Build Status](https://travis-ci.com/ballerina-platform/module-ballerina-java.jms.svg?branch=master)](https://travis-ci.com/ballerina-platform/module-ballerina-java.jms) +# Ballerina `java.jms` Library -## Module overview +[![Build](https://github.com/ballerina-platform/module-ballerina-java.jms/actions/workflows/build-timestamped-master.yml/badge.svg)](https://github.com/ballerina-platform/module-ballerina-java.jms/actions/workflows/build-timestamped-master.yml) +[![codecov](https://codecov.io/gh/ballerina-platform/module-ballerina-java.jms/branch/master/graph/badge.svg)](https://codecov.io/gh/ballerina-platform/module-ballerina-java.jms) +[![Trivy](https://github.com/ballerina-platform/module-ballerina-java.jms/actions/workflows/trivy-scan.yml/badge.svg)](https://github.com/ballerina-platform/module-ballerina-java.jms/actions/workflows/trivy-scan.yml) +[![GraalVM Check](https://github.com/ballerina-platform/module-ballerina-java.jms/actions/workflows/build-with-bal-test-graalvm.yml/badge.svg)](https://github.com/ballerina-platform/module-ballerina-java.jms/actions/workflows/build-with-bal-test-graalvm.yml) +[![GitHub Last Commit](https://img.shields.io/github/last-commit/ballerina-platform/module-ballerina-java.jms.svg)](https://github.com/ballerina-platform/module-ballerina-java.jms/commits/master) -The `ballerina/java.jms` module provides an API to connect to an external JMS provider like ActiveMQ from Ballerina. +The `ballerina/java.jms` library provides an API to connect to an external JMS provider like ActiveMQ from Ballerina. -This module is created with minimal deviation from the JMS API to make it easy for the developers who are used to working - with the JMS API. This module is written to support both JMS 2.0 and JMS 1.0 API. +This library is created with minimal deviation from the JMS API to make it easy for the developers who are used to working with the JMS API. This library is written to support both JMS 2.0 and JMS 1.0 API. - Currently, the following JMS API Classes are supported through this module. +Currently, the following JMS API Classes are supported through this library. - Connection - Session - Destination (Queue, Topic, TemporaryQueue, TemporaryTopic) - - Message (TextMessage, MapMessage, BytesMessage, StreamMessage) + - Message (TextMessage, MapMessage, BytesMessage) - MessageConsumer - MessageProducer -The following sections provide details on how to use the JMS connector. - -- [Compatibility](#compatibility) -- [Samples](#samples) - -## Compatibility - -| Ballerina Language Version | JMS Module Version | -|:---------------------------:|:------------------------------:| -| 1.0.x | 0.6.x | -| 1.1.x | 0.7.x | -| 1.2.x | 0.8.x | -| Swan Lake Preview1 | 0.99.x | + The following sections provide details on how to use the JMS connector. + + - [Samples](#samples) ## Samples -### JMS Message Producer and Consumer example +### JMS message Producer -Following is a simple Ballerina program that sends and receives a message from a queue named *MyQueue*. +The following Ballerina program sends messages to a queue named *MyQueue*. ```ballerina -import ballerina/log; -import ballerina/java.jms; +import ballerinax/java.jms; public function main() returns error? { - jms:Connection connection = check jms:createConnection({ - initialContextFactory: "org.apache.activemq.jndi.ActiveMQInitialContextFactory", - providerUrl: "tcp://localhost:61616" - }); + initialContextFactory: "org.apache.activemq.jndi.ActiveMQInitialContextFactory", + providerUrl: "tcp://localhost:61616" + }); jms:Session session = check connection->createSession({acknowledgementMode: "AUTO_ACKNOWLEDGE"}); jms:Destination queue = check session->createQueue("MyQueue"); jms:MessageProducer producer = check session.createProducer(queue); - jms:MessageConsumer consumer = check session->createConsumer(queue); + jms:TextMessage msg = { + content: "Hello Ballerina!" + }; + check producer->send(msg); +} +``` - jms:TextMessage msg = check session.createTextMessage("Hello Ballerina!"); +## JMS message consumer +The following Ballerina program receives messages from a queue named *MyQueue*. +```ballerina +import ballerinax/java.jms; +import ballerina/log; - check producer->send(msg); +public function main() returns error? { + jms:Connection connection = check jms:createConnection({ + initialContextFactory: "org.apache.activemq.jndi.ActiveMQInitialContextFactory", + providerUrl: "tcp://localhost:61616" + }); + jms:Session session = check connection->createSession({acknowledgementMode: "AUTO_ACKNOWLEDGE"}); + jms:Destination queue = check session->createQueue("MyQueue"); + jms:MessageConsumer consumer = check session.createConsumer(queue); - jms:Message? response = check consumer->receive(3000); - if (response is jms:TextMessage) { - var val = response.getText(); - if (val is string) { - log:printInfo("Message received: " + val); - } else { - log:printInfo("Message received without text"); + while true { + jms:Message? response = check consumer->receive(3000); + if response is jms:TextMessage { + log:printInfo("Message received: ", content = response.toString()); } - } else { - log:printInfo("Message received."); } } ``` @@ -72,67 +74,127 @@ public function main() returns error? { ### Asynchronous message consumer One of the key deviations from the JMS API was the asynchronous message consumption using message listeners. In -Ballerina transport listener, the concept is covered with the **service** type, hence we have used the Ballerina service to -implement the message listener. Following is a message listener example listening on a topic named *MyTopic*. +Ballerina transport listener concept is covered with **service** type, hence we have used the Ballerina service to +implement the message listener. Following is a message listener example listening on a queue named *MyQueue*. ```ballerina import ballerina/log; -import ballerina/java.jms; - -jms:Connection connection = check jms:createConnection({ - initialContextFactory: "org.apache.activemq.jndi.ActiveMQInitialContextFactory", - providerUrl: "tcp://localhost:61616" - }); - -listener jms:MessageConsumer jmsConsumer = createListener(connection); - -service messageListener on jmsConsumer { - - resource function onMessage(jms:Message message) { - if (message is jms:TextMessage) { - var val = message.getText(); - if (val is string) { - log:printInfo("Message received: " + val ); - } else { - log:printInfo("Message received without text"); - } - } else { - log:printInfo("Message received."); - } - } -} - -function createListener(jms:Connection connection) returns jms:MessageConsumer { - jms:Session session = checkpanic connection->createSession({acknowledgementMode: "AUTO_ACKNOWLEDGE"}); - jms:Destination queue = checkpanic session->createQueue("MyQueue"); - jms:MessageConsumer consumer = checkpanic session->createConsumer(queue); - return consumer; +import ballerinax/java.jms; + +service "consumer-service" on new jms:Listener( + connectionConfig = { + initialContextFactory: "org.apache.activemq.jndi.ActiveMQInitialContextFactory", + providerUrl: "tcp://localhost:61616" + }, + sessionConfig = { + acknowledgementMode: "AUTO_ACKNOWLEDGE" + }, + destination = { + 'type: jms:QUEUE, + name: "MyQueue" + } +) { + remote function onMessage(jms:Message message) returns error? { + if message is jms:TextMessage { + log:printInfo("Text message received", content = message.content); + } + } } ``` + ## Adding the required dependencies Add the required dependencies to the `Ballerina.toml` file based on the broker that you're trying to connect to. - Add the configurations below to run the given examples using `Apache ActiveMQ`. +Add the configurations below to run the given examples using `Apache ActiveMQ`. ``` - [[platform.libraries]] - module = "jms" - path = "/activemq-client-5.15.12.jar" - artifactId = "activemq-client" - version = "5.15.12" - groupId = "org.apache.activemq" - - [[platform.libraries]] - module = "jms" - path = "/geronimo-j2ee-management_1.1_spec-1.0.1.jar" - artifactId = "geronimo-j2ee-management_1.1_spec" - version = "1.0.1" - groupId = "org.apache.geronimo.specs" - - [[platform.libraries]] - module = "jms" - path = "/libs/hawtbuf-1.11.jar" - artifactId = "hawtbuf" - version = "1.11" - groupId = "org.fusesource.hawtbuf" +[[platform.java11.dependency]] +groupId = "org.apache.activemq" +artifactId = "activemq-client" +version = "5.18.2" + +[[platform.java11.dependency]] +groupId = "org.apache.geronimo.specs" +artifactId = "geronimo-j2ee-management_1.1_spec" +version = "1.0.1" + +[[platform.java11.dependency]] +groupId = "org.fusesource.hawtbuf" +artifactId = "hawtbuf" +version = "1.11" ``` + +## Issues and projects + +Issues and Projects tabs are disabled for this repository as this is part of the Ballerina Standard Library. To report bugs, request new features, start new discussions, view project boards, etc., go to the [Ballerina Standard Library parent repository](https://github.com/ballerina-platform/ballerina-standard-library). + +This repository only contains the source code for the library. + +## Build from the source + +### Set up the prerequisites + +* Download and install Java SE Development Kit (JDK) version 11 (from one of the following locations). + + * [Oracle](https://www.oracle.com/java/technologies/javase-jdk11-downloads.html) + + * [OpenJDK](https://adoptium.net/) + + > **Note:** Set the JAVA_HOME environment variable to the path name of the directory into which you installed JDK. + +2. Download and install [Docker](https://www.docker.com/). This is required to run the tests. + +### Build the source + +Execute the commands below to build from the source. + +1. To build the library: + ``` + ./gradlew clean build + ``` + +2. To run the tests: + ``` + ./gradlew clean test + ``` +3. To build the library without the tests: + ``` + ./gradlew clean build -x test + ``` +4. To debug library implementation: + ``` + ./gradlew clean build -Pdebug= + ``` +5. To debug the library with Ballerina language: + ``` + ./gradlew clean build -PbalJavaDebug= + ``` +6. Publish ZIP artifact to the local `.m2` repository: + ``` + ./gradlew clean build publishToMavenLocal + ``` +7. Publish the generated artifacts to the local Ballerina central repository: + ``` + ./gradlew clean build -PpublishToLocalCentral=true + ``` +8. Publish the generated artifacts to the Ballerina central repository: + ``` + ./gradlew clean build -PpublishToCentral=true + ``` + +## Contribute to Ballerina + +As an open source project, Ballerina welcomes contributions from the community. + +For more information, go to the [contribution guidelines](https://github.com/ballerina-platform/ballerina-lang/blob/master/CONTRIBUTING.md). + +## Code of conduct + +All the contributors are encouraged to read the [Ballerina Code of Conduct](https://ballerina.io/code-of-conduct). + +## Useful links + +* For more information go to the [`java.jms` library](https://lib.ballerina.io/ballerinax/java.jms/latest). +* For example demonstrations of the usage, go to [Ballerina By Examples](https://ballerina.io/learn/by-example/). +* Chat live with us via our [Discord server](https://discord.gg/ballerinalang). +* Post all technical questions on Stack Overflow with the [#ballerina](https://stackoverflow.com/questions/tagged/ballerina) tag. diff --git a/ballerina/Ballerina.toml b/ballerina/Ballerina.toml new file mode 100644 index 00000000..30031356 --- /dev/null +++ b/ballerina/Ballerina.toml @@ -0,0 +1,28 @@ +[package] +org = "ballerinax" +name = "java.jms" +version = "0.0.1" +authors = ["Ballerina"] +keywords = ["jms"] +repository = "https://github.com/ballerina-platform/module-ballerina-java.jms" +icon = "icon.png" +license = ["Apache-2.0"] +distribution = "2201.6.0" + +[[platform.java11.dependency]] +groupId = "io.ballerina.stdlib" +artifactId = "java.jms-native" +version = "0.0.1" +path = "../native/build/libs/java.jms-native-0.0.1-SNAPSHOT.jar" + +[[platform.java11.dependency]] +groupId = "org.slf4j" +artifactId = "slf4j-api" +version = "2.0.7" +path = "./lib/slf4j-api-2.0.7.jar" + +[[platform.java11.dependency]] +groupId = "javax.jms" +artifactId = "javax.jms-api" +version = "2.0.1" +path = "./lib/javax.jms-api-2.0.1.jar" diff --git a/ballerina/Dependencies.toml b/ballerina/Dependencies.toml new file mode 100644 index 00000000..23381a4e --- /dev/null +++ b/ballerina/Dependencies.toml @@ -0,0 +1,68 @@ +# AUTO-GENERATED FILE. DO NOT MODIFY. + +# This file is auto-generated by Ballerina for managing dependency versions. +# It should not be modified by hand. + +[ballerina] +dependencies-toml-version = "2" +distribution-version = "2201.6.0" + +[[package]] +org = "ballerina" +name = "io" +version = "1.4.1" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.value"} +] + +[[package]] +org = "ballerina" +name = "jballerina.java" +version = "0.0.0" +modules = [ + {org = "ballerina", packageName = "jballerina.java", moduleName = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "lang.value" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "log" +version = "2.7.1" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.value"}, + {org = "ballerina", name = "observe"} +] +modules = [ + {org = "ballerina", packageName = "log", moduleName = "log"} +] + +[[package]] +org = "ballerina" +name = "observe" +version = "1.0.7" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerinax" +name = "java.jms" +version = "0.0.1" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "log"} +] +modules = [ + {org = "ballerinax", packageName = "java.jms", moduleName = "java.jms"} +] + diff --git a/ballerina/Module.md b/ballerina/Module.md new file mode 100644 index 00000000..2ec2142e --- /dev/null +++ b/ballerina/Module.md @@ -0,0 +1,120 @@ +## Overview + +The `ballerina/java.jms` module provides an API to connect to an external JMS provider like ActiveMQ from Ballerina. + +This module is created with minimal deviation from the JMS API to make it easy for the developers who are used to working + with the JMS API. This module is written to support both JMS 2.0 and JMS 1.0 API. + +Currently, the following JMS API Classes are supported through this module. + + - Connection + - Session + - Destination (Queue, Topic, TemporaryQueue, TemporaryTopic) + - Message (TextMessage, MapMessage, BytesMessage) + - MessageConsumer + - MessageProducer + + The following sections provide details on how to use the JMS connector. + + - [Samples](#samples) + +## Samples + +### JMS message Producer + +The following Ballerina program sends messages to a queue named *MyQueue*. + +```ballerina +import ballerinax/java.jms; + +public function main() returns error? { + jms:Connection connection = check jms:createConnection({ + initialContextFactory: "org.apache.activemq.jndi.ActiveMQInitialContextFactory", + providerUrl: "tcp://localhost:61616" + }); + jms:Session session = check connection->createSession({acknowledgementMode: "AUTO_ACKNOWLEDGE"}); + jms:Destination queue = check session->createQueue("MyQueue"); + jms:MessageProducer producer = check session.createProducer(queue); + jms:TextMessage msg = { + content: "Hello Ballerina!" + }; + check producer->send(msg); +} +``` + +## JMS message consumer +The following Ballerina program receives messages from a queue named *MyQueue*. +```ballerina +import ballerinax/java.jms; +import ballerina/log; + +public function main() returns error? { + jms:Connection connection = check jms:createConnection({ + initialContextFactory: "org.apache.activemq.jndi.ActiveMQInitialContextFactory", + providerUrl: "tcp://localhost:61616" + }); + jms:Session session = check connection->createSession({acknowledgementMode: "AUTO_ACKNOWLEDGE"}); + jms:Destination queue = check session->createQueue("MyQueue"); + jms:MessageConsumer consumer = check session.createConsumer(queue); + + while true { + jms:Message? response = check consumer->receive(3000); + if response is jms:TextMessage { + log:printInfo("Message received: ", content = response.toString()); + } + } +} +``` + +### Asynchronous message consumer + +One of the key deviations from the JMS API was the asynchronous message consumption using message listeners. In +Ballerina transport listener concept is covered with **service** type, hence we have used the Ballerina service to +implement the message listener. Following is a message listener example listening on a queue named *MyQueue*. + +```ballerina +import ballerina/log; +import ballerinax/java.jms; + +service "consumer-service" on new jms:Listener( + connectionConfig = { + initialContextFactory: "org.apache.activemq.jndi.ActiveMQInitialContextFactory", + providerUrl: "tcp://localhost:61616" + }, + sessionConfig = { + acknowledgementMode: "AUTO_ACKNOWLEDGE" + }, + destination = { + 'type: jms:QUEUE, + name: "MyQueue" + } +) { + remote function onMessage(jms:Message message) returns error? { + if message is jms:TextMessage { + log:printInfo("Text message received", content = message.content); + } + } +} +``` + +## Adding the required dependencies + +Add the required dependencies to the `Ballerina.toml` file based on the broker that you're trying to connect to. +Add the configurations below to run the given examples using `Apache ActiveMQ`. + +``` +[[platform.java11.dependency]] +groupId = "org.apache.activemq" +artifactId = "activemq-client" +version = "5.18.2" + +[[platform.java11.dependency]] +groupId = "org.apache.geronimo.specs" +artifactId = "geronimo-j2ee-management_1.1_spec" +version = "1.0.1" + +[[platform.java11.dependency]] +groupId = "org.fusesource.hawtbuf" +artifactId = "hawtbuf" +version = "1.11" +``` diff --git a/ballerina/Package.md b/ballerina/Package.md new file mode 100644 index 00000000..262635f1 --- /dev/null +++ b/ballerina/Package.md @@ -0,0 +1,119 @@ +## Package overview + +The `ballerina/java.jms` package provides an API to connect to an external JMS provider like ActiveMQ from Ballerina. + +This package is created with minimal deviation from the JMS API to make it easy for the developers who are used to working with the JMS API. This package is written to support both JMS 2.0 and JMS 1.0 API. + +Currently, the following JMS API Classes are supported through this package. + + - Connection + - Session + - Destination (Queue, Topic, TemporaryQueue, TemporaryTopic) + - Message (TextMessage, MapMessage, BytesMessage) + - MessageConsumer + - MessageProducer + + The following sections provide details on how to use the JMS connector. + + - [Samples](#samples) + +## Samples + +### JMS message Producer + +The following Ballerina program sends messages to a queue named *MyQueue*. + +```ballerina +import ballerinax/java.jms; + +public function main() returns error? { + jms:Connection connection = check jms:createConnection({ + initialContextFactory: "org.apache.activemq.jndi.ActiveMQInitialContextFactory", + providerUrl: "tcp://localhost:61616" + }); + jms:Session session = check connection->createSession({acknowledgementMode: "AUTO_ACKNOWLEDGE"}); + jms:Destination queue = check session->createQueue("MyQueue"); + jms:MessageProducer producer = check session.createProducer(queue); + jms:TextMessage msg = { + content: "Hello Ballerina!" + }; + check producer->send(msg); +} +``` + +## JMS message consumer +The following Ballerina program receives messages from a queue named *MyQueue*. +```ballerina +import ballerinax/java.jms; +import ballerina/log; + +public function main() returns error? { + jms:Connection connection = check jms:createConnection({ + initialContextFactory: "org.apache.activemq.jndi.ActiveMQInitialContextFactory", + providerUrl: "tcp://localhost:61616" + }); + jms:Session session = check connection->createSession({acknowledgementMode: "AUTO_ACKNOWLEDGE"}); + jms:Destination queue = check session->createQueue("MyQueue"); + jms:MessageConsumer consumer = check session.createConsumer(queue); + + while true { + jms:Message? response = check consumer->receive(3000); + if response is jms:TextMessage { + log:printInfo("Message received: ", content = response.toString()); + } + } +} +``` + +### Asynchronous message consumer + +One of the key deviations from the JMS API was the asynchronous message consumption using message listeners. In +Ballerina transport listener concept is covered with **service** type, hence we have used the Ballerina service to +implement the message listener. Following is a message listener example listening on a queue named *MyQueue*. + +```ballerina +import ballerina/log; +import ballerinax/java.jms; + +service "consumer-service" on new jms:Listener( + connectionConfig = { + initialContextFactory: "org.apache.activemq.jndi.ActiveMQInitialContextFactory", + providerUrl: "tcp://localhost:61616" + }, + sessionConfig = { + acknowledgementMode: "AUTO_ACKNOWLEDGE" + }, + destination = { + 'type: jms:QUEUE, + name: "MyQueue" + } +) { + remote function onMessage(jms:Message message) returns error? { + if message is jms:TextMessage { + log:printInfo("Text message received", content = message.content); + } + } +} +``` + +## Adding the required dependencies + +Add the required dependencies to the `Ballerina.toml` file based on the broker that you're trying to connect to. +Add the configurations below to run the given examples using `Apache ActiveMQ`. + +``` +[[platform.java11.dependency]] +groupId = "org.apache.activemq" +artifactId = "activemq-client" +version = "5.18.2" + +[[platform.java11.dependency]] +groupId = "org.apache.geronimo.specs" +artifactId = "geronimo-j2ee-management_1.1_spec" +version = "1.0.1" + +[[platform.java11.dependency]] +groupId = "org.fusesource.hawtbuf" +artifactId = "hawtbuf" +version = "1.11" +``` diff --git a/ballerina/build.gradle b/ballerina/build.gradle new file mode 100644 index 00000000..2c404fa4 --- /dev/null +++ b/ballerina/build.gradle @@ -0,0 +1,177 @@ +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import org.apache.tools.ant.taskdefs.condition.Os + +buildscript { + repositories { + maven { + url = 'https://maven.pkg.github.com/ballerina-platform/plugin-gradle' + credentials { + username System.getenv("packageUser") + password System.getenv("packagePAT") + } + } + } + dependencies { + classpath "io.ballerina:plugin-gradle:${project.ballerinaGradlePluginVersion}" + } +} + +description = 'Ballerina - JMS Package' + +def packageName = "java.jms" +def packageOrg = "ballerinax" +def tomlVersion = stripBallerinaExtensionVersion("${project.version}") +def ballerinaTomlFilePlaceHolder = new File("${project.rootDir}/build-config/resources/Ballerina.toml") +def ballerinaTomlFile = new File("$project.projectDir/Ballerina.toml") + +def stripBallerinaExtensionVersion(String extVersion) { + if (extVersion.matches(project.ext.timestampedVersionRegex)) { + def splitVersion = extVersion.split('-') + if (splitVersion.length > 3) { + def strippedValues = splitVersion[0..-4] + return strippedValues.join('-') + } else { + return extVersion + } + } else { + return extVersion.replace("${project.ext.snapshotVersion}", "") + } +} + +apply plugin: 'io.ballerina.plugin' + +ballerina { + packageOrganization = packageOrg + module = packageName + langVersion = ballerinaLangVersion + testCoverageParam = "--code-coverage --coverage-format=xml --includes=io.ballerina.stdlib.*:stdlib.java.jms*" +} + +configurations { + externalJars +} + +dependencies { + /* SLF4J dependencies */ + externalJars(group: 'org.slf4j', name: 'slf4j-api', version: "${slf4jVersion}") { + transitive = false + } + /* JMS dependencies */ + externalJars(group: 'javax.jms', name: 'javax.jms-api', version: "${javaxJmsVersion}") { + transitive = false + } +} + +task updateTomlFiles { + doLast { + def stdlibDependentJavaxJmsVersion = project.javaxJmsVersion + def stdlibDependentSlf4jVersion = project.slf4jVersion + def newConfig = ballerinaTomlFilePlaceHolder.text.replace("@project.version@", project.version) + newConfig = newConfig.replace("@toml.version@", tomlVersion) + newConfig = newConfig.replace("@slf4j.version@", stdlibDependentSlf4jVersion) + newConfig = newConfig.replace("@javax.jms.version@", stdlibDependentJavaxJmsVersion) + ballerinaTomlFile.text = newConfig + } +} + +task commitTomlFiles { + doLast { + project.exec { + ignoreExitValue true + if (Os.isFamily(Os.FAMILY_WINDOWS)) { + commandLine 'cmd', '/c', "git commit -m \"[Automated] Update the native jar versions\" Ballerina.toml Dependencies.toml" + } else { + commandLine 'sh', '-c', "git commit -m '[Automated] Update the native jar versions' Ballerina.toml Dependencies.toml" + } + } + } +} + +//task startMqttServer() { +// doLast { +// if (!Os.isFamily(Os.FAMILY_WINDOWS)) { +// def stdOut = new ByteArrayOutputStream() +// exec { +// commandLine 'sh', '-c', "docker ps --filter name=mqtt-test" +// standardOutput = stdOut +// } +// if (!stdOut.toString().contains("mqtt-test")) { +// println "Starting Mqtt server." +// exec { +// commandLine 'sh', '-c', "docker-compose -f tests/resources/docker-compose.yaml up -d" +// standardOutput = stdOut +// } +// println stdOut.toString() +// sleep(5 * 1000) +// } else { +// println "Mqtt server is already running." +// } +// } +// } +//} +// +//task stopMqttServer() { +// doLast { +// if (!Os.isFamily(Os.FAMILY_WINDOWS)) { +// def stdOut = new ByteArrayOutputStream() +// exec { +// commandLine 'sh', '-c', "docker ps --filter name=mqtt-test" +// standardOutput = stdOut +// } +// if (stdOut.toString().contains("mqtt-test")) { +// println "Stopping Mqtt server." +// exec { +// commandLine 'sh', '-c', "docker-compose -f tests/resources/docker-compose.yaml rm -svf" +// standardOutput = stdOut +// } +// println stdOut.toString() +// sleep(5 * 1000) +// } else { +// println "Mqtt server is not started." +// } +// } +// } +//} + +publishing { + publications { + maven(MavenPublication) { + artifact source: createArtifactZip, extension: 'zip' + } + } + repositories { + maven { + name = "GitHubPackages" + url = uri("https://maven.pkg.github.com/ballerina-platform/module-${packageOrg}-${packageName}") + credentials { + username = System.getenv("publishUser") + password = System.getenv("publishPAT") + } + } + } +} + +updateTomlFiles.dependsOn copyStdlibs + +//test.dependsOn startMqttServer +//build.finalizedBy stopMqttServer + +build.dependsOn ":java.jms-native:build" +build.dependsOn "generatePomFileForMavenPublication" +publishToMavenLocal.dependsOn build +publish.dependsOn build diff --git a/ballerina/caller.bal b/ballerina/caller.bal new file mode 100644 index 00000000..4ad5b5ef --- /dev/null +++ b/ballerina/caller.bal @@ -0,0 +1,27 @@ +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +# Represents a JMS caller, which can be used to commit the offsets consumed by the service. +public isolated client class Caller { + + # Mark a JMS message as received. + # + # + message - JMS message record + # + return - `jms:Error` if there is an error in the execution or else nil + isolated remote function acknowledge(Message message) returns Error? { + return externConsumerAcknowledge(message); + } +} diff --git a/java.jms/src/java.jms/connection.bal b/ballerina/connection.bal similarity index 58% rename from java.jms/src/java.jms/connection.bal rename to ballerina/connection.bal index 7a6d2a4d..7be68105 100644 --- a/java.jms/src/java.jms/connection.bal +++ b/ballerina/connection.bal @@ -1,6 +1,6 @@ -// Copyright (c) 2019 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. // -// WSO2 Inc. licenses this file to you under the Apache License, +// WSO2 LLC. licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except // in compliance with the License. // You may obtain a copy of the License at @@ -14,75 +14,57 @@ // specific language governing permissions and limitations // under the License. -import ballerina/java; +import ballerina/jballerina.java; import ballerina/log; -import ballerina/observe; -# Represents JMS Connection +# Represents JMS Connection. # # + config - Used to store configurations related to a JMS Connection -public type Connection client object { - - public ConnectionConfiguration config = {}; - private handle jmsConnection = JAVA_NULL; +public isolated client class Connection { + public final readonly & ConnectionConfiguration config; + private final handle jmsConnection; # JMS Connection constructor - function init(ConnectionConfiguration c) returns error?{ - self.config = c; - return self.createConnection(); - } - - # Creates a connection with the broker reading the connection configurations. - # - # + return - Return error or nil - function createConnection() returns error? { + public isolated function init(*ConnectionConfiguration connectionConfig) returns error? { + self.config = connectionConfig.cloneReadOnly(); string icf = self.config.initialContextFactory; string providerUrl = self.config.providerUrl; string factoryName = self.config.connectionFactoryName; - - handle|error value = createJmsConnection(icf, providerUrl, factoryName, self.config.properties); - if (value is handle) { - self.jmsConnection = value; - registerAndIncrementCounter(new observe:Counter(TOTAL_JMS_CONNECTIONS)); - log:printDebug("Successfully connected to broker."); - return; - } else { - log:printDebug("Error connecting to broker."); - return value; - } + self.jmsConnection = check createJmsConnection( + icf, providerUrl, factoryName, connectionConfig.properties); } # Create a Session object, specifying transacted and acknowledgeMode # # + sessionConfig - SessionConfiguration record consist with JMS session config # + return - Returns the Session or an error if it fails. - public remote function createSession(SessionConfiguration sessionConfig) returns Session | error { + isolated remote function createSession(SessionConfiguration sessionConfig) returns Session|error { return new Session(self.jmsConnection, sessionConfig); } # Starts (or restarts) a connection's delivery of incoming messages. # A call to start on a connection that has already been started is ignored. - public remote function 'start() { + isolated remote function 'start() { error? err = startJmsConnection(self.jmsConnection); if (err is error) { log:printError("Error starting connection", err); } - + } - + # Temporarily stops a connection's delivery of incoming messages. # Delivery can be restarted using the connection's start method. - public remote function stop() { + isolated remote function stop() { error? err = stopJmsConnection(self.jmsConnection); if (err is error) { log:printError("Error stopping connection", err); } } - function getJmsConnection() returns handle { + isolated function getJmsConnection() returns handle { return self.jmsConnection; } -}; +} # Configurations related to a JMS connection # @@ -101,22 +83,21 @@ public type ConnectionConfiguration record {| map properties = {}; |}; -public function createConnection(ConnectionConfiguration c) returns Connection|error{ +public isolated function createConnection(ConnectionConfiguration c) returns Connection|error{ return new Connection(c); } -function createJmsConnection(string initialContextFactory, string providerUrl, string connectionFactoryName, - map otherPropeties) returns handle | error = @java:Method { - class: "org.ballerinalang.java.jms.JmsConnectionUtils" +isolated function createJmsConnection(string initialContextFactory, string providerUrl, + string connectionFactoryName, map otherPropeties) returns handle|error = @java:Method { + 'class: "io.ballerina.stdlib.java.jms.JmsConnectionUtils" } external; -function startJmsConnection(handle jmsConnection) returns error? = @java:Method { +isolated function startJmsConnection(handle jmsConnection) returns error? = @java:Method { name: "start", - class: "javax.jms.Connection" + 'class: "javax.jms.Connection" } external; - -function stopJmsConnection(handle jmsConnection) returns error? = @java:Method { +isolated function stopJmsConnection(handle jmsConnection) returns error? = @java:Method { name: "stop", - class: "javax.jms.Connection" + 'class: "javax.jms.Connection" } external; diff --git a/java.jms/src/java.jms/destination.bal b/ballerina/destination.bal similarity index 74% rename from java.jms/src/java.jms/destination.bal rename to ballerina/destination.bal index e41516eb..cb9c2d9d 100644 --- a/java.jms/src/java.jms/destination.bal +++ b/ballerina/destination.bal @@ -1,6 +1,6 @@ -// Copyright (c) 2018 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. // -// WSO2 Inc. licenses this file to you under the Apache License, +// WSO2 LLC. licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except // in compliance with the License. // You may obtain a copy of the License at @@ -14,18 +14,15 @@ // specific language governing permissions and limitations // under the License. -import ballerina/java; +import ballerina/jballerina.java; # Represent the JMS destination -public type Destination abstract object { - - handle jmsDestination; - - function getJmsDestination() returns handle; - +public type Destination distinct object { + + isolated function getJmsDestination() returns handle; }; -function getDestination(handle jmsDestination) returns Destination | error { +function getDestination(handle jmsDestination) returns Destination|error { handle jmsDestinationType = getDestinationType(jmsDestination); string? destinationType = java:toString(jmsDestinationType); match destinationType { @@ -42,10 +39,9 @@ function getDestination(handle jmsDestination) returns Destination | error { return new TemporaryTopic(jmsDestination); } } - JmsError err = JmsError("Invalid destination type"); - return err; + return error Error("Invalid destination type"); } function getDestinationType(handle destination) returns handle = @java:Method { - class: "org.ballerinalang.java.jms.JmsDestinationUtils" + 'class: "io.ballerina.stdlib.java.jms.JmsDestinationUtils" } external; diff --git a/java.jms/src/java.jms/error.bal b/ballerina/errors.bal similarity index 71% rename from java.jms/src/java.jms/error.bal rename to ballerina/errors.bal index fe9ed3ee..7829d90f 100644 --- a/java.jms/src/java.jms/error.bal +++ b/ballerina/errors.bal @@ -1,6 +1,6 @@ -// Copyright (c) 2018 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. // -// WSO2 Inc. licenses this file to you under the Apache License, +// WSO2 LLC. licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except // in compliance with the License. // You may obtain a copy of the License at @@ -14,4 +14,5 @@ // specific language governing permissions and limitations // under the License. -public type JmsError distinct error; +# Represents a JMS distinct error. +public type Error distinct error; diff --git a/ballerina/icon.png b/ballerina/icon.png new file mode 100644 index 00000000..691abf50 Binary files /dev/null and b/ballerina/icon.png differ diff --git a/ballerina/init.bal b/ballerina/init.bal new file mode 100644 index 00000000..6a3f90fd --- /dev/null +++ b/ballerina/init.bal @@ -0,0 +1,25 @@ +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import ballerina/jballerina.java; + +isolated function init() { + setModule(); +} + +isolated function setModule() = @java:Method { + 'class: "io.ballerina.stdlib.java.jms.ModuleUtils" +} external; diff --git a/java.jms/src/java.jms/jms_commons.bal b/ballerina/jms_commons.bal similarity index 70% rename from java.jms/src/java.jms/jms_commons.bal rename to ballerina/jms_commons.bal index e1b76b9e..9b98cb6f 100644 --- a/java.jms/src/java.jms/jms_commons.bal +++ b/ballerina/jms_commons.bal @@ -1,6 +1,6 @@ -// Copyright (c) 2019 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. // -// WSO2 Inc. licenses this file to you under the Apache License, +// WSO2 LLC. licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except // in compliance with the License. // You may obtain a copy of the License at @@ -14,6 +14,6 @@ // specific language governing permissions and limitations // under the License. -import ballerina/java; +import ballerina/jballerina.java; -handle JAVA_NULL = java:createNull(); +final handle JAVA_NULL = java:createNull(); diff --git a/ballerina/message.bal b/ballerina/message.bal new file mode 100644 index 00000000..ce2825d4 --- /dev/null +++ b/ballerina/message.bal @@ -0,0 +1,101 @@ +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import ballerina/jballerina.java; + +# Represent the JMS Message used to send and receive content from the a JMS provider. +# +# + messageId - Unique identifier for a JMS message +# + timestamp - Time a message was handed off to a provider to be sent +# + correlationId - Id which can be use to correlate multiple messages +# + replyTo - JMS destination to which a reply to this message should be sent +# + destination - JMS destination of this message +# + deliveryMode - Delivery mode of this message +# + redelivered - Indication of whether this message is being redelivered +# + jmsType - Message type identifier supplied by the client when the message was sent +# + expiration - Message expiration time +# + deliveredTime - The earliest time when a JMS provider may deliver the message to a consumer +# + priority - Message priority level +# + properties - Additional message properties +public type Message record { + string messageId?; + int timestamp?; + string correlationId?; + record {| + JmsDestinationType 'type; + string name?; + |} replyTo?; + record {| + JmsDestinationType 'type; + string name?; + |} destination?; + int deliveryMode?; + boolean redelivered?; + string jmsType?; + int expiration?; + int deliveredTime?; + int priority?; + map properties?; +}; + +# Represent the JMS Text Message. +# +# + content - Message content +public type TextMessage record {| + *Message; + string content; +|}; + +# Represent the JMS Map Message. +# +# + content - Message content +public type MapMessage record {| + *Message; + map content; +|}; + +# Represent the JMS Bytes Message. +# +# + content - Message content +public type BytesMessage record {| + *Message; + byte[] content; +|}; + +isolated function externWriteBytes(handle message, byte[] value) returns error? = @java:Method { + name: "writeBytes", + 'class: "io.ballerina.stdlib.java.jms.JmsBytesMessageUtils" +} external; + +isolated function externSetBoolean(handle message, handle name, boolean value) returns error? = @java:Method { + name: "setBoolean", + 'class: "javax.jms.MapMessage" +} external; + +isolated function externSetDouble(handle message, handle name, float value) returns error? = @java:Method { + name: "setDouble", + 'class: "javax.jms.MapMessage" +} external; + +isolated function externSetLong(handle message, handle name, int value) returns error? = @java:Method { + name: "setLong", + 'class: "javax.jms.MapMessage" +} external; + +isolated function externSetString(handle message, handle name, handle value) returns error? = @java:Method { + name: "setString", + 'class: "javax.jms.MapMessage" +} external; diff --git a/ballerina/message_consumer.bal b/ballerina/message_consumer.bal new file mode 100644 index 00000000..241f41c3 --- /dev/null +++ b/ballerina/message_consumer.bal @@ -0,0 +1,86 @@ +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import ballerina/jballerina.java; + +# JMS Message Consumer client object to receive messages from both queues and topics. +public isolated client class MessageConsumer { + private final handle jmsConsumer; + + # Initialize the Message Consumer client object. + # + # + jmsProducer - reference to java MessageConsumer object + isolated function init(handle jmsMessageConsumer) { + self.jmsConsumer = jmsMessageConsumer; + } + + # Receives the next message that arrives within the specified timeout interval. + # + # + timeoutMillis - Message receive timeout + # + return - `jms:JmsMessage` or `jsm:Error` if there is an error in the execution + isolated remote function receive(int timeoutMillis = 0) returns Message|Error? { + return externReceive(self.jmsConsumer, timeoutMillis); + }; + + # Receives the next message if one is immediately available. + # + # + return - `jms:JmsMessage` or `jsm:Error` if there is an error in the execution + isolated remote function receiveNoWait() returns Message|Error? { + return externReceiveNoWait(self.jmsConsumer); + } + + # Mark a JMS message as received. + # + # + message - JMS message record + # + return - `jms:Error` if there is an error in the execution or else nil + isolated remote function acknowledge(Message message) returns Error? { + return externConsumerAcknowledge(message); + } + + # Closes the message consumer. + # + # + return - `jms:Error` if there is an error or else nil + isolated remote function close() returns Error? { + error? result = externClose(self.jmsConsumer); + if result is error { + return error Error(result.message()); + } + } + + isolated function getJmsConsumer() returns handle { + return self.jmsConsumer; + } +} + +isolated function externReceive(handle jmsMessageConsumer, int timeout) returns Message|Error? = @java:Method { + name: "receive", + 'class: "io.ballerina.stdlib.java.jms.ConsumerUtils" +} external; + +isolated function externReceiveNoWait(handle jmsMessageConsumer) returns Message|Error? = @java:Method { + name: "receiveNoWait", + 'class: "io.ballerina.stdlib.java.jms.ConsumerUtils" +} external; + +isolated function externConsumerAcknowledge(Message message) returns Error? = @java:Method { + name: "acknowledge", + 'class: "io.ballerina.stdlib.java.jms.ConsumerUtils" +} external; + +isolated function externClose(handle jmsConsumer) returns error? = @java:Method { + name: "close", + 'class: "javax.jms.MessageConsumer" +} external; diff --git a/ballerina/message_listener.bal b/ballerina/message_listener.bal new file mode 100644 index 00000000..1bc3e164 --- /dev/null +++ b/ballerina/message_listener.bal @@ -0,0 +1,153 @@ +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import ballerina/jballerina.java; +import ballerina/log; + +# The JMS service type. +public type Service distinct service object { + // remote function onMessage(jms:Message message, jms:Caller caller) returns error?; +}; + +# Defines the supported JMS destinations. +public enum JmsDestinationType { + # Represents JMS Queue + QUEUE = "QUEUE", + # Represents JMS Temporary Queue + TEMPORARY_QUEUE = "TEMPORARY_QUEUE", + # Represents JMS Topic + TOPIC = "TOPIC", + # Represents JMS Temporary Topic + TEMPORARY_TOPIC = "TEMPORARY_TOPIC" +} + +# Message consumer configurations. +# +# + connectionConfig - Configurations related to the broker connection +# + sessionConfig - Configurations related to the JMS session +# + destination - Name of the JMS destination +# + messageSelector - only messages with properties matching the message selector expression are added to the durable subscription. +# An empty string indicates that there is no message selector for the durable subscription. +# + noLocal - if true then any messages published to the topic using this session's connection, or any other connection +# with the same client identifier, will not be added to the durable subscription. +public type ConsumerConfiguration record {| + ConnectionConfiguration connectionConfig; + SessionConfiguration sessionConfig; + record {| + JmsDestinationType 'type; + string name?; + |} destination; + string messageSelector = ""; + boolean noLocal = false; +|}; + +# Represents a JMS consumer listener. +public isolated class Listener { + private final MessageConsumer consumer; + + # Creates a new `jms:Listener`. + # + # + consumer - The relevant JMS consumer. + public isolated function init(*ConsumerConfiguration consumerConfig) returns error? { + Connection connection = check new (consumerConfig.connectionConfig); + Session session = check connection->createSession(consumerConfig.sessionConfig); + Destination destination = check createJmsDestination( + session, consumerConfig.destination.'type, consumerConfig.destination?.name); + self.consumer = check session.createConsumer( + destination, consumerConfig.messageSelector, consumerConfig.noLocal); + } + + # Attaches a message consumer service to a listener. + # ```ballerina + # error? result = listener.attach(jmsService); + # ``` + # + # + 'service - The service instance. + # + name - Name of the service. + # + return - Returns nil or an error upon failure to register the listener. + public isolated function attach(Service 'service, string[]|string? name = ()) returns Error? { + return setMessageListener(self.consumer.getJmsConsumer(), 'service); + } + + # Detaches a message consumer service from the the listener. + # ```ballerina + # error? result = listener.detach(jmsService); + # ``` + # + # + 'service - The service to be detached + # + return - A `kafka:Error` if an error is encountered while detaching a service or else `()` + public isolated function detach(Service 'service) returns Error? {} + + # Starts the endpoint. + # + # + return - Returns nil or an error upon failure to start. + public isolated function 'start() returns Error? {} + + + # Stops the JMS listener gracefully. + # ```ballerina + # error? result = listener.gracefulStop(); + # ``` + # + # + return - A `jms:JmsError` if an error is encountered during the listener-stopping process or else `()` + public isolated function gracefulStop() returns Error? { + return self.consumer->close(); + } + + # Stops the JMS listener immediately. + # ```ballerina + # error? result = listener.immediateStop(); + # ``` + # + # + return - A `jms:JmsError` if an error is encountered during the listener-stopping process or else `()` + public isolated function immediateStop() returns Error? { + return self.consumer->close(); + } +} + +isolated function createJmsDestination(Session session, JmsDestinationType 'type, string? name) returns Destination|error { + if 'type is TEMPORARY_QUEUE || 'type is TEMPORARY_TOPIC { + if name is string { + log:printWarn("Temporary JSM destinations does not support naming"); + } + } + if 'type is QUEUE || 'type is TOPIC { + if name is () { + return error ("JMS destination name can not be empty"); + } + } + match 'type { + QUEUE => { + return session->createQueue( name); + } + TEMPORARY_QUEUE => { + return session->createTemporaryQueue(); + } + TOPIC => { + return session->createTopic( name); + } + TEMPORARY_TOPIC => { + return session->createTemporaryTopic(); + } + _ => { + return error (string `Unidentified JSM destination type: ${'type}`); + } + } +} + +isolated function setMessageListener(handle jmsConsumer, Service 'service) returns Error? = @java:Method { + 'class: "io.ballerina.stdlib.java.jms.JmsMessageListenerUtils" +} external; diff --git a/ballerina/message_producer.bal b/ballerina/message_producer.bal new file mode 100644 index 00000000..a5340515 --- /dev/null +++ b/ballerina/message_producer.bal @@ -0,0 +1,92 @@ +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import ballerina/jballerina.java; + +# JMS Message Producer client object to send messages to both queues and topics. +public isolated client class MessageProducer { + private final handle jmsProducer; + private final handle jmsSession; + + # Initialize the Message Producer client object + # + # + jmsProducer - reference to java MessageProducer object + isolated function init(handle jmsProducer, handle session) returns error? { + self.jmsProducer = jmsProducer; + self.jmsSession = session; + } + + # Sends a message to the JMS provider + # + # + message - Message to be sent to the JMS provider + # + return - Error if unable to send the message to the queue + isolated remote function send(Message message) returns error? { + handle jmsMessage = check getJmsMessage(self.jmsSession, message); + return externSend(self.jmsProducer, jmsMessage); + } + + # Sends a message to a given destination of the JMS provider + # + # + destination - Destination used for the message sender + # + message - Message to be sent to the JMS provider + # + return - Error if sending to the given destination fails + isolated remote function sendTo(Destination destination, Message message) returns error? { + handle jmsMessage = check getJmsMessage(self.jmsSession, message); + return externSendTo(self.jmsProducer, destination.getJmsDestination(), jmsMessage); + } +}; + +isolated function getJmsMessage(handle session, Message message) returns handle|error { + if message is TextMessage { + return createJmsTextMessageWithText(session, java:fromString(message.content)); + } else if message is BytesMessage { + handle jmsMessage = check createJmsBytesMessage(session); + check externWriteBytes(jmsMessage, message.content); + return jmsMessage; + } else if message is MapMessage { + handle jmsMessage = check createJmsMapMessage(session); + check populateMapMessage(jmsMessage, message.content); + return jmsMessage; + } + return error ("Unidentified message type"); +} + +isolated function populateMapMessage(handle mapMessage, map keyValues) returns error? { + foreach string 'key in keyValues.keys() { + var value = keyValues.get('key); + if value is int { + check externSetLong(mapMessage, java:fromString('key), value); + } else if value is float { + check externSetDouble(mapMessage, java:fromString('key), value); + } else if value is boolean { + check externSetBoolean(mapMessage, java:fromString('key), value); + } else if value is string { + check externSetString(mapMessage, java:fromString('key), java:fromString(value)); + } + } +} + +isolated function externSend(handle messageProducer, handle message) returns error? = @java:Method { + name: "send", + paramTypes: ["javax.jms.Message"], + 'class: "javax.jms.MessageProducer" +} external; + +isolated function externSendTo(handle messageProducer, handle destination, handle message) returns error? = @java:Method { + name: "send", + paramTypes: ["javax.jms.Destination", "javax.jms.Message"], + 'class: "javax.jms.MessageProducer" +} external; diff --git a/java.jms/src/java.jms/queue.bal b/ballerina/queue.bal similarity index 56% rename from java.jms/src/java.jms/queue.bal rename to ballerina/queue.bal index cba98f8a..1f1266f0 100644 --- a/java.jms/src/java.jms/queue.bal +++ b/ballerina/queue.bal @@ -1,6 +1,6 @@ -// Copyright (c) 2019 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. // -// WSO2 Inc. licenses this file to you under the Apache License, +// WSO2 LLC. licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except // in compliance with the License. // You may obtain a copy of the License at @@ -14,42 +14,37 @@ // specific language governing permissions and limitations // under the License. -import ballerina/java; +import ballerina/jballerina.java; -# Represent the JMS queue -public type Queue object { - - // Add a reference to the `Destination` object type. +# Represent the JMS queue. +public isolated class Queue { *Destination; + + private final handle jmsDestination; # Initialized a `Queue` object. # # + handle - The java reference to the jms text message. - function init(handle queue) { + isolated function init(handle queue) { self.jmsDestination = queue; } # Get the JMS queue # # + return - Returns the java reference to the jms queue - function getJmsDestination() returns handle { + isolated function getJmsDestination() returns handle { return self.jmsDestination; } # Gets the name of this queue. # # + return - Returns the string value or an error if it fails. - public function getQueueName() returns string | error? { - handle|error val = getQueueName(self.jmsDestination); - if (val is handle) { - return java:toString(val); - } else { - return val; - } + public isolated function getQueueName() returns string|error? { + handle queue = check getQueueName(self.jmsDestination); + return java:toString(queue); } +} -}; - -function getQueueName(handle destination) returns handle | error = @java:Method { - class: "javax.jms.Queue" -} external; \ No newline at end of file +isolated function getQueueName(handle destination) returns handle|error = @java:Method { + 'class: "javax.jms.Queue" +} external; diff --git a/java.jms/src/java.jms/resources/.keep b/ballerina/resources/.keep similarity index 100% rename from java.jms/src/java.jms/resources/.keep rename to ballerina/resources/.keep diff --git a/ballerina/session.bal b/ballerina/session.bal new file mode 100644 index 00000000..fdb62226 --- /dev/null +++ b/ballerina/session.bal @@ -0,0 +1,287 @@ +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import ballerina/log; +import ballerina/jballerina.java; + +# Represents the JMS session. +# +# + config - Stores the configurations related to a JMS session. +public isolated client class Session { + private final readonly & SessionConfiguration config; + private final handle jmsSession; + +# The default constructor of the JMS session. + public isolated function init(handle jmsConnection, SessionConfiguration sessionConfig) returns error? { + self.config = sessionConfig.cloneReadOnly(); + handle ackModeJString = java:fromString(self.config.acknowledgementMode); + self.jmsSession = check createJmsSession(jmsConnection, ackModeJString); + } + + # Unsubscribe a durable subscription that has been created by a client. + # It is erroneous for a client to delete a durable subscription while there is an active (not closed) consumer + # for the subscription, or while a consumed message being part of a pending transaction or has not been + # acknowledged in the session. + # + # + subscriptionId - The name, which is used to identify the subscription. + # + return - Cancels the subscription. + isolated remote function unsubscribe(string subscriptionId) returns error? { + return unsubscribeJmsSubscription(self.jmsSession, java:fromString(subscriptionId)); + } + + # Creates a JMS Queue, which can be used as temporary response destination. + # + # + return - Returns the JMS destination for a temporary queue or an error if it fails. + isolated remote function createTemporaryQueue() returns Destination|Error { + handle|error val = createTemporaryJmsQueue(self.jmsSession); + if (val is handle) { + return new TemporaryQueue(val); + } else { + return error Error("Error occurred while creating the JMS queue.", val); + } + } + + # Creates a JMS Topic, which can be used as a temporary response destination. + # + # + return - Returns the JMS destination for a temporary topic or an error if it fails. + isolated remote function createTemporaryTopic() returns Destination|Error { + handle|error val = createTemporaryJmsTopic(self.jmsSession); + if (val is handle) { + return new TemporaryTopic(val); + } else { + return error Error("Error occurred while creating the JMS topic.", val); + } + } + + # Creates a JMS Queue, which can be used with a message producer. + # + # + queueName - The name of the Queue. + # + return - Returns the JMS destination for a queue or an error if it fails. + isolated remote function createQueue(string queueName) returns Destination|error { + handle|error val = createJmsQueue(self.jmsSession, java:fromString(queueName)); + if (val is handle) { + return new Queue(val); + } else { + return val; + } + } + + # Creates a JMS Topic, which can be used with a message producer. + # + # + topicName - The name of the Topic. + # + return - Returns the JMS destination for a topic or an error if it fails. + isolated remote function createTopic(string topicName) returns Destination|error { + handle|error val = createJmsTopic(self.jmsSession, java:fromString(topicName)); + if (val is handle) { + return new Topic(val); + } else { + return val; + } + } + + # Get the reference to the java session object. + # + # + return - Returns jms session java reference. + function getJmsSession() returns handle { + return self.jmsSession; + } + + # Creates a MessageProducer to send messages to the specified destination. + # + # + destination - the Destination to send to, or nil if this is a producer which does not have a specified destination + # + return - Returns jms:MessageProducer + public isolated function createProducer(Destination? destination = ()) returns MessageProducer|error { + handle jmsDestination = (destination is Destination) ? destination.getJmsDestination() : JAVA_NULL; + handle|error v = createJmsProducer(self.jmsSession, jmsDestination); + if (v is handle) { + return new MessageProducer(v, self.jmsSession); + } else { + log:printError("Error occurred while creating producer"); + return v; + } + } + + # Creates a MessageConsumer for the specified destination. Both Queue and Topic can be used in + # the destination parameter to create a MessageConsumer. + # + # + destination - the Destination to access + # + messageSelector - only messages with properties matching the message selector expression are delivered. + # An empty string indicates that there is no message selector for the message consumer. + # + noLocal - if true, and the destination is a topic, then the MessageConsumer will not receive messages published to the topic by its own connection. + # + return - Returns a jms:MessageConsumer + public isolated function createConsumer(Destination destination, + string messageSelector = "", boolean noLocal = false) returns MessageConsumer|error { + var val = createJmsConsumer( + self.jmsSession, destination.getJmsDestination(), + java:fromString(messageSelector), noLocal); + if (val is handle) { + MessageConsumer consumer = new (val); + return consumer; + } else { + return val; + } + } + + # Creates an unshared durable subscription on the specified topic (if one does not already exist), + # specifying a message selector and the noLocal parameter, and creates a consumer on that durable subscription. + # + # + topic - the non-temporary Topic to subscribe to + # + subscriberName - the name used to identify this subscription + # + messageSelector - only messages with properties matching the message selector expression are added to the durable subscription. + # An empty string indicates that there is no message selector for the durable subscription. + # + noLocal - if true then any messages published to the topic using this session's connection, or any other connection + # with the same client identifier, will not be added to the durable subscription. + # + return - Returns a jms:MessageConsumer + public isolated function createDurableSubscriber(Destination topic, string subscriberName, + string messageSelector = "", boolean noLocal = false) returns MessageConsumer|error { + var val = createJmsDurableSubscriber( + self.jmsSession, topic.getJmsDestination(), + java:fromString(subscriberName), java:fromString(messageSelector), noLocal); + if (val is handle) { + MessageConsumer consumer = new (val); + return consumer; + } else { + return val; + } + } + + # Creates a shared non-durable subscription with the specified name on the specified topic + # (if one does not already exist) specifying a message selector, and creates a consumer on that subscription. + # + # + topic - the Topic to subscribe to + # + subscriberName - the name used to identify the shared non-durable subscription + # + messageSelector - only messages with properties matching the message selector expression are added to the shared + # non-durable subscription. A value of null or an empty string indicates that there is no message + # selector for the shared non-durable subscription. + # + return - Returns a jms:MessageConsumer + public isolated function createSharedConsumer(Destination topic, string subscriberName, + string messageSelector = "") returns MessageConsumer|error { + var val = createJmsSharedConsumer( + self.jmsSession, topic.getJmsDestination(), + java:fromString(subscriberName), java:fromString(messageSelector)); + if (val is handle) { + MessageConsumer consumer = new (val); + return consumer; + } else { + return val; + } + } + + # Creates a shared durable subscription on the specified topic (if one does not already exist), + # specifying a message selector, and creates a consumer on that durable subscription. + # + # + topic - the non-temporary Topic to subscribe to + # + subscriberName - the name used to identify this subscription + # + messageSelector - only messages with properties matching the message selector expression are added to the durable subscription. + # A value of null or an empty string indicates that there is no message selector for the durable subscription. + # + return - Returns a jms:MessageConsumer + public isolated function createSharedDurableConsumer(Destination topic, string subscriberName, + string messageSelector = "") returns MessageConsumer|error { + var val = createJmsSharedDurableConsumer( + self.jmsSession, topic.getJmsDestination(), + java:fromString(subscriberName), java:fromString(messageSelector)); + if (val is handle) { + MessageConsumer consumer = new (val); + return consumer; + } else { + return val; + } + } +} + +# The Configurations that are related to a JMS session. +# +# + acknowledgementMode - Specifies the session mode that will be used. Valid values are "AUTO_ACKNOWLEDGE", +# "CLIENT_ACKNOWLEDGE", "SESSION_TRANSACTED", and "DUPS_OK_ACKNOWLEDGE". +public type SessionConfiguration record {| + string acknowledgementMode = "AUTO_ACKNOWLEDGE"; +|}; + +isolated function createJmsTextMessageWithText(handle session, handle text) returns handle|error = @java:Method { + name: "createTextMessage", + paramTypes: ["java.lang.String"], + 'class: "javax.jms.Session" +} external; + +isolated function createJmsMapMessage(handle session) returns handle|error = @java:Method { + name: "createMapMessage", + 'class: "javax.jms.Session" +} external; + +isolated function createJmsBytesMessage(handle session) returns handle|error = @java:Method { + name: "createBytesMessage", + 'class: "javax.jms.Session" +} external; + +isolated function createJmsConsumer(handle jmsSession, handle jmsDestination, + handle selectorString, boolean noLocal) returns handle|error = @java:Method { + name: "createConsumer", + paramTypes: ["javax.jms.Destination", "java.lang.String", "boolean"], + 'class: "javax.jms.Session" +} external; + +isolated function createJmsSession(handle connection, handle acknowledgmentMode) returns handle|error = @java:Method { + 'class: "io.ballerina.stdlib.java.jms.JmsSessionUtils" +} external; + +isolated function unsubscribeJmsSubscription(handle session, handle subscriptionId) returns error? = @java:Method { + name: "unsubscribe", + 'class: "javax.jms.Session" +} external; + +isolated function createJmsProducer(handle session, handle jmsDestination) returns handle|error = @java:Method { + name: "createProducer", + 'class: "javax.jms.Session" +} external; + +isolated function createJmsDurableSubscriber(handle jmsSession, handle subscriberName, handle jmsDestination, + handle selectorString, boolean noLocal) returns handle|error = @java:Method { + name: "createDurableSubscriber", + paramTypes: ["javax.jms.Topic", "java.lang.String", "java.lang.String", "boolean"], + 'class: "javax.jms.Session" +} external; + +isolated function createJmsSharedConsumer(handle jmsSession, handle subscriberName, handle jmsDestination, + handle selectorString) returns handle|error = @java:Method { + name: "createSharedConsumer", + paramTypes: ["javax.jms.Topic", "java.lang.String", "java.lang.String"], + 'class: "javax.jms.Session" +} external; + +isolated function createJmsSharedDurableConsumer(handle jmsSession, handle subscriberName, handle jmsDestination, + handle selectorString) returns handle|error = @java:Method { + name: "createSharedDurableConsumer", + paramTypes: ["javax.jms.Topic", "java.lang.String", "java.lang.String"], + 'class: "javax.jms.Session" +} external; + +isolated function createJmsQueue(handle session, handle queueName) returns handle|error = @java:Method { + name: "createQueue", + 'class: "javax.jms.Session" +} external; + +isolated function createJmsTopic(handle session, handle topicName) returns handle|error = @java:Method { + name: "createTopic", + 'class: "javax.jms.Session" +} external; + +isolated function createTemporaryJmsQueue(handle session) returns handle|error = @java:Method { + 'class: "io.ballerina.stdlib.java.jms.JmsSessionUtils" +} external; + +isolated function createTemporaryJmsTopic(handle session) returns handle|error = @java:Method { + 'class: "io.ballerina.stdlib.java.jms.JmsSessionUtils" +} external; diff --git a/java.jms/src/java.jms/temporary_queue.bal b/ballerina/temporary_queue.bal similarity index 61% rename from java.jms/src/java.jms/temporary_queue.bal rename to ballerina/temporary_queue.bal index 83d4e037..671a7b71 100644 --- a/java.jms/src/java.jms/temporary_queue.bal +++ b/ballerina/temporary_queue.bal @@ -1,6 +1,6 @@ -// Copyright (c) 2019 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. // -// WSO2 Inc. licenses this file to you under the Apache License, +// WSO2 LLC. licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except // in compliance with the License. // You may obtain a copy of the License at @@ -14,36 +14,32 @@ // specific language governing permissions and limitations // under the License. -import ballerina/java; -import ballerina/observe; +import ballerina/jballerina.java; -observe:Gauge temporaryQueueGauge = new(ACTIVE_JMS_TEMPORARY_QUEUES); - -# Represent the JMS temporary queue -public type TemporaryQueue object { - - // Add a reference to the `Destination` object type. +# Represent the JMS temporary queue. +public isolated class TemporaryQueue { *Destination; - + + private final handle jmsDestination; + # Initialized a `TemporaryQueue` object. # # + handle - The java reference to the jms text message. - function init(handle temporaryQueue) { - registerAndIncrementGauge(temporaryQueueGauge); + isolated function init(handle temporaryQueue) { self.jmsDestination = temporaryQueue; } # Get the JMS temporary queue # # + return - Returns the java reference to the jms temporary queue - function getJmsDestination() returns handle { + isolated function getJmsDestination() returns handle { return self.jmsDestination; } # Gets the name of this temporary queue. # # + return - Returns the string value or an error if it fails. - public function getQueueName() returns string | error? { + public isolated function getQueueName() returns string | error? { handle|error val = getQueueName(self.jmsDestination); if (val is handle) { return java:toString(val); @@ -55,14 +51,12 @@ public type TemporaryQueue object { # Deletes this temporary queue. # # + return - Returns an error if it fails. - public function delete() returns error? { - decrementGauge(temporaryQueueGauge); + public isolated function delete() returns error? { return deleteTemporaryQueue(self.jmsDestination); } +} -}; - -function deleteTemporaryQueue(handle destination) returns error? = @java:Method { +isolated function deleteTemporaryQueue(handle destination) returns error? = @java:Method { name: "delete", - class: "javax.jms.TemporaryQueue" -} external; \ No newline at end of file + 'class: "javax.jms.TemporaryQueue" +} external; diff --git a/java.jms/src/java.jms/temporary_topic.bal b/ballerina/temporary_topic.bal similarity index 62% rename from java.jms/src/java.jms/temporary_topic.bal rename to ballerina/temporary_topic.bal index bf728c2e..d96da2de 100644 --- a/java.jms/src/java.jms/temporary_topic.bal +++ b/ballerina/temporary_topic.bal @@ -1,6 +1,6 @@ -// Copyright (c) 2019 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. // -// WSO2 Inc. licenses this file to you under the Apache License, +// WSO2 LLC. licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except // in compliance with the License. // You may obtain a copy of the License at @@ -14,36 +14,32 @@ // specific language governing permissions and limitations // under the License. -import ballerina/java; -import ballerina/observe; +import ballerina/jballerina.java; -observe:Gauge temporaryTopicGauge = new(ACTIVE_JMS_TEMPORARY_TOPICS); - -# Represent the JMS temporary topic -public type TemporaryTopic object { - - // Add a reference to the `Destination` object type. +# Represent the JMS temporary topic. +public isolated class TemporaryTopic { *Destination; + private final handle jmsDestination; + # Initialized a `TemporaryTopic` object. # # + handle - The java reference to the jms text message. - function init(handle temporaryTopic) { - registerAndIncrementGauge(temporaryTopicGauge); + isolated function init(handle temporaryTopic) { self.jmsDestination = temporaryTopic; } # Get the JMS temporary topic # # + return - Returns the java reference to the jms temporary topic - function getJmsDestination() returns handle { + isolated function getJmsDestination() returns handle { return self.jmsDestination; } # Gets the name of this temporary topic. # # + return - Returns the string value or an error if it fails. - public function getTopicName() returns string | error? { + public isolated function getTopicName() returns string|error? { handle|error val = getTopicName(self.jmsDestination); if (val is handle) { return java:toString(val); @@ -55,14 +51,12 @@ public type TemporaryTopic object { # Deletes this temporary topic. # # + return - Returns an error if it fails. - public function delete() returns error? { - decrementGauge(temporaryTopicGauge); + public isolated function delete() returns error? { return deleteTemporaryTopic(self.jmsDestination); } +} -}; - -function deleteTemporaryTopic(handle destination) returns error? = @java:Method { +isolated function deleteTemporaryTopic(handle destination) returns error? = @java:Method { name: "delete", - class: "javax.jms.TemporaryTopic" -} external; \ No newline at end of file + 'class: "javax.jms.TemporaryTopic" +} external; diff --git a/java.jms/src/java.jms/tests/resources/.keep b/ballerina/tests/resources/.keep similarity index 100% rename from java.jms/src/java.jms/tests/resources/.keep rename to ballerina/tests/resources/.keep diff --git a/java.jms/src/java.jms/topic.bal b/ballerina/topic.bal similarity index 56% rename from java.jms/src/java.jms/topic.bal rename to ballerina/topic.bal index 057574ed..c03f2ea3 100644 --- a/java.jms/src/java.jms/topic.bal +++ b/ballerina/topic.bal @@ -1,6 +1,6 @@ -// Copyright (c) 2019 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. // -// WSO2 Inc. licenses this file to you under the Apache License, +// WSO2 LLC. licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except // in compliance with the License. // You may obtain a copy of the License at @@ -14,42 +14,37 @@ // specific language governing permissions and limitations // under the License. -import ballerina/java; +import ballerina/jballerina.java; -# Represent the JMS topic -public type Topic object { - - // Add a reference to the `Destination` object type. +# Represent the JMS topic. +public isolated class Topic { *Destination; + + private final handle jmsDestination; # Initialized a `Topic` object. # # + handle - The java reference to the jms text message. - function init(handle topic) { + isolated function init(handle topic) { self.jmsDestination = topic; } # Get the JMS topic # # + return - Returns the java reference to the jms topic - function getJmsDestination() returns handle { + isolated function getJmsDestination() returns handle { return self.jmsDestination; } # Gets the name of this topic. # # + return - Returns the string value or an error if it fails. - public function getTopicName() returns string | error? { - handle|error val = getTopicName(self.jmsDestination); - if (val is handle) { - return java:toString(val); - } else { - return val; - } + public isolated function getTopicName() returns string|error? { + handle topic = check getTopicName(self.jmsDestination); + return java:toString(topic); } +} -}; - -function getTopicName(handle destination) returns handle | error = @java:Method { - class: "javax.jms.Topic" -} external; \ No newline at end of file +isolated function getTopicName(handle destination) returns handle|error = @java:Method { + 'class: "javax.jms.Topic" +} external; diff --git a/build-config/checkstyle/build.gradle b/build-config/checkstyle/build.gradle new file mode 100644 index 00000000..56359994 --- /dev/null +++ b/build-config/checkstyle/build.gradle @@ -0,0 +1,47 @@ +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +plugins { + id "de.undercouch.download" +} + +apply plugin: 'java' + +task downloadCheckstyleRuleFiles(type: Download) { + src([ + 'https://raw.githubusercontent.com/wso2/code-quality-tools/v1.3/checkstyle/checkstyle.xml', + 'https://raw.githubusercontent.com/wso2/code-quality-tools/v1.3/checkstyle/suppressions.xml' + ]) + overwrite false + onlyIfNewer true + dest buildDir +} + +jar { + enabled = false +} + +clean { + enabled = false +} + +artifacts.add('default', file("$project.buildDir/checkstyle.xml")) { + builtBy('downloadCheckstyleRuleFiles') +} + +artifacts.add('default', file("$project.buildDir/suppressions.xml")) { + builtBy('downloadCheckstyleRuleFiles') +} diff --git a/build-config/resources/Ballerina.toml b/build-config/resources/Ballerina.toml new file mode 100644 index 00000000..afe784e0 --- /dev/null +++ b/build-config/resources/Ballerina.toml @@ -0,0 +1,28 @@ +[package] +org = "ballerinax" +name = "java.jms" +version = "@toml.version@" +authors = ["Ballerina"] +keywords = ["jms"] +repository = "https://github.com/ballerina-platform/module-ballerina-java.jms" +icon = "icon.png" +license = ["Apache-2.0"] +distribution = "2201.6.0" + +[[platform.java11.dependency]] +groupId = "io.ballerina.stdlib" +artifactId = "java.jms-native" +version = "@toml.version@" +path = "../native/build/libs/java.jms-native-@project.version@.jar" + +[[platform.java11.dependency]] +groupId = "org.slf4j" +artifactId = "slf4j-api" +version = "@slf4j.version@" +path = "./lib/slf4j-api-@slf4j.version@.jar" + +[[platform.java11.dependency]] +groupId = "javax.jms" +artifactId = "javax.jms-api" +version = "@javax.jms.version@" +path = "./lib/javax.jms-api-@javax.jms.version@.jar" diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..1706a8e3 --- /dev/null +++ b/build.gradle @@ -0,0 +1,104 @@ +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +plugins { + id "com.github.spotbugs-base" + id "com.github.johnrengelman.shadow" + id "de.undercouch.download" + id "net.researchgate.release" +} + +ext.ballerinaLangVersion = project.ballerinaLangVersion +ext.slf4jVersion = project.slf4jVersion +ext.javaxJmsVersion = project.javaxJmsVersion + +allprojects { + group = project.group + version = project.version + + apply plugin: 'jacoco' + apply plugin: 'maven-publish' + + repositories { + mavenLocal() + + maven { + url = 'https://maven.wso2.org/nexus/content/repositories/releases/' + } + + maven { + url = 'https://maven.wso2.org/nexus/content/groups/wso2-public/' + } + + maven { + url = 'https://repo.maven.apache.org/maven2' + } + + maven { + url = 'https://maven.pkg.github.com/ballerina-platform/*' + credentials { + username System.getenv("packageUser") + password System.getenv("packagePAT") + } + } + } + + ext { + snapshotVersion= '-SNAPSHOT' + timestampedVersionRegex = '.*-\\d{8}-\\d{6}-\\w.*\$' + } +} + +subprojects { + + configurations { + ballerinaStdLibs + } + + dependencies { + /* Standard libraries */ + ballerinaStdLibs "io.ballerina.stdlib:time-ballerina:${stdlibTimeVersion}" + ballerinaStdLibs "io.ballerina.stdlib:log-ballerina:${stdlibLogVersion}" + ballerinaStdLibs "io.ballerina.stdlib:uuid-ballerina:${stdlibUuidVersion}" + ballerinaStdLibs "io.ballerina.stdlib:crypto-ballerina:${stdlibCryptoVersion}" + ballerinaStdLibs "io.ballerina.stdlib:io-ballerina:${stdlibIoVersion}" + ballerinaStdLibs "io.ballerina.stdlib:observe-ballerina:${observeVersion}" + ballerinaStdLibs "io.ballerina:observe-ballerina:${observeInternalVersion}" + } + + task allDeps(type: DependencyReportTask) {} +} + +def moduleVersion = project.version.replace("-SNAPSHOT", "") + +release { + failOnPublishNeeded = false + + buildTasks = ["build"] + failOnSnapshotDependencies = true + versionPropertyFile = 'gradle.properties' + tagTemplate = 'v$version' + + git { + requireBranch = "release-${moduleVersion}" + pushToRemote = 'origin' + } +} + +task build { + dependsOn(':java.jms-ballerina:build') + dependsOn(':java.jms-native:build') +} diff --git a/java.jms/tests/resources/.keep b/changelog.md similarity index 100% rename from java.jms/tests/resources/.keep rename to changelog.md diff --git a/codecov.yml b/codecov.yml new file mode 100644 index 00000000..224cf170 --- /dev/null +++ b/codecov.yml @@ -0,0 +1,14 @@ +ignore: + - "compiler-plugin-tests" + - "examples" + - "load-tests" + +coverage: + precision: 2 + round: down + range: "60...80" + status: + project: + default: + target: 80 + \ No newline at end of file diff --git a/compiler-plugin/pom.xml b/compiler-plugin/pom.xml deleted file mode 100644 index 0e0e69cc..00000000 --- a/compiler-plugin/pom.xml +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - org.ballerinalang - module-jms - 0.99.0 - ../pom.xml - - 4.0.0 - jms-compiler-plugin - 0.99.0 - jar - JMS Compiler Plugin - - - - org.ballerinalang - ballerina-lang - compile - - - org.ballerinalang - ballerina-runtime - compile - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - -proc:none - - - - - - diff --git a/compiler-plugin/src/main/java/org.ballerinalang.java.jms/ServiceCompilerPlugin.java b/compiler-plugin/src/main/java/org.ballerinalang.java.jms/ServiceCompilerPlugin.java deleted file mode 100644 index 47a8b75c..00000000 --- a/compiler-plugin/src/main/java/org.ballerinalang.java.jms/ServiceCompilerPlugin.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.ballerinalang.java.jms; - -import org.ballerinalang.compiler.plugins.SupportedResourceParamTypes; -import org.ballerinalang.compiler.plugins.AbstractCompilerPlugin; -import org.ballerinalang.model.tree.AnnotationAttachmentNode; -import org.ballerinalang.model.tree.FunctionNode; -import org.ballerinalang.model.tree.ServiceNode; -import org.ballerinalang.util.diagnostic.Diagnostic; -import org.ballerinalang.util.diagnostic.DiagnosticLog; -import org.wso2.ballerinalang.compiler.semantics.analyzer.Types; -import org.wso2.ballerinalang.compiler.semantics.model.types.BType; -import org.wso2.ballerinalang.compiler.tree.BLangFunction; -import org.wso2.ballerinalang.compiler.tree.BLangSimpleVariable; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import static org.ballerinalang.jvm.util.BLangConstants.VERSION_SEPARATOR; - -/** - * Abstract Compiler plugin for validating Jms Listener services. - * - * @since 0.995.0 - */ -@SupportedResourceParamTypes(expectedListenerType = @SupportedResourceParamTypes.Type(orgName = "wso2", packageName = "jms", - name = "MessageListener"), - paramTypes = { - @SupportedResourceParamTypes.Type(orgName = "wso2", packageName = "jms", name = "Message") - } -) -public class ServiceCompilerPlugin extends AbstractCompilerPlugin { - - private static final String PACKAGE_NAME = "wso2/jms"; - private static final String VERSION = "0.7.0"; - - private static final String PACKAGE_NAME_WITH_VERSION = PACKAGE_NAME + VERSION_SEPARATOR + VERSION; - private static final String MESSAGE_NAME = "Message"; - private static final String TEXT_MESSAGE_NAME = "TextMessage"; - private static final String MAP_MESSAGE_NAME = "MapMessage"; - private static final String STREAM_MESSAGE_NAME= "StreamMessage"; - private static final String BYTES_MESSAGE_NAME = "BytesMessage"; - - private static final String RESOURCE_NAME_ON_MESSAGE = "onMessage"; - private static final String RESOURCE_NAME_ON_TEXT_MESSAGE = "onTextMessage"; - private static final String RESOURCE_NAME_ON_MAP_MESSAGE = "onMapMessage"; - private static final String RESOURCE_NAME_ON_BYTES_MESSAGE = "onBytesMessage"; - private static final String RESOURCE_NAME_ON_STREAM_MESSAGE = "onStreamMessage"; - private static final String RESOURCE_NAME_ON_OTHER_MESSAGE = "onOtherMessage"; - private static final Set SPECIFIC_FUNCTION_SET; - static { - SPECIFIC_FUNCTION_SET = new HashSet() { - { - add(RESOURCE_NAME_ON_TEXT_MESSAGE); - add(RESOURCE_NAME_ON_MAP_MESSAGE); - add(RESOURCE_NAME_ON_BYTES_MESSAGE); - add(RESOURCE_NAME_ON_STREAM_MESSAGE); - } - }; - } - - private static final String MESSAGE_FULL_NAME = PACKAGE_NAME_WITH_VERSION + ":" + MESSAGE_NAME; - private static final String TEXT_MESSAGE_FULL_NAME = PACKAGE_NAME_WITH_VERSION + ":" + TEXT_MESSAGE_NAME; - private static final String MAP_MESSAGE_FULL_NAME = PACKAGE_NAME_WITH_VERSION + ":" + MAP_MESSAGE_NAME; - private static final String BYTES_MESSAGE_FULL_NAME = PACKAGE_NAME_WITH_VERSION + ":" + BYTES_MESSAGE_NAME; - private static final String STREAM_MESSAGE_FULL_NAME = PACKAGE_NAME_WITH_VERSION + ":" + STREAM_MESSAGE_NAME; - private static final String INVALID_RESOURCE_SIGNATURE_FOR = "Invalid resource signature for "; - - private DiagnosticLog dlog = null; - private Types types = null; - private BType errorOrNil = null; - - @Override - public void init(DiagnosticLog diagnosticLog) { - dlog = diagnosticLog; - } - - @Override - public void process(ServiceNode serviceNode, List annotations) { - - if (!annotations.isEmpty()) { - dlog.logDiagnostic(Diagnostic.Kind.ERROR, serviceNode.getPosition(), - "The JMS service does not have a service annotation"); - } - - List resources = (List) serviceNode.getResources(); - - if (resources.isEmpty()) { - dlog.logDiagnostic(Diagnostic.Kind.ERROR, serviceNode.getPosition(), - "service: at least on resource is expected."); - } - if (resources.size() == 1) { - BLangFunction resource = resources.get(0); - if (!RESOURCE_NAME_ON_MESSAGE.equals(resource.name.value)) { - dlog.logDiagnostic(Diagnostic.Kind.ERROR, resource.pos, - "resource: Expected resource name is [" + RESOURCE_NAME_ON_MESSAGE - + "] or one or more of message specific resources with " - + "[" + RESOURCE_NAME_ON_OTHER_MESSAGE + "] resource."); - } - } else { - boolean otherFunctionFound = false; - for(BLangFunction resource: resources) { - if (!isResourceReturnsErrorOrNil(resource)) { - dlog.logDiagnostic(Diagnostic.Kind.ERROR, resource.pos, "Invalid return type: expected error?"); - } - - if (!otherFunctionFound && RESOURCE_NAME_ON_OTHER_MESSAGE.equals(resource.getName().getValue()) ) { - validateParameter(resource, MESSAGE_FULL_NAME); - otherFunctionFound = true; - } else { - validateSpecificFunction(resource); - } - } - - if (!otherFunctionFound) { - dlog.logDiagnostic(Diagnostic.Kind.ERROR, serviceNode.getPosition(), - "resource: Expected resource name [" + RESOURCE_NAME_ON_OTHER_MESSAGE + "] not specified."); - } - } - - } - - private void validateSpecificFunction(BLangFunction resource) { - String resourceName = resource.getName().getValue(); - if (RESOURCE_NAME_ON_MESSAGE.equals(resourceName)) { - dlog.logDiagnostic(Diagnostic.Kind.ERROR, resource.pos, - "resource: [" + RESOURCE_NAME_ON_MESSAGE + "] cannot be used with message type" + - " specific resources and [" + RESOURCE_NAME_ON_OTHER_MESSAGE + "] resource."); - } - - if (RESOURCE_NAME_ON_TEXT_MESSAGE.equals(resourceName)) { - validateParameter(resource, TEXT_MESSAGE_FULL_NAME); - } else if (RESOURCE_NAME_ON_BYTES_MESSAGE.equals(resourceName)) { - validateParameter(resource, BYTES_MESSAGE_FULL_NAME); - } else if (RESOURCE_NAME_ON_MAP_MESSAGE.equals(resourceName)) { - validateParameter(resource, MAP_MESSAGE_FULL_NAME); - } else if (RESOURCE_NAME_ON_STREAM_MESSAGE.equals(resourceName)) { - validateParameter(resource, STREAM_MESSAGE_FULL_NAME); - } else { - dlog.logDiagnostic(Diagnostic.Kind.ERROR, resource.pos, - "resource: Unknown resource name [" + resourceName + "]"); - } - } - - private void validateParameter(BLangFunction resource, String messageFullName) { - List paramDetails = resource.getParameters(); - if (paramDetails == null || paramDetails.size() != 1) { - dlog.logDiagnostic(Diagnostic.Kind.ERROR, resource.pos, INVALID_RESOURCE_SIGNATURE_FOR - + resource.getName().getValue() + - " Expected " + messageFullName + " parameter only."); - } else if (!messageFullName.equals(paramDetails.get(0).type.toString())) { - dlog.logDiagnostic(Diagnostic.Kind.ERROR, resource.pos, - INVALID_RESOURCE_SIGNATURE_FOR + resource.getName().getValue() + - " Parameter should be " + messageFullName + " found: " - + paramDetails.get(0).type.toString()); - } - } - - public boolean isResourceReturnsErrorOrNil(FunctionNode functionNode) { - BLangFunction resource = (BLangFunction) functionNode; - return types.isAssignable(resource.symbol.getReturnType(), errorOrNil); - } -} - - diff --git a/compiler-plugin/src/main/resources/META-INF/services/org.ballerinalang.compiler.plugins.CompilerPlugin b/compiler-plugin/src/main/resources/META-INF/services/org.ballerinalang.compiler.plugins.CompilerPlugin deleted file mode 100644 index 38d6790f..00000000 --- a/compiler-plugin/src/main/resources/META-INF/services/org.ballerinalang.compiler.plugins.CompilerPlugin +++ /dev/null @@ -1 +0,0 @@ -org.ballerinalang.java.jms.ServiceCompilerPlugin \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 00000000..1fcd674e --- /dev/null +++ b/gradle.properties @@ -0,0 +1,31 @@ +org.gradle.caching=true +group=io.ballerina.stdlib +version=0.0.1-SNAPSHOT +ballerinaLangVersion=2201.6.0 + +checkstylePluginVersion=8.18 +spotbugsPluginVersion=4.5.1 +shadowJarPluginVersion=5.2.0 +downloadPluginVersion=4.0.4 +releasePluginVersion=2.6.0 +ballerinaGradlePluginVersion=1.0.0 + +# Azure dependencies +javaxJmsVersion=2.0.1 +slf4jVersion=2.0.7 + +#stdlib dependencies + +# Level 01 +stdlibTimeVersion=2.2.5 +stdlibIoVersion=1.4.1 + +# Level 02 +stdlibLogVersion=2.7.1 +stdlibCryptoVersion=2.3.1 + +# Level 03 +stdlibUuidVersion=1.5.1 + +observeVersion=1.0.7 +observeInternalVersion=1.0.6 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..943f0cbf Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..f398c33c --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 00000000..65dcd68d --- /dev/null +++ b/gradlew @@ -0,0 +1,244 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..6689b85b --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/issue_template.md b/issue_template.md deleted file mode 100644 index 757e13ef..00000000 --- a/issue_template.md +++ /dev/null @@ -1,18 +0,0 @@ -**Description:** - - -**Suggested Labels:** - - -**Suggested Assignees:** - - -**Affected Product Version:** - -**OS, DB, other environment details and versions:** - -**Steps to reproduce:** - - -**Related Issues:** - \ No newline at end of file diff --git a/java.jms/Ballerina.lock b/java.jms/Ballerina.lock deleted file mode 100644 index 4ecb406f..00000000 --- a/java.jms/Ballerina.lock +++ /dev/null @@ -1,34 +0,0 @@ -org_name = "ballerina" -version = "0.99.0" -lockfile_version = "1.0.0" -ballerina_version = "slp1" - -[[imports."ballerina/observe:0.8.0"]] -org_name = "ballerina" -name = "java" -version = "0.9.0" - -[[imports."ballerina/log:1.0.0"]] -org_name = "ballerina" -name = "java" -version = "0.9.0" - -[[imports."ballerina/java.jms:0.99.0"]] -org_name = "ballerina" -name = "observe" -version = "0.8.0" - -[[imports."ballerina/java.jms:0.99.0"]] -org_name = "ballerina" -name = "log" -version = "1.0.0" - -[[imports."ballerina/java.jms:0.99.0"]] -org_name = "ballerina" -name = "java" -version = "0.9.0" - -[[imports."ballerina/java.jms:0.99.0"]] -org_name = "ballerina" -name = "lang.object" -version = "1.0.0" diff --git a/java.jms/Ballerina.toml b/java.jms/Ballerina.toml deleted file mode 100644 index f57ef2fa..00000000 --- a/java.jms/Ballerina.toml +++ /dev/null @@ -1,26 +0,0 @@ -[project] -org-name= "ballerina" -version= "0.99.0" -license= ["Apache-2.0"] -authors = ["Ballerina"] -keywords = ["jms"] -repository = "https://github.com/ballerina-platform/module-jms" - -[dependencies] - -[platform] -target = "java8" - - [[platform.libraries]] - module = "java.jms" - path = "../utils/target/jms-utils-0.99.0.jar" - artifactId = "jms-utils" - version = "0.99.0" - groupId = "org.ballerinalang" - - [[platform.libraries]] - module = "java.jms" - path = "../utils/target/classes/lib/javax.jms-api-2.0.1.jar" - artifactId = "javax.jms-api" - version = "2.0.1" - groupId = "javax.jms" diff --git a/java.jms/pom.xml b/java.jms/pom.xml deleted file mode 100644 index 7f7a2cff..00000000 --- a/java.jms/pom.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - - - org.ballerinalang - module-jms - 0.99.0 - ../pom.xml - - 4.0.0 - b7a-jms-connector - pom - 0.8.1 - Ballerina JMS Connector - - - - - org.codehaus.mojo - exec-maven-plugin - - - ballerina-build - package - - exec - - - - - ballerina - - build - -c - -a - - - - - - diff --git a/java.jms/src/java.jms/Module.md b/java.jms/src/java.jms/Module.md deleted file mode 100644 index df8e7277..00000000 --- a/java.jms/src/java.jms/Module.md +++ /dev/null @@ -1,139 +0,0 @@ -Connects to a JMS provider using Ballerina. - -## Module overview - -The `ballerina/java.jms` module provides an API to connect to an external JMS provider like ActiveMQ from Ballerina. - -This module is created with minimal deviation from the JMS API to make it easy for the developers who are used to working - with the JMS API. This module is written to support both JMS 2.0 and JMS 1.0 API. - -Currently, the following JMS API Classes are supported through this module. - - - Connection - - Session - - Destination (Queue, Topic, TemporaryQueue, TemporaryTopic) - - Message (TextMessage, MapMessage, BytesMessage, StreamMessage) - - MessageConsumer - - MessageProducer - - The following sections provide details on how to use the JMS connector. - - - [Compatibility](#compatibility) - - [Samples](#samples) - -## Compatibility - -| Ballerina Language Version | JMS Module Version | -|:---------------------------:|:------------------------------:| -| 1.0.x | 0.6.x | -| 1.1.x | 0.7.x | -| 1.2.x | 0.8.x | -| Swan Lake Preview1 | 0.99.x | - -## Samples - -### JMS Message Producer and Consumer example - -Following is a simple Ballerina program that sends and receives a message from a queue named *MyQueue*. - -```ballerina -import ballerina/log; -import ballerina/java.jms; - -public function main() returns error? { - - jms:Connection connection = check jms:createConnection({ - initialContextFactory: "org.apache.activemq.jndi.ActiveMQInitialContextFactory", - providerUrl: "tcp://localhost:61616" - }); - jms:Session session = check connection->createSession({acknowledgementMode: "AUTO_ACKNOWLEDGE"}); - jms:Destination queue = check session->createQueue("MyQueue"); - jms:MessageProducer producer = check session.createProducer(queue); - jms:MessageConsumer consumer = check session->createConsumer(queue); - - jms:TextMessage msg = check session.createTextMessage("Hello Ballerina!"); - - check producer->send(msg); - - jms:Message? response = check consumer->receive(3000); - if (response is jms:TextMessage) { - var val = response.getText(); - if (val is string) { - log:printInfo("Message received: " + val); - } else { - log:printInfo("Message received without text"); - } - } else { - log:printInfo("Message received."); - } -} -``` - -### Asynchronous message consumer - -One of the key deviations from the JMS API was the asynchronous message consumption using message listeners. In -Ballerina transport listener concept is covered with **service** type, hence we have used the Ballerina service to -implement the message listener. Following is a message listener example listening on a topic named *MyTopic*. - -```ballerina -import ballerina/log; -import ballerina/java.jms; - -jms:Connection connection = check jms:createConnection({ - initialContextFactory: "org.apache.activemq.jndi.ActiveMQInitialContextFactory", - providerUrl: "tcp://localhost:61616" - }); - -listener jms:MessageConsumer jmsConsumer = createListener(connection); - -service messageListener on jmsConsumer { - - resource function onMessage(jms:Message message) { - if (message is jms:TextMessage) { - var val = message.getText(); - if (val is string) { - log:printInfo("Message received: " + val ); - } else { - log:printInfo("Message received without text"); - } - } else { - log:printInfo("Message received."); - } - } -} - -function createListener(jms:Connection connection) returns jms:MessageConsumer { - jms:Session session = checkpanic connection->createSession({acknowledgementMode: "AUTO_ACKNOWLEDGE"}); - jms:Destination queue = checkpanic session->createQueue("MyQueue"); - jms:MessageConsumer consumer = checkpanic session->createConsumer(queue); - return consumer; -} -``` - -## Adding the required dependencies - -Add the required dependencies to the `Ballerina.toml` file based on the broker that you're trying to connect to. -Add the configurations below to run the given examples using `Apache ActiveMQ`. - -``` - [[platform.libraries]] - module = "jms" - path = "/activemq-client-5.15.12.jar" - artifactId = "activemq-client" - version = "5.15.12" - groupId = "org.apache.activemq" - - [[platform.libraries]] - module = "jms" - path = "/geronimo-j2ee-management_1.1_spec-1.0.1.jar" - artifactId = "geronimo-j2ee-management_1.1_spec" - version = "1.0.1" - groupId = "org.apache.geronimo.specs" - - [[platform.libraries]] - module = "jms" - path = "/libs/hawtbuf-1.11.jar" - artifactId = "hawtbuf" - version = "1.11" - groupId = "org.fusesource.hawtbuf" -``` diff --git a/java.jms/src/java.jms/Observability/JMSMetricsUtils.bal b/java.jms/src/java.jms/Observability/JMSMetricsUtils.bal deleted file mode 100644 index 49f77b59..00000000 --- a/java.jms/src/java.jms/Observability/JMSMetricsUtils.bal +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2020 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -// -// WSO2 Inc. licenses this file to you under the Apache License, -// Version 2.0 (the "License"); you may not use this file except -// in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -import ballerina/observe; -import ballerina/log; - -# Register and increment counter -# -# + counter - counter to be registered and incremented -function registerAndIncrementCounter(observe:Counter counter) { - error? result = counter.register(); - if (result is error) { - log:printError("Error in registering counter : " + counter.name, result); - } - counter.increment(); -} - -# Register and increment gauge -# -# + gauge - gauge to be registered and incremented -function registerAndIncrementGauge(observe:Gauge gauge) { - error? result = gauge.register(); - if (result is error) { - log:printError("Error in registering gauge : " + gauge.name, result); - } - gauge.increment(); -} - -# Decrement gauge -# -# + gauge - gauge to be decremented -function decrementGauge(observe:Gauge gauge) { - gauge.decrement(); -} diff --git a/java.jms/src/java.jms/Observability/JMSObservabilityConstants.bal b/java.jms/src/java.jms/Observability/JMSObservabilityConstants.bal deleted file mode 100644 index 419eff1e..00000000 --- a/java.jms/src/java.jms/Observability/JMSObservabilityConstants.bal +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2020 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -// -// WSO2 Inc. licenses this file to you under the Apache License, -// Version 2.0 (the "License"); you may not use this file except -// in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -const TOTAL_JMS_CONNECTIONS = "JMS_Connection_total"; -const TOTAL_JMS_MESSAGES_RECEIVED = "JMS_Consumer_Messages_Received_total"; -const TOTAL_JMS_MESSAGES_SENT = "JMS_Producer_Messages_Sent_total"; -const TOTAL_JMS_SESSIONS = "JMS_Session_total"; -const TOTAL_JMS_UNSUBSCRIBES = "JMS_Unsubscribe_total"; -const TOTAL_JMS_TEMPORARY_QUEUES = "JMS_TemporaryQueue_total"; -const TOTAL_JMS_TEMPORARY_TOPICS = "JMS_TemporaryTopic_total"; -const TOTAL_JMS_QUEUES = "JMS_Queue_total"; -const TOTAL_JMS_TOPICS = "JMS_Topic_total"; -const TOTAL_JMS_MESSAGES_CREATED = "JMS_Messages_Created_total"; -const TOTAL_JMS_TEXT_MESSAGES_WITH_TEXT_CREATED = "JMS_Text_Messages_With_Text_Created_total"; -const TOTAL_JMS_TEXT_MESSAGES_CREATED = "JMS_Text_Messages_Created_total"; -const TOTAL_JMS_MAP_MESSAGES_CREATED = "JMS_Map_Messages_Created_total"; -const TOTAL_JMS_STREAM_MESSAGES_CREATED = "JMS_Stream_Messages_Created_total"; -const TOTAL_JMS_BYTE_MESSAGES_CREATED = "JMS_Byte_Messages_Created_total"; -const TOTAL_JMS_PRODUCERS = "JMS_Producer_total"; -const TOTAL_JMS_CONSUMERS = "JMS_Consumer_total"; -const TOTAL_JMS_DURABLE_SUBSCRIBERS = "JMS_DurableSubscriber_total"; -const TOTAL_JMS_SHARED_CONSUMERS = "JMS_SharedConsumer_total"; -const TOTAL_JMS_SHARED_DURABLE_CONSUMERS = "JMS_SharedDurableConsumer_total"; - -const ACTIVE_JMS_CONSUMERS = "JMS_Consumer_active"; -const ACTIVE_JMS_TEMPORARY_QUEUES = "JMS_TemporaryQueue_active"; -const ACTIVE_JMS_TEMPORARY_TOPICS = "JMS_TemporaryTopic_active"; diff --git a/java.jms/src/java.jms/abstract_message.bal b/java.jms/src/java.jms/abstract_message.bal deleted file mode 100644 index f218ca4d..00000000 --- a/java.jms/src/java.jms/abstract_message.bal +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) 2019 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -// -// WSO2 Inc. licenses this file to you under the Apache License, -// Version 2.0 (the "License"); you may not use this file except -// in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -# The abstract message object is the root of all message objects. It defines message headers, properties, and -# acknowledge methods used for all message objects. -# -# Most message-oriented middleware (MOM) products treat messages as lightweight entities that consist of a header -# and a body. The header contains fields used for message routing and identification; the body contains the -# application data being sent. -public type AbstractMessage abstract client object { - - handle jmsMessage; - - public remote function acknowledge() returns error?; - - public function clearBody() returns error?; - - public function clearProperties() returns error?; - - public function getBooleanProperty(string name) returns boolean | error; - - public function getByteProperty(string name) returns byte | error; - - public function getDoubleProperty(string name) returns float | error; - - public function getFloatProperty(string name) returns float | error; - - public function getIntProperty(string name) returns int | error; - - public function getJMSCorrelationID() returns (string|error)?; - - public function getJMSCorrelationIDAsBytes() returns byte[] | error; - - public function getJMSDeliveryMode() returns int | error; - - public function getJMSDeliveryTime() returns int | error; - - public function getJMSDestination() returns Destination | error; - - public function getJMSExpiration() returns int | error; - - public function getJMSMessageID() returns (string|error)?; - - public function getJMSPriority() returns int | error; - - public function getJMSRedelivered() returns boolean | error; - - public function getJMSReplyTo() returns Destination | error; - - public function getJMSTimestamp() returns int | error; - - public function getJMSType() returns (string|error)?; - - public function getLongProperty(string name) returns int | error; - - public function getPropertyNames() returns string[] | error; - - public function getShortProperty(string name) returns int | error; - - public function getStringProperty(string name) returns (string|error)?; - - public function propertyExists(string name) returns boolean | error; - - public function setBooleanProperty(string name, boolean value) returns error?; - - public function setByteProperty(string name, byte value) returns error?; - - public function setDoubleProperty(string name, float value) returns error?; - - public function setFloatProperty(string name, float value) returns error?; - - public function setIntProperty(string name, int value) returns error?; - - public function setJMSCorrelationID(string correlationId) returns error?; - - public function setJMSCorrelationIDAsBytes(byte[] correlationId) returns error?; - - public function setJMSReplyTo(Destination replyTo) returns error?; - - public function setJMSType(string jmsType) returns error?; - - public function setLongProperty(string name, int value) returns error?; - - public function setShortProperty(string name, int value) returns error?; - - public function setStringProperty(string name, string value) returns error?; - - function getJmsMessage() returns handle; - -}; diff --git a/java.jms/src/java.jms/bytes_message.bal b/java.jms/src/java.jms/bytes_message.bal deleted file mode 100644 index 00334442..00000000 --- a/java.jms/src/java.jms/bytes_message.bal +++ /dev/null @@ -1,667 +0,0 @@ -// Copyright (c) 2019 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -// -// WSO2 Inc. licenses this file to you under the Apache License, -// Version 2.0 (the "License"); you may not use this file except -// in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -import ballerina/java; - -# Represent the 'BytesMessage' used to send and receive content from the a JMS provider. -# -# Most message-oriented middleware (MOM) products treat messages as lightweight entities that consist of a header -# and a body. The header contains fields used for message routing and identification; the body contains the -# application data being sent. -public type BytesMessage client object { - - // Add a reference to the `AbstractMessage` object type. - *AbstractMessage; - - # Initialized a `BytesMessage` object. - # - # + handle - The java reference to the jms text message. - function init(handle bytesMessage) { - self.jmsMessage = bytesMessage; - } - - # Get the number of bytes of the message body. - # - # + return - Returns the body length or an error if it fails. - public function getBodyLength() returns int | error { - return getBodyLength(self.jmsMessage); - } - - # Read a boolean from the message. - # - # + return - Returns a boolean value or an error if it fails. - public function readBoolean() returns boolean | error { - return readBoolean(self.jmsMessage); - } - - # Read a byte from the message. - # - # + return - Returns a byte value or an error if it fails. - public function readByte() returns byte | error { - return readByte(self.jmsMessage); - } - - # Read a byte array from the message. - # - # + length - The number of bytes to read - # + return - Returns a byte array or an error if it fails. - public function readBytes(int? length = ()) returns byte[] | error { - if(length is int) { - return readPortionOfBytes(self.jmsMessage, length); - } else { - return readBytes(self.jmsMessage); - } - } - -// # Read a unicode character value from the message. -// # -// # + return - Returns a string value or an error if it fails. -// public function readChar() returns string | error { -// returns readChar(self.jmsMessage); -// } - - # Read a double value from the message. - # - # + return - Returns a double value or an error if it fails. - public function readDouble() returns float | error { - return readDouble(self.jmsMessage); - } - - # Read a float value from the message. - # - # + return - Returns a float value or an error if it fails. - public function readFloat() returns float | error { - return readFloat(self.jmsMessage); - } - - # Read an int value from the message. - # - # + return - Returns an int value or an error if it fails. - public function readInt() returns int | error { - return readInt(self.jmsMessage); - } - - # Read a long value from the message. - # - # + return - Returns a long value or an error if it fails. - public function readLong() returns int | error { - return readLong(self.jmsMessage); - } - - # Read a short value from the message. - # - # + return - Returns a short value or an error if it fails. - public function readShort() returns int | error { - return readShort(self.jmsMessage); - } - - # Read an unsigned 8-bit number from the message. - # - # + return - Returns a int value or an error if it fails. - public function readUnsignedByte() returns int | error { - return readUnsignedByte(self.jmsMessage); - } - - # Read an unsigned 16-bit number from the message. - # - # + return - Returns a int value or an error if it fails. - public function readUnsignedShort() returns int | error { - return readUnsignedShort(self.jmsMessage); - } - - # Read a string that has been encoded using a modified UTF-8 format from the message. - # - # + return - Returns a string value or an error if it fails. - public function readUTF() returns string? | error { - handle|error val = readUTF(self.jmsMessage); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Puts the message body in read-only mode and repositions the stream of bytes to the beginning. - # - # + return - Returns an error if it fails. - public function reset() returns error? { - return reset(self.jmsMessage); - } - - # Write a boolean to the message stream as a 1-byte value. - # - # + value - The boolean value to be written - # + return - Returns an error if it fails. - public function writeBoolean(boolean value) returns error? { - return writeBoolean(self.jmsMessage, value); - } - - # Write a byte to the message. - # - # + value - The byte value to be written - # + return - Returns an error if it fails. - public function writeByte(byte value) returns error? { - return writeByte(self.jmsMessage, value); - } - - # Write a byte array to the message. - # - # + value - The byte array to be written - # + offset - The initial offset within the byte array - # + length - The number of bytes to use - # + return - Returns an error if it fails. - public function writeBytes(byte[] value, int? offset = (), int? length = ()) returns error? { - if(offset is int && length is int) { - return writePortionOfBytes(self.jmsMessage, value, offset, length); - } else { - return writeBytes(self.jmsMessage, value); - } - } - -// # Write a char to the message. -// # -// # + return - Returns an error if it fails. -// public function writeChar(string value) returns error? { -// return writeChar(self.jmsMessage, java:fromString(value)); -// } - - # Write a double to the message. - # - # + value - The double value to be written - # + return - Returns an error if it fails. - public function writeDouble(float value) returns error? { - return writeDouble(self.jmsMessage, value); - } - - # Write a float to the message. - # - # + value - The float value to be written - # + return - Returns an error if it fails. - public function writeFloat(float value) returns error? { - return writeFloat(self.jmsMessage, value); - } - - # Write an int to the message. - # - # + value - The int value to be written - # + return - Returns an error if it fails. - public function writeInt(int value) returns error? { - return writeInt(self.jmsMessage, value); - } - - # Write a long to the message. - # - # + value - The long value to be written - # + return - Returns an error if it fails. - public function writeLong(int value) returns error? { - return writeLong(self.jmsMessage, value); - } - - # Write a short to the message. - # - # + value - The short value to be written - # + return - Returns an error if it fails. - public function writeShort(int value) returns error? { - return writeShort(self.jmsMessage, value); - } - - # Write a string to the message. - # - # + value - The string value to be written - # + return - Returns an error if it fails. - public function writeUTF(string value) returns error? { - return writeUTF(self.jmsMessage, java:fromString(value)); - } - - # Acknowledges the reception of this message. This is used when the consumer has chosen CLIENT_ACKNOWLEDGE as its - # acknowledgment mode. - # - # + return - If an error occurred while acknowledging the message. - public remote function acknowledge() returns error? { - return acknowledge(self.jmsMessage); - } - - # Clears out the message body. - # - # + return - If an error occurred while clearing out the message properties. - public function clearBody() returns error? { - return clearBody(self.jmsMessage); - } - - # Clears a message's properties. - # - # + return - If an error occurred while clearing out the message properties. - public function clearProperties() returns error? { - return clearProperties(self.jmsMessage); - } - - # Get the given boolean property. - # - # + name - The name of the boolean property - # + return - Returns the boolean value or an error if it fails. - public function getBooleanProperty(string name) returns boolean | error { - return getBooleanProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given byte property. - # - # + name - The name of the byte property - # + return - Returns the byte value or an error if it fails. - public function getByteProperty(string name) returns byte | error { - return getByteProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given double property. - # - # + name - The name of the double property - # + return - Returns the double value or an error if it fails. - public function getDoubleProperty(string name) returns float | error { - return getDoubleProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given float property. - # - # + name - The name of the float property - # + return - Returns the float value or an error if it fails. - public function getFloatProperty(string name) returns float | error { - return getFloatProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given int property. - # - # + name - The name of the int property - # + return - Returns the int value or an error if it fails. - public function getIntProperty(string name) returns int | error { - return getIntProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the message correlation ID. - # - # + return - Returns the message correlation ID or an error if it fails. - public function getJMSCorrelationID() returns string? | error { - handle|error val = getJMSCorrelationID(self.jmsMessage); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Get the message correlation ID as an array of bytes. - # - # + return - Returns the message correlation ID as an byte array or an error if it fails. - public function getJMSCorrelationIDAsBytes() returns byte[] | error { - return getJMSCorrelationIDAsBytes(self.jmsMessage); - } - - # Get the message delivery mode. - # - # + return - Returns the message delivery mode or an error if it fails. - public function getJMSDeliveryMode() returns int | error { - return getJMSDeliveryMode(self.jmsMessage); - } - - # Get the message delivery time. - # - # + return - Returns the message delivery time or an error if it fails. - public function getJMSDeliveryTime() returns int | error { - return getJMSDeliveryTime(self.jmsMessage); - } - - # Get the message destination object. - # - # + return - Returns the message destination object or an error if it fails. - public function getJMSDestination() returns Destination | error { - handle|error val = getJMSDestination(self.jmsMessage); - if (val is handle) { - return getDestination(val); - } else { - return val; - } - } - - # Get the message expiration time. - # - # + return - Returns the message expiration time or an error if it fails. - public function getJMSExpiration() returns int | error { - return getJMSExpiration(self.jmsMessage); - } - - # Get the message ID. - # - # + return - Returns the message ID or an error if it fails. - public function getJMSMessageID() returns string? | error { - handle|error val = getJMSMessageID(self.jmsMessage); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Get the message priority. - # - # + return - Returns the message priority or an error if it fails. - public function getJMSPriority() returns int | error { - return getJMSPriority(self.jmsMessage); - } - - # Get an indication whether the message being redelivered. - # - # + return - Returns the message redelivered or an error if it fails. - public function getJMSRedelivered() returns boolean | error { - return getJMSRedelivered(self.jmsMessage); - } - - # Get the Destination object to which a reply to this message should be sent. - # - # + return - Returns the reply to destination or an error if it fails. - public function getJMSReplyTo() returns Destination | error { - handle|error val = getJMSReplyTo(self.jmsMessage); - if (val is handle) { - return getDestination(val); - } else { - return val; - } - } - - # Get the message timestamp. - # - # + return - Returns the message timestamp or an error if it fails. - public function getJMSTimestamp() returns int | error { - return getJMSTimestamp(self.jmsMessage); - } - - # Get the message type identifier. - # - # + return - Returns the message type or an error if it fails. - public function getJMSType() returns (string|error)? { - handle|error val = getJMSType(self.jmsMessage); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Get the given long property. - # - # + name - The name of the long property - # + return - Returns the int value or an error if it fails. - public function getLongProperty(string name) returns int | error { - return getLongProperty(self.jmsMessage, java:fromString(name)); - } - - # Get string array of property names. - # - # + return - Returns the string array of property names or an error if it fails. - public function getPropertyNames() returns string[] | error { - return getPropertyNames(self.jmsMessage); - } - - # Get the given short property. - # - # + name - The name of the short property - # + return - Returns the int value or an error if it fails. - public function getShortProperty(string name) returns int | error { - return getShortProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given string property. - # - # + name - The name of the string property - # + return - Returns the string value or an error if it fails. - public function getStringProperty(string name) returns (string|error)? { - handle|error val = getStringProperty(self.jmsMessage, java:fromString(name)); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Indicate whether a property value exists. - # - # + name - The name of the property to test - # + return - Returns true if the property exists or an error if it fails. - public function propertyExists(string name) returns boolean | error { - return propertyExists(self.jmsMessage, java:fromString(name)); - } - - # Set the boolean value with the specified name into the message. - # - # + name - The name of the boolean property - # + value - The boolean property value to set - # + return - Returns an error if it fails. - public function setBooleanProperty(string name, boolean value) returns error? { - return setBooleanProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the byte value with the specified name into the message. - # - # + name - The name of the byte property - # + value - The byte property value to set - # + return - Returns an error if it fails. - public function setByteProperty(string name, byte value) returns error? { - return setByteProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the double value with the specified name into the message. - # - # + name - The name of the double property - # + value - The double property value to set - # + return - Returns an error if it fails. - public function setDoubleProperty(string name, float value) returns error? { - return setDoubleProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the float value with the specified name into the message. - # - # + name - The name of the float property - # + value - The float property value to set - # + return - Returns an error if it fails. - public function setFloatProperty(string name, float value) returns error? { - return setFloatProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the int value with the specified name into the message. - # - # + name - The name of the int property - # + value - The int property value to set - # + return - Returns an error if it fails. - public function setIntProperty(string name, int value) returns error? { - return setIntProperty(self.jmsMessage, java:fromString(name), value); - } - - # Sets the correlation id for the message. - # - # + correlationId - correlation id of a message as a string - # + return - Returns an error if it fails. - public function setJMSCorrelationID(string correlationId) returns error? { - return setJMSCorrelationID(self.jmsMessage, java:fromString(correlationId)); - } - - # Sets the correlation id an array of bytes for the message. - # - # + correlationId - correlation id value as an array of bytes - # + return - Returns an error if it fails. - public function setJMSCorrelationIDAsBytes(byte[] correlationId) returns error? { - return setJMSCorrelationIDAsBytes(self.jmsMessage, correlationId); - } - - # Set the reply destination to the message which a reply should send. - # - # + replyTo - Destination to which to send a response to this message - # + return - Returns an error if it fails. - public function setJMSReplyTo(Destination replyTo) returns error? { - return setJMSReplyTo(self.jmsMessage, replyTo.getJmsDestination()); - } - - # Set the message type. - # - # + jmsType - The message type - # + return - Returns an error if it fails. - public function setJMSType(string jmsType) returns error? { - return setJMSType(self.jmsMessage, java:fromString(jmsType)); - } - - # Set the long value with the specified name into the message. - # - # + name - The name of the long property - # + value - The long property value to set - # + return - Returns an error if it fails. - public function setLongProperty(string name, int value) returns error? { - return setLongProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the short value with the specified name into the message. - # - # + name - The name of the short property - # + value - The short property value to set - # + return - Returns an error if it fails. - public function setShortProperty(string name, int value) returns error? { - return setShortProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the string value with the specified name into the message. - # - # + name - The name of the string property - # + value - The string property value to set - # + return - Returns an error if it fails. - public function setStringProperty(string name, string value) returns error? { - return setStringProperty(self.jmsMessage, java:fromString(name), java:fromString(value)); - } - - # Get the JMS bytes message - # - # + return - Returns the java reference to the jms bytes message - function getJmsMessage() returns handle { - return self.jmsMessage; - } - -}; - -function getBodyLength(handle message) returns int | error = @java:Method { - class: "javax.jms.BytesMessage" -} external; - -function readBoolean(handle message) returns boolean | error = @java:Method { - class: "javax.jms.BytesMessage" -} external; - -function readByte(handle message) returns byte | error = @java:Method { - class: "javax.jms.BytesMessage" -} external; - -function readBytes(handle message) returns byte[] | error { - return trap readJavaBytes(message); -} - -function readJavaBytes(handle message) returns byte[] = @java:Method { - class: "org.ballerinalang.java.jms.JmsBytesMessageUtils" -} external; - -function readPortionOfBytes(handle message, int length) returns byte[] | error { - return trap readPortionOfJavaBytes(message, length); -} - -function readPortionOfJavaBytes(handle message, int length) returns byte[] = @java:Method { - class: "org.ballerinalang.java.jms.JmsBytesMessageUtils" -} external; - -//function readChar(handle message) returns int | error = @java:Method { -// class: "javax.jms.BytesMessage" -//} external; - -function readDouble(handle message) returns float | error = @java:Method { - class: "javax.jms.BytesMessage" -} external; - -function readFloat(handle message) returns float | error = @java:Method { - class: "javax.jms.BytesMessage" -} external; - -function readInt(handle message) returns int | error = @java:Method { - class: "javax.jms.BytesMessage" -} external; - -function readLong(handle message) returns int | error = @java:Method { - class: "javax.jms.BytesMessage" -} external; - -function readShort(handle message) returns int | error = @java:Method { - class: "javax.jms.BytesMessage" -} external; - -function readUnsignedByte(handle message) returns int | error = @java:Method { - class: "javax.jms.BytesMessage" -} external; - -function readUnsignedShort(handle message) returns int | error = @java:Method { - class: "javax.jms.BytesMessage" -} external; - -function readUTF(handle message) returns handle | error = @java:Method { - class: "javax.jms.BytesMessage" -} external; - -function reset(handle message) returns error? = @java:Method { - class: "javax.jms.BytesMessage" -} external; - -function writeBoolean(handle message, boolean value) returns error? = @java:Method { - class: "javax.jms.BytesMessage" -} external; - -function writeByte(handle message, byte value) returns error? = @java:Method { - class: "javax.jms.BytesMessage" -} external; - -function writeBytes(handle message, byte[] value) returns error? = @java:Method { - class: "org.ballerinalang.java.jms.JmsBytesMessageUtils" -} external; - -function writePortionOfBytes(handle message, byte[] value, int offset, int length) returns error? = @java:Method { - class: "org.ballerinalang.java.jms.JmsBytesMessageUtils" -} external; - -//function writeChar(handle message, handle value) returns error? = @java:Method { -// class: "javax.jms.BytesMessage" -//} external; - -function writeDouble(handle message, float value) returns error? = @java:Method { - class: "javax.jms.BytesMessage" -} external; - -function writeFloat(handle message, float value) returns error? = @java:Method { - class: "javax.jms.BytesMessage" -} external; - -function writeInt(handle message, int value) returns error? = @java:Method { - class: "javax.jms.BytesMessage" -} external; - -function writeLong(handle message, int value) returns error? = @java:Method { - class: "javax.jms.BytesMessage" -} external; - -function writeShort(handle message, int value) returns error? = @java:Method { - class: "javax.jms.BytesMessage" -} external; - -function writeUTF(handle message, handle value) returns error? = @java:Method { - class: "javax.jms.BytesMessage" -} external; diff --git a/java.jms/src/java.jms/map_message.bal b/java.jms/src/java.jms/map_message.bal deleted file mode 100644 index a3236e92..00000000 --- a/java.jms/src/java.jms/map_message.bal +++ /dev/null @@ -1,661 +0,0 @@ -// Copyright (c) 2019 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -// -// WSO2 Inc. licenses this file to you under the Apache License, -// Version 2.0 (the "License"); you may not use this file except -// in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -import ballerina/java; - -# Represent the 'MapMessage' used to send and receive content from the a JMS provider. -# -# Most message-oriented middleware (MOM) products treat messages as lightweight entities that consist of a header -# and a body. The header contains fields used for message routing and identification; the body contains the -# application data being sent. -public type MapMessage client object { - - // Add a reference to the `AbstractMessage` object type. - *AbstractMessage; - - # Initialized a `MapMessage` object. - # - # + handle - The java reference to the jms text message. - function init(handle mapMessage) { - self.jmsMessage = mapMessage; - } - - # Get the boolean value by given name. - # - # + name - The name of the boolean - # + return - Returns the boolean value or an error if it fails. - public function getBoolean(string name) returns boolean | error { - return getBoolean(self.jmsMessage, java:fromString(name)); - } - - # Get the byte value by given name. - # - # + name - The name of the byte - # + return - Returns the byte value or an error if it fails. - public function getByte(string name) returns byte | error { - return getByte(self.jmsMessage, java:fromString(name)); - } - - # Get the byte array by given name. - # - # + name - The name of the byte array - # + return - Returns the byte array or an error if it fails. - public function getBytes(string name) returns byte[] | error { - return getBytes(self.jmsMessage, java:fromString(name)); - } - -// # Get the char value by given name. -// # -// # + return - Returns the char value or an error if it fails. -// public function getChar(string name) returns string | error { -// handle|error val = getChar(self.jmsMessage, java:fromString(name)); -// if (val is handle) { -// return java:toString(val); -// } else { -// return val; -// } -// } - - - # Get the double value by given name. - # - # + name - The name of the double - # + return - Returns the double value or an error if it fails. - public function getDouble(string name) returns float | error { - return getDouble(self.jmsMessage, java:fromString(name)); - } - - # Get the float value by given name. - # - # + name - The name of the float - # + return - Returns the float value or an error if it fails. - public function getFloat(string name) returns float | error { - return getFloat(self.jmsMessage, java:fromString(name)); - } - - # Get the int value by given name. - # - # + name - The name of the int - # + return - Returns the int value or an error if it fails. - public function getInt(string name) returns int | error { - return getInt(self.jmsMessage, java:fromString(name)); - } - - # Get the long value by given name. - # - # + name - The name of the long - # + return - Returns the long value or an error if it fails. - public function getLong(string name) returns int | error { - return getLong(self.jmsMessage, java:fromString(name)); - } - - # Get all the names in the MapMessage object. - # - # + return - Returns the string[] or an error if it fails. - public function getMapNames() returns string[] | error { - return getMapNames(self.jmsMessage); - } - - # Get the short value by given name. - # - # + name - The name of the short - # + return - Returns the short value or an error if it fails. - public function getShort(string name) returns int | error { - return getShort(self.jmsMessage, java:fromString(name)); - } - - # Get the string value by given name. - # - # + name - The name of the string - # + return - Returns the string value or an error if it fails. - public function getString(string name) returns string? | error { - handle|error val = getString(self.jmsMessage, java:fromString(name)); - if(val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Check whether an item exists in this MapMessage. - # - # + name - The name of the item to test - # + return - Returns the item exists or an error if it fails. - public function itemExists(string name) returns boolean | error { - return itemExists(self.jmsMessage, java:fromString(name)); - } - - # Set a boolean value with the specified name. - # - # + name - The name of the boolean - # + value - The boolean value to set in the Map - # + return - Returns an error if it fails. - public function setBoolean(string name, boolean value) returns error? { - return setBoolean(self.jmsMessage, java:fromString(name), value); - } - - # Set a byte value with the specified name. - # - # + name - the name of the byte - # + value - The byte value to set in the Map - # + return - Returns an error if it fails. - public function setByte(string name, byte value) returns error? { - return setByte(self.jmsMessage, java:fromString(name), value); - } - - # Set a byte array with the specified name. - # - # + name - The name of the byte array - # + value - The byte array value to set in the Map - # + offset - The initial offset within the byte array - # + length - The number of bytes to use - # + return - Returns an error if it fails. - public function setBytes(string name, byte[] value, int? offset = (), int? length = ()) returns error? { - if(offset is int && length is int) { - // return setPortionOfBytes(self.jmsMessage, java:fromString(name), value, offset, length); - } else { - // return setBytes(self.jmsMessage, java:fromString(name), value); - } - } - -// # Set a char value with the specified name. -// # -// # + name - The name of the Unicode character -// # + value - The Unicode character value to set in the Map -// # + return - Returns an error if it fails. -// public function setChar(string name, string value) returns error? { -// return setChar(self.jmsMessage, java:fromString(name), java:fromString(value)); -// } - - # Set a double value with the specified name. - # - # + name - The name of the double - # + value - The double value to set in the Map - # + return - Returns an error if it fails. - public function setDouble(string name, float value) returns error? { - return setDouble(self.jmsMessage, java:fromString(name), value); - } - - # Set a float value with the specified name. - # - # + name - The name of the float - # + value - The float value to set in the Map - # + return - Returns an error if it fails. - public function setFloat(string name, float value) returns error? { - return setFloat(self.jmsMessage, java:fromString(name), value); - } - - # Set a int value with the specified name. - # - # + name - The name of the int - # + value - The int value to set in the Map - # + return - Returns an error if it fails. - public function setInt(string name, int value) returns error? { - return setInt(self.jmsMessage, java:fromString(name), value); - } - - # Set a long value with the specified name. - # - # + name - The name of the long - # + value - The long value to set in the Map - # + return - Returns an error if it fails. - public function setLong(string name, int value) returns error? { - return setLong(self.jmsMessage, java:fromString(name), value); - } - - # Set a short value with the specified name. - # - # + name - The name of the short - # + value - The short value to set in the Map - # + return - Returns an error if it fails. - public function setShort(string name, int value) returns error? { - return setShort(self.jmsMessage, java:fromString(name), value); - } - - # Set a string value with the specified name. - # - # + name - The name of the string - # + value - The string value to set in the Map - # + return - Returns an error if it fails. - public function setString(string name, string value) returns error? { - return setString(self.jmsMessage, java:fromString(name), java:fromString(value)); - } - - # Acknowledges the reception of this message. This is used when the consumer has chosen CLIENT_ACKNOWLEDGE as its - # acknowledgment mode. - # - # + return - If an error occurred while acknowledging the message. - public remote function acknowledge() returns error? { - return acknowledge(self.jmsMessage); - } - - # Clears out the message body. - # - # + return - If an error occurred while clearing out the message properties. - public function clearBody() returns error? { - return clearBody(self.jmsMessage); - } - - # Clears a message's properties. - # - # + return - If an error occurred while clearing out the message properties. - public function clearProperties() returns error? { - return clearProperties(self.jmsMessage); - } - - # Get the given boolean property. - # - # + name - The name of the boolean property - # + return - Returns the boolean value or an error if it fails. - public function getBooleanProperty(string name) returns boolean | error { - return getBooleanProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given byte property. - # - # + name - The name of the byte property - # + return - Returns the byte value or an error if it fails. - public function getByteProperty(string name) returns byte | error { - return getByteProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given double property. - # - # + name - The name of the double property - # + return - Returns the double value or an error if it fails. - public function getDoubleProperty(string name) returns float | error { - return getDoubleProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given float property. - # - # + name - The name of the float property - # + return - Returns the float value or an error if it fails. - public function getFloatProperty(string name) returns float | error { - return getFloatProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given int property. - # - # + name - The name of the int property - # + return - Returns the int value or an error if it fails. - public function getIntProperty(string name) returns int | error { - return getIntProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the message correlation ID. - # - # + return - Returns the message correlation ID or an error if it fails. - public function getJMSCorrelationID() returns string? | error { - handle|error val = getJMSCorrelationID(self.jmsMessage); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Get the message correlation ID as an array of bytes. - # - # + return - Returns the message correlation ID as an byte array or an error if it fails. - public function getJMSCorrelationIDAsBytes() returns byte[] | error { - return getJMSCorrelationIDAsBytes(self.jmsMessage); - } - - # Get the message delivery mode. - # - # + return - Returns the message delivery mode or an error if it fails. - public function getJMSDeliveryMode() returns int | error { - return getJMSDeliveryMode(self.jmsMessage); - } - - # Get the message delivery time. - # - # + return - Returns the message delivery time or an error if it fails. - public function getJMSDeliveryTime() returns int | error { - return getJMSDeliveryTime(self.jmsMessage); - } - - # Get the message destination object. - # - # + return - Returns the message destination object or an error if it fails. - public function getJMSDestination() returns Destination | error { - handle|error val = getJMSDestination(self.jmsMessage); - if (val is handle) { - return getDestination(val); - } else { - return val; - } - } - - # Get the message expiration time. - # - # + return - Returns the message expiration time or an error if it fails. - public function getJMSExpiration() returns int | error { - return getJMSExpiration(self.jmsMessage); - } - - # Get the message ID. - # - # + return - Returns the message ID or an error if it fails. - public function getJMSMessageID() returns string? | error { - handle|error val = getJMSMessageID(self.jmsMessage); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Get the message priority. - # - # + return - Returns the message priority or an error if it fails. - public function getJMSPriority() returns int | error { - return getJMSPriority(self.jmsMessage); - } - - # Get an indication whether the message being redelivered. - # - # + return - Returns the message redelivered or an error if it fails. - public function getJMSRedelivered() returns boolean | error { - return getJMSRedelivered(self.jmsMessage); - } - - # Get the Destination object to which a reply to this message should be sent. - # - # + return - Returns the reply to destination or an error if it fails. - public function getJMSReplyTo() returns Destination | error { - handle|error val = getJMSReplyTo(self.jmsMessage); - if (val is handle) { - return getDestination(val); - } else { - return val; - } - } - - # Get the message timestamp. - # - # + return - Returns the message timestamp or an error if it fails. - public function getJMSTimestamp() returns int | error { - return getJMSTimestamp(self.jmsMessage); - } - - # Get the message type identifier. - # - # + return - Returns the message type or an error if it fails. - public function getJMSType() returns (string|error)? { - handle|error val = getJMSType(self.jmsMessage); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Get the given long property. - # - # + name - The name of the long property - # + return - Returns the int value or an error if it fails. - public function getLongProperty(string name) returns int | error { - return getLongProperty(self.jmsMessage, java:fromString(name)); - } - - # Get string array of property names. - # - # + return - Returns the string array of property names or an error if it fails. - public function getPropertyNames() returns string[] | error { - return getPropertyNames(self.jmsMessage); - } - - # Get the given short property. - # - # + name - The name of the short property - # + return - Returns the int value or an error if it fails. - public function getShortProperty(string name) returns int | error { - return getShortProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given string property. - # - # + name - The name of the string property - # + return - Returns the string value or an error if it fails. - public function getStringProperty(string name) returns (string|error)? { - handle|error val = getStringProperty(self.jmsMessage, java:fromString(name)); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Indicate whether a property value exists. - # - # + name - The name of the property to test - # + return - Returns true if the property exists or an error if it fails. - public function propertyExists(string name) returns boolean | error { - return propertyExists(self.jmsMessage, java:fromString(name)); - } - - # Set the boolean value with the specified name into the message. - # - # + name - The name of the boolean property - # + value - The boolean property value to set - # + return - Returns an error if it fails. - public function setBooleanProperty(string name, boolean value) returns error? { - return setBooleanProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the byte value with the specified name into the message. - # - # + name - The name of the byte property - # + value - The byte property value to set - # + return - Returns an error if it fails. - public function setByteProperty(string name, byte value) returns error? { - return setByteProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the double value with the specified name into the message. - # - # + name - The name of the double property - # + value - The double property value to set - # + return - Returns an error if it fails. - public function setDoubleProperty(string name, float value) returns error? { - return setDoubleProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the float value with the specified name into the message. - # - # + name - The name of the float property - # + value - The float property value to set - # + return - Returns an error if it fails. - public function setFloatProperty(string name, float value) returns error? { - return setFloatProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the int value with the specified name into the message. - # - # + name - The name of the int property - # + value - The int property value to set - # + return - Returns an error if it fails. - public function setIntProperty(string name, int value) returns error? { - return setIntProperty(self.jmsMessage, java:fromString(name), value); - } - - # Sets the correlation id for the message. - # - # + correlationId - correlation id of a message as a string - # + return - Returns an error if it fails. - public function setJMSCorrelationID(string correlationId) returns error? { - return setJMSCorrelationID(self.jmsMessage, java:fromString(correlationId)); - } - - # Sets the correlation id an array of bytes for the message. - # - # + correlationId - correlation id value as an array of bytes - # + return - Returns an error if it fails. - public function setJMSCorrelationIDAsBytes(byte[] correlationId) returns error? { - return setJMSCorrelationIDAsBytes(self.jmsMessage, correlationId); - } - - # Set the reply destination to the message which a reply should send. - # - # + replyTo - Destination to which to send a response to this message - # + return - Returns an error if it fails. - public function setJMSReplyTo(Destination replyTo) returns error? { - return setJMSReplyTo(self.jmsMessage, replyTo.getJmsDestination()); - } - - # Set the message type. - # - # + jmsType - The message type - # + return - Returns an error if it fails. - public function setJMSType(string jmsType) returns error? { - return setJMSType(self.jmsMessage, java:fromString(jmsType)); - } - - # Set the long value with the specified name into the message. - # - # + name - The name of the long property - # + value - The long property value to set - # + return - Returns an error if it fails. - public function setLongProperty(string name, int value) returns error? { - return setLongProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the short value with the specified name into the message. - # - # + name - The name of the short property - # + value - The short property value to set - # + return - Returns an error if it fails. - public function setShortProperty(string name, int value) returns error? { - return setShortProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the string value with the specified name into the message. - # - # + name - The name of the string property - # + value - The string property value to set - # + return - Returns an error if it fails. - public function setStringProperty(string name, string value) returns error? { - return setStringProperty(self.jmsMessage, java:fromString(name), java:fromString(value)); - } - - # Get the JMS map message - # - # + return - Returns the java reference to the jms map message - function getJmsMessage() returns handle { - return self.jmsMessage; - } - -}; - -function getBoolean(handle message, handle name) returns boolean | error = @java:Method { - class: "javax.jms.MapMessage" -} external; - -function getByte(handle message, handle name) returns byte | error = @java:Method { - class: "javax.jms.MapMessage" -} external; - -function getBytes(handle message, handle name) returns byte[] | error = @java:Method { - class: "org.ballerinalang.java.jms.JmsMapMessageUtils" -} external; - -//function getChar(handle message, handle name) returns int | error = @java:Method { -// class: "javax.jms.MapMessage" -//} external; - -function getDouble(handle message, handle name) returns float | error = @java:Method { - class: "javax.jms.MapMessage" -} external; - -function getFloat(handle message, handle name) returns float | error = @java:Method { - class: "javax.jms.MapMessage" -} external; - -function getInt(handle message, handle name) returns int | error = @java:Method { - class: "javax.jms.MapMessage" -} external; - -function getLong(handle message, handle name) returns int | error = @java:Method { - class: "javax.jms.MapMessage" -} external; - -function getMapNames(handle message) returns string[] | error { - return getJmsMapNames(message); -} - -function getJmsMapNames(handle message) returns string[] = @java:Method { - class: "org.ballerinalang.java.jms.JmsMapMessageUtils" -} external; - -function getShort(handle message, handle name) returns int | error = @java:Method { - class: "javax.jms.MapMessage" -} external; - -function getString(handle message, handle name) returns handle | error = @java:Method { - class: "javax.jms.MapMessage" -} external; - -function itemExists(handle message, handle name) returns boolean | error = @java:Method { - class: "javax.jms.MapMessage" -} external; - -function setBoolean(handle message, handle name, boolean value) returns error? = @java:Method { - class: "javax.jms.MapMessage" -} external; - -function setByte(handle message, handle name, byte value) returns error? = @java:Method { - class: "javax.jms.MapMessage" -} external; - -//function setBytes(handle message, handle name, byte[] value) returns error? = @java:Method { -// class: "javax.jms.MapMessage" -//} external; - -//function setPortionOfBytes(handle message, handle name, handle array, int offset, int length) returns error? = @java:Method { -// name: "setBytes", -// paramTypes: ["java.lang.String", {class:"byte", dimensions:1}, "int", "int"], -// class: "javax.jms.MapMessage" -//} external; - -//function setChar(handle message, handle name, handle value) returns error? = @java:Method { -// class: "javax.jms.MapMessage" -//} external; - -function setDouble(handle message, handle name, float value) returns error? = @java:Method { - class: "javax.jms.MapMessage" -} external; - -function setFloat(handle message, handle name, float value) returns error? = @java:Method { - class: "javax.jms.MapMessage" -} external; - -function setInt(handle message, handle name, int value) returns error? = @java:Method { - class: "javax.jms.MapMessage" -} external; - -function setLong(handle message, handle name, int value) returns error? = @java:Method { - class: "javax.jms.MapMessage" -} external; - -function setShort(handle message, handle name, int value) returns error? = @java:Method { - class: "javax.jms.MapMessage" -} external; - -function setString(handle message, handle name, handle value) returns error? = @java:Method { - class: "javax.jms.MapMessage" -} external; diff --git a/java.jms/src/java.jms/message.bal b/java.jms/src/java.jms/message.bal deleted file mode 100644 index f3ce3e2d..00000000 --- a/java.jms/src/java.jms/message.bal +++ /dev/null @@ -1,513 +0,0 @@ -// Copyright (c) 2019 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -// -// WSO2 Inc. licenses this file to you under the Apache License, -// Version 2.0 (the "License"); you may not use this file except -// in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -import ballerina/java; - -# Represent the 'Message' used to send and receive content from the a JMS provider. -# -# Most message-oriented middleware (MOM) products treat messages as lightweight entities that consist of a header -# and a body. The header contains fields used for message routing and identification; the body contains the -# application data being sent. -public type Message client object { - - // Add a reference to the `AbstractMessage` object type. - *AbstractMessage; - - # Initialized a `Message` object. - # - # + handle - The java reference to the jms message. - public function init(handle message) { - self.jmsMessage = message; - } - - # Acknowledges the reception of this message. This is used when the consumer has chosen CLIENT_ACKNOWLEDGE as its - # acknowledgment mode. - # - # + return - If an error occurred while acknowledging the message. - public remote function acknowledge() returns error? { - return acknowledge(self.jmsMessage); - } - - # Clears out the message body. - # - # + return - If an error occurred while clearing out the message properties. - public function clearBody() returns error? { - return clearBody(self.jmsMessage); - } - - # Clears a message's properties. - # - # + return - If an error occurred while clearing out the message properties. - public function clearProperties() returns error? { - return clearProperties(self.jmsMessage); - } - - # Get the given boolean property. - # - # + name - The name of the boolean property - # + return - Returns the boolean value or an error if it fails. - public function getBooleanProperty(string name) returns boolean | error { - return getBooleanProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given byte property. - # - # + name - The name of the byte property - # + return - Returns the byte value or an error if it fails. - public function getByteProperty(string name) returns byte | error { - return getByteProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given double property. - # - # + name - The name of the double property - # + return - Returns the double value or an error if it fails. - public function getDoubleProperty(string name) returns float | error { - return getDoubleProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given float property. - # - # + name - The name of the float property - # + return - Returns the float value or an error if it fails. - public function getFloatProperty(string name) returns float | error { - return getFloatProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given int property. - # - # + name - The name of the int property - # + return - Returns the int value or an error if it fails. - public function getIntProperty(string name) returns int | error { - return getIntProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the message correlation ID. - # - # + return - Returns the message correlation ID or an error if it fails. - public function getJMSCorrelationID() returns string? | error { - handle|error val = getJMSCorrelationID(self.jmsMessage); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Get the message correlation ID as an array of bytes. - # - # + return - Returns the message correlation ID as an byte array or an error if it fails. - public function getJMSCorrelationIDAsBytes() returns byte[] | error { - return getJMSCorrelationIDAsBytes(self.jmsMessage); - } - - # Get the message delivery mode. - # - # + return - Returns the message delivery mode or an error if it fails. - public function getJMSDeliveryMode() returns int | error { - return getJMSDeliveryMode(self.jmsMessage); - } - - # Get the message delivery time. - # - # + return - Returns the message delivery time or an error if it fails. - public function getJMSDeliveryTime() returns int | error { - return getJMSDeliveryTime(self.jmsMessage); - } - - # Get the message destination object. - # - # + return - Returns the message destination object or an error if it fails. - public function getJMSDestination() returns Destination | error { - handle|error val = getJMSDestination(self.jmsMessage); - if (val is handle) { - return getDestination(val); - } else { - return val; - } - } - - # Get the message expiration time. - # - # + return - Returns the message expiration time or an error if it fails. - public function getJMSExpiration() returns int | error { - return getJMSExpiration(self.jmsMessage); - } - - # Get the message ID. - # - # + return - Returns the message ID or an error if it fails. - public function getJMSMessageID() returns string? | error { - handle|error val = getJMSMessageID(self.jmsMessage); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Get the message priority. - # - # + return - Returns the message priority or an error if it fails. - public function getJMSPriority() returns int | error { - return getJMSPriority(self.jmsMessage); - } - - # Get an indication whether the message being redelivered. - # - # + return - Returns the message redelivered or an error if it fails. - public function getJMSRedelivered() returns boolean | error { - return getJMSRedelivered(self.jmsMessage); - } - - # Get the Destination object to which a reply to this message should be sent. - # - # + return - Returns the reply to destination or an error if it fails. - public function getJMSReplyTo() returns Destination | error { - handle|error val = getJMSReplyTo(self.jmsMessage); - if (val is handle) { - return getDestination(val); - } else { - return val; - } - } - - # Get the message timestamp. - # - # + return - Returns the message timestamp or an error if it fails. - public function getJMSTimestamp() returns int | error { - return getJMSTimestamp(self.jmsMessage); - } - - # Get the message type identifier. - # - # + return - Returns the message type or an error if it fails. - public function getJMSType() returns (string|error)? { - handle|error val = getJMSType(self.jmsMessage); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Get the given long property. - # - # + name - The name of the long property - # + return - Returns the int value or an error if it fails. - public function getLongProperty(string name) returns int | error { - return getLongProperty(self.jmsMessage, java:fromString(name)); - } - - # Get string array of property names. - # - # + return - Returns the string array of property names or an error if it fails. - public function getPropertyNames() returns string[] | error { - return getPropertyNames(self.jmsMessage); - } - - # Get the given short property. - # - # + name - The name of the short property - # + return - Returns the int value or an error if it fails. - public function getShortProperty(string name) returns int | error { - return getShortProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given string property. - # - # + name - The name of the string property - # + return - Returns the string value or an error if it fails. - public function getStringProperty(string name) returns (string|error)? { - handle|error val = getStringProperty(self.jmsMessage, java:fromString(name)); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Indicate whether a property value exists. - # - # + name - The name of the property to test - # + return - Returns true if the property exists or an error if it fails. - public function propertyExists(string name) returns boolean | error { - return propertyExists(self.jmsMessage, java:fromString(name)); - } - - # Set the boolean value with the specified name into the message. - # - # + name - The name of the boolean property - # + value - The boolean property value to set - # + return - Returns an error if it fails. - public function setBooleanProperty(string name, boolean value) returns error? { - return setBooleanProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the byte value with the specified name into the message. - # - # + name - The name of the byte property - # + value - The byte property value to set - # + return - Returns an error if it fails. - public function setByteProperty(string name, byte value) returns error? { - return setByteProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the double value with the specified name into the message. - # - # + name - The name of the double property - # + value - The double property value to set - # + return - Returns an error if it fails. - public function setDoubleProperty(string name, float value) returns error? { - return setDoubleProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the float value with the specified name into the message. - # - # + name - The name of the float property - # + value - The float property value to set - # + return - Returns an error if it fails. - public function setFloatProperty(string name, float value) returns error? { - return setFloatProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the int value with the specified name into the message. - # - # + name - The name of the int property - # + value - The int property value to set - # + return - Returns an error if it fails. - public function setIntProperty(string name, int value) returns error? { - return setIntProperty(self.jmsMessage, java:fromString(name), value); - } - - # Sets the correlation id for the message. - # - # + correlationId - correlation id of a message as a string - # + return - Returns an error if it fails. - public function setJMSCorrelationID(string correlationId) returns error? { - return setJMSCorrelationID(self.jmsMessage, java:fromString(correlationId)); - } - - # Sets the correlation id an array of bytes for the message. - # - # + correlationId - correlation id value as an array of bytes - # + return - Returns an error if it fails. - public function setJMSCorrelationIDAsBytes(byte[] correlationId) returns error? { - return setJMSCorrelationIDAsBytes(self.jmsMessage, correlationId); - } - - # Set the reply destination to the message which a reply should send. - # - # + replyTo - Destination to which to send a response to this message - # + return - Returns an error if it fails. - public function setJMSReplyTo(Destination replyTo) returns error? { - return setJMSReplyTo(self.jmsMessage, replyTo.getJmsDestination()); - } - - # Set the message type. - # - # + jmsType - The message type - # + return - Returns an error if it fails. - public function setJMSType(string jmsType) returns error? { - return setJMSType(self.jmsMessage, java:fromString(jmsType)); - } - - # Set the long value with the specified name into the message. - # - # + name - The name of the long property - # + value - The long property value to set - # + return - Returns an error if it fails. - public function setLongProperty(string name, int value) returns error? { - return setLongProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the short value with the specified name into the message. - # - # + name - The name of the short property - # + value - The short property value to set - # + return - Returns an error if it fails. - public function setShortProperty(string name, int value) returns error? { - return setShortProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the string value with the specified name into the message. - # - # + name - The name of the string property - # + value - The string property value to set - # + return - Returns an error if it fails. - public function setStringProperty(string name, string value) returns error? { - return setStringProperty(self.jmsMessage, java:fromString(name), java:fromString(value)); - } - - # Get the JMS message - # - # + return - Returns the java reference to the jms text message - function getJmsMessage() returns handle { - return self.jmsMessage; - } -}; - -function acknowledge(handle message) returns error? = @java:Method { - class: "javax.jms.Message" -} external; - -function clearBody(handle message) returns error? = @java:Method { - class: "javax.jms.Message" -} external; - -function clearProperties(handle message) returns error? = @java:Method { - class: "javax.jms.Message" -} external; - -function getBooleanProperty(handle message, handle name) returns boolean | error = @java:Method { - class: "javax.jms.Message" -} external; - -function getByteProperty(handle message, handle name) returns byte | error = @java:Method { - class: "javax.jms.Message" -} external; - -function getDoubleProperty(handle message, handle name) returns float | error = @java:Method { - class: "javax.jms.Message" -} external; - -function getFloatProperty(handle message, handle name) returns float | error = @java:Method { - class: "javax.jms.Message" -} external; - -function getIntProperty(handle message, handle name) returns int | error = @java:Method { - class: "javax.jms.Message" -} external; - -function getJMSCorrelationID(handle message) returns handle | error = @java:Method { - class: "javax.jms.Message" -} external; - -function getJMSCorrelationIDAsBytes(handle message) returns byte[] | error = @java:Method { - class: "org.ballerinalang.java.jms.JmsMessageUtils" -} external; - -function getJMSDeliveryMode(handle message) returns int | error = @java:Method { - class: "javax.jms.Message" -} external; - -function getJMSDeliveryTime(handle message) returns int | error = @java:Method { - class: "javax.jms.Message" -} external; - -function getJMSDestination(handle message) returns handle | error = @java:Method { - class: "javax.jms.Message" -} external; - -function getJMSExpiration(handle message) returns int | error = @java:Method { - class: "javax.jms.Message" -} external; - -function getJMSMessageID(handle message) returns handle | error = @java:Method { - class: "javax.jms.Message" -} external; - -function getJMSPriority(handle message) returns int | error = @java:Method { - class: "javax.jms.Message" -} external; - -function getJMSRedelivered(handle message) returns boolean | error = @java:Method { - class: "javax.jms.Message" -} external; - -function getJMSReplyTo(handle message) returns handle | error = @java:Method { - class: "javax.jms.Message" -} external; - -function getJMSTimestamp(handle message) returns int | error = @java:Method { - class: "javax.jms.Message" -} external; - -function getJMSType(handle message) returns handle | error = @java:Method { - class: "javax.jms.Message" -} external; - -function getLongProperty(handle message, handle name) returns int | error = @java:Method { - class: "javax.jms.Message" -} external; - -function getPropertyNames(handle message) returns string[] | error { - return trap getJmsPropertyNames(message); -} - -function getJmsPropertyNames(handle message) returns string[] = @java:Method { - class: "org.ballerinalang.java.jms.JmsMessageUtils" -} external; - -function getShortProperty(handle message, handle name) returns int | error = @java:Method { - class: "javax.jms.Message" -} external; - -function getStringProperty(handle message, handle name) returns handle | error = @java:Method { - class: "javax.jms.Message" -} external; - -function propertyExists(handle message, handle name) returns boolean | error = @java:Method { - class: "javax.jms.Message" -} external; - -function setBooleanProperty(handle message, handle name, boolean value) returns error? = @java:Method { - class: "javax.jms.Message" -} external; - -function setByteProperty(handle message, handle name, byte value) returns error? = @java:Method { - class: "javax.jms.Message" -} external; - -function setDoubleProperty(handle message, handle name, float value) returns error? = @java:Method { - class: "javax.jms.Message" -} external; - -function setFloatProperty(handle message, handle name, float value) returns error? = @java:Method { - class: "javax.jms.Message" -} external; - -function setIntProperty(handle message, handle name, int value) returns error? = @java:Method { - class: "javax.jms.Message" -} external; - -function setJMSCorrelationID(handle message, handle correlationId) returns error? = @java:Method { - class: "javax.jms.Message" -} external; - -function setJMSCorrelationIDAsBytes(handle message, byte[] correlationId) returns error? = @java:Method { - class: "org.ballerinalang.java.jms.JmsMessageUtils" -} external; - -function setJMSReplyTo(handle message, handle destination) returns error? = @java:Method { - class: "javax.jms.Message" -} external; - -function setJMSType(handle message, handle jmsType) returns error? = @java:Method { - class: "javax.jms.Message" -} external; - -function setLongProperty(handle message, handle name, int value) returns error? = @java:Method { - class: "javax.jms.Message" -} external; - -function setShortProperty(handle message, handle name, int value) returns error? = @java:Method { - class: "javax.jms.Message" -} external; - -function setStringProperty(handle message, handle name, handle value) returns error? = @java:Method { - class: "javax.jms.Message" -} external; diff --git a/java.jms/src/java.jms/message_consumer.bal b/java.jms/src/java.jms/message_consumer.bal deleted file mode 100644 index fc12d8b6..00000000 --- a/java.jms/src/java.jms/message_consumer.bal +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright (c) 2018 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -// -// WSO2 Inc. licenses this file to you under the Apache License, -// Version 2.0 (the "License"); you may not use this file except -// in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -import ballerina/log; -import ballerina/java; -import ballerina/'lang\.object as lang; -import ballerina/observe; - -observe:Gauge consumerGauge = new(ACTIVE_JMS_CONSUMERS); - -public type MessageConsumer client object { - - *lang:Listener; - private handle jmsConsumer = JAVA_NULL; - - function init(handle jmsMessageConsumer) { - self.jmsConsumer = jmsMessageConsumer; - registerAndIncrementGauge(consumerGauge); - } - - # Binds the queue receiver endpoint to a service. - # - # + s - The service instance. - # + name - Name of the service. - # + return - Returns nil or an error upon failure to register the listener. - public function __attach(service s, string? name = ()) returns error? { - string n = (name is string)? name: ""; - log:printDebug("Message consumer attached to service" + n); - return setMessageListener(self.jmsConsumer, s); - } - - # Starts the endpoint. - # - # + return - Returns nil or an error upon failure to start. - public function __start() returns error? { - return; - } - - public function __gracefulStop() returns error? { - return self.closeConsumer(); - } - - public function __immediateStop() returns error? { - } - - public function __detach(service s) returns error? { - } - - # Stops consuming messages through the QueueListener. - # - # + return - Returns nil or an error upon failure to close the queue receiver. - public function __stop() returns error? { - return self.closeConsumer(); - } - - private function closeConsumer() returns error? { - decrementGauge(consumerGauge); - return self->close(); - } - - public remote function receive(int timeoutMillis = 0) returns Message|()|error { - var response = receiveJmsMessage(self.jmsConsumer, timeoutMillis); - registerAndIncrementCounter(new observe:Counter(TOTAL_JMS_MESSAGES_RECEIVED)); - if (response is handle) { - if (java:isNull(response)) { - return (); - } else { - return self.getBallerinaMessage(response); - } - } else { - return response; - } - } - - public remote function receiveNoWait() returns Message|()|error { - handle|error response = receiveNoWaitJmsMessage(self.jmsConsumer); - if (response is handle) { - if (java:isNull(response)) { - return (); - } else { - return self.getBallerinaMessage(response); - } - } else { - return response; - } - } - - public remote function close() returns error? { - return closeJmsConsumer(self.jmsConsumer); - } - - private function getBallerinaMessage(handle jmsMessage) returns Message|error { - if (isTextMessage(jmsMessage)) { - return new TextMessage(jmsMessage); - } else if (isMapMessage(jmsMessage)) { - return new MapMessage(jmsMessage); - } else if (isBytesMessage(jmsMessage)) { - return new BytesMessage(jmsMessage); - } else if (isStreamMessage(jmsMessage)) { - return new StreamMessage(jmsMessage); - } else { - return new Message(jmsMessage); - } - } - - function getJmsConsumer() returns handle { - return self.jmsConsumer; - } -}; - -function receiveJmsMessage(handle jmsMessageConsumer, int timeout) returns handle|error = @java:Method { - name: "receive", - paramTypes: ["long"], - class: "javax.jms.MessageConsumer" -} external; - -function receiveNoWaitJmsMessage(handle jmsMessageConsumer) returns handle|error = @java:Method { - name: "receiveNoWait", - class: "javax.jms.MessageConsumer" -} external; - -function isTextMessage(handle jmsMessage) returns boolean = @java:Method { - class: "org.ballerinalang.java.jms.JmsMessageUtils" -} external; - -function isMapMessage(handle jmsMessage) returns boolean = @java:Method { - class: "org.ballerinalang.java.jms.JmsMessageUtils" -} external; - -function isBytesMessage(handle jmsMessage) returns boolean = @java:Method { - class: "org.ballerinalang.java.jms.JmsMessageUtils" -} external; - -function isStreamMessage(handle jmsMessage) returns boolean = @java:Method { - class: "org.ballerinalang.java.jms.JmsMessageUtils" -} external; - -function closeJmsConsumer(handle jmsConsumer) returns error? = @java:Method { - name: "close", - class: "javax.jms.MessageConsumer" -} external; - -function setMessageListener(handle jmsConsumer, service serviceObject) returns error? = @java:Method { - class: "org.ballerinalang.java.jms.JmsMessageListenerUtils" -} external; diff --git a/java.jms/src/java.jms/message_producer.bal b/java.jms/src/java.jms/message_producer.bal deleted file mode 100644 index a0e96b7f..00000000 --- a/java.jms/src/java.jms/message_producer.bal +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) 2018 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -// -// WSO2 Inc. licenses this file to you under the Apache License, -// Version 2.0 (the "License"); you may not use this file except -// in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -import ballerina/java; -import ballerina/observe; - -# JMS Message Producer client object to send messages to both queues and topics. -# -public type MessageProducer client object { - - private handle jmsProducer = JAVA_NULL; - - # Initialize the Message Producer client object - # - # + jmsProducer - reference to java MessageProducer object - public function init(handle jmsProducer) returns error? { - self.jmsProducer = jmsProducer; - } - - # Sends a message to the JMS provider - # - # + message - Message to be sent to the JMS provider - # + return - Error if unable to send the message to the queue - public remote function send(Message message) returns error? { - registerAndIncrementCounter(new observe:Counter(TOTAL_JMS_MESSAGES_SENT)); - return send(self.jmsProducer, message.getJmsMessage()); - } - - # Sends a message to a given destination of the JMS provider - # - # + destination - Destination used for the message sender - # + message - Message to be sent to the JMS provider - # + return - Error if sending to the given destination fails - public remote function sendTo(Destination destination, Message message) returns error? { - return sendToDestination(self.jmsProducer, destination.getJmsDestination(), message.getJmsMessage()); - } -}; - -function send(handle messageProducer, handle message) returns error? = @java:Method { - name: "send", - paramTypes: ["javax.jms.Message"], - class: "javax.jms.MessageProducer" -} external; - -function sendToDestination(handle messageProducer, handle destination, handle message) returns error? = @java:Method { - name: "send", - paramTypes: ["javax.jms.Destination", "javax.jms.Message"], - class: "javax.jms.MessageProducer" -} external; diff --git a/java.jms/src/java.jms/session.bal b/java.jms/src/java.jms/session.bal deleted file mode 100644 index 934ff7a6..00000000 --- a/java.jms/src/java.jms/session.bal +++ /dev/null @@ -1,402 +0,0 @@ -// Copyright (c) 2018 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -// -// WSO2 Inc. licenses this file to you under the Apache License, -// Version 2.0 (the "License"); you may not use this file except -// in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -import ballerina/log; -import ballerina/java; -import ballerina/observe; - -# Represents the JMS session. -# -# + config - Stores the configurations related to a JMS session. -public type Session client object { - - private SessionConfiguration config; - private handle jmsSession = JAVA_NULL; - - # The default constructor of the JMS session. - public function init(handle connection, SessionConfiguration sessionConfig) returns error? { - self.config = sessionConfig; - return self.createSession(connection); - } - - private function createSession(handle jmsConnection) returns error? { - handle ackModeJString = java:fromString(self.config.acknowledgementMode); - self.jmsSession = check createJmsSession(jmsConnection, ackModeJString); - registerAndIncrementCounter(new observe:Counter(TOTAL_JMS_SESSIONS)); - } - - # Unsubscribe a durable subscription that has been created by a client. - # It is erroneous for a client to delete a durable subscription while there is an active (not closed) consumer - # for the subscription, or while a consumed message being part of a pending transaction or has not been - # acknowledged in the session. - # - # + subscriptionId - The name, which is used to identify the subscription. - # + return - Cancels the subscription. - public remote function unsubscribe(string subscriptionId) returns error? { - registerAndIncrementCounter(new observe:Counter(TOTAL_JMS_UNSUBSCRIBES)); - return unsubscribeJmsSubscription(self.jmsSession, java:fromString(subscriptionId)); - } - - # Creates a JMS Queue, which can be used as temporary response destination. - # - # + return - Returns the JMS destination for a temporary queue or an error if it fails. - public remote function createTemporaryQueue() returns Destination|JmsError { - handle|error val = createTemporaryJmsQueue(self.jmsSession); - registerAndIncrementCounter(new observe:Counter(TOTAL_JMS_TEMPORARY_QUEUES)); - if (val is handle) { - return new TemporaryQueue(val); - } else { - return JmsError("Error occurred while creating the JMS queue.", val); - } - } - - # Creates a JMS Topic, which can be used as a temporary response destination. - # - # + return - Returns the JMS destination for a temporary topic or an error if it fails. - public function createTemporaryTopic() returns Destination|JmsError { - handle|error val = createTemporaryJmsTopic(self.jmsSession); - registerAndIncrementCounter(new observe:Counter(TOTAL_JMS_TEMPORARY_TOPICS)); - if (val is handle) { - return new TemporaryTopic(val); - } else { - return JmsError("Error occurred while creating the JMS topic.", val); - } - } - - # Creates a JMS Queue, which can be used with a message producer. - # - # + queueName - The name of the Queue. - # + return - Returns the JMS destination for a queue or an error if it fails. - public remote function createQueue(string queueName) returns Destination|error { - handle|error val = createJmsQueue(self.jmsSession, java:fromString(queueName)); - registerAndIncrementCounter(new observe:Counter(TOTAL_JMS_QUEUES)); - if (val is handle) { - return new Queue(val); - } else { - return val; - } - } - - # Creates a JMS Topic, which can be used with a message producer. - # - # + topicName - The name of the Topic. - # + return - Returns the JMS destination for a topic or an error if it fails. - public remote function createTopic(string topicName) returns Destination|error { - handle|error val = createJmsTopic(self.jmsSession, java:fromString(topicName)); - registerAndIncrementCounter(new observe:Counter(TOTAL_JMS_TOPICS)); - if (val is handle) { - return new Topic(val); - } else { - return val; - } - } - - # Get the reference to the java session object. - # - # + return - Returns jms session java reference. - function getJmsSession() returns handle { - return self.jmsSession; - } - - # Creates a JMS message. - # - # + return - Returns the JMS message or an error if it fails. - public function createMessage() returns Message|error { - handle|error val = createJmsMessage(self.jmsSession); - registerAndIncrementCounter(new observe:Counter(TOTAL_JMS_MESSAGES_CREATED)); - if (val is handle) { - Message message = new(val); - return message; - } else { - return val; - } - } - - # Creates a JMS text message. - # - # + text - The string used to initialize this message - # + return - Returns the JMS text message or an error if it fails. - public function createTextMessage(string? text = ()) returns TextMessage|error { - if (text is string) { - handle|error val = createJmsTextMessageWithText(self.jmsSession, java:fromString(text)); - registerAndIncrementCounter(new observe:Counter(TOTAL_JMS_TEXT_MESSAGES_WITH_TEXT_CREATED)); - if (val is handle) { - TextMessage textMessage = new(val); - return textMessage; - } else { - return val; - } - } else { - handle|error val = createJmsTextMessage(self.jmsSession); - registerAndIncrementCounter(new observe:Counter(TOTAL_JMS_TEXT_MESSAGES_CREATED)); - if (val is handle) { - TextMessage textMessage = new(val); - return textMessage; - } else { - return val; - } - } - } - - # Creates a JMS map message. - # - # + return - Returns the JMS map message or an error if it fails. - public function createMapMessage() returns MapMessage|error { - handle|error val = createJmsMapMessage(self.jmsSession); - registerAndIncrementCounter(new observe:Counter(TOTAL_JMS_MAP_MESSAGES_CREATED)); - if (val is handle) { - MapMessage message = new(val); - return message; - } else { - return val; - } - } - - # Creates a JMS stream message. - # - # + return - Returns the JMS stream message or an error if it fails. - public function createStreamMessage() returns StreamMessage|error { - handle|error val = createJmsStreamMessage(self.jmsSession); - registerAndIncrementCounter(new observe:Counter(TOTAL_JMS_STREAM_MESSAGES_CREATED)); - if (val is handle) { - StreamMessage message = new(val); - return message; - } else { - return val; - } - } - - # Creates a JMS byte message. - # - # + return - Returns the JMS byte message or an error if it fails. - public function createByteMessage() returns BytesMessage|error { - handle|error val = createJmsBytesMessage(self.jmsSession); - registerAndIncrementCounter(new observe:Counter("JMS_ByteMessage_total")); - if (val is handle) { - BytesMessage message = new(val); - return message; - } else { - return val; - } - } - - # Creates a MessageProducer to send messages to the specified destination. - # - # + destination - the Destination to send to, or nil if this is a producer which does not have a specified destination - # + return - Returns jms:MessageProducer - public function createProducer(Destination? destination = ()) returns MessageProducer|error { - - handle jmsDestination = (destination is Destination) ? destination.getJmsDestination(): JAVA_NULL; - handle|error v = createJmsProducer(self.jmsSession, jmsDestination); - registerAndIncrementCounter(new observe:Counter(TOTAL_JMS_PRODUCERS)); - if (v is handle) { - return new MessageProducer(v); - } else { - log:printError("Error occurred while creating producer"); - return v; - } - } - - # Creates a MessageConsumer for the specified destination. Both Queue and Topic can be used in - # the destination parameter to create a MessageConsumer. - # - # + destination - the Destination to access - # + messageSelector - only messages with properties matching the message selector expression are delivered. - # An empty string indicates that there is no message selector for the message consumer. - # + noLocal - if true, and the destination is a topic, then the MessageConsumer will not receive messages published to the topic by its own connection. - # + return - Returns a jms:MessageConsumer - public remote function createConsumer(Destination destination, string messageSelector = "", - boolean noLocal = false) returns MessageConsumer|error { - var val = createJmsConsumer(self.jmsSession, destination.getJmsDestination(), - java:fromString(messageSelector), noLocal); - registerAndIncrementCounter(new observe:Counter(TOTAL_JMS_CONSUMERS)); - if (val is handle) { - MessageConsumer consumer = new(val); - return consumer; - } else { - return val; - } - } - - # Creates an unshared durable subscription on the specified topic (if one does not already exist), - # specifying a message selector and the noLocal parameter, and creates a consumer on that durable subscription. - # - # + topic - the non-temporary Topic to subscribe to - # + subscriberName - the name used to identify this subscription - # + messageSelector - only messages with properties matching the message selector expression are added to the durable subscription. - # An empty string indicates that there is no message selector for the durable subscription. - # + noLocal - if true then any messages published to the topic using this session's connection, or any other connection - # with the same client identifier, will not be added to the durable subscription. - # + return - Returns a jms:MessageConsumer - public remote function createDurableSubscriber(Destination topic, string subscriberName, - string messageSelector = "", - boolean noLocal = false) returns MessageConsumer|error { - var val = createJmsDurableSubscriber(self.jmsSession, topic.getJmsDestination(), - java:fromString(subscriberName), - java:fromString(messageSelector), noLocal); - registerAndIncrementCounter(new observe:Counter(TOTAL_JMS_DURABLE_SUBSCRIBERS)); - if (val is handle) { - MessageConsumer consumer = new(val); - return consumer; - } else { - return val; - } - } - - # Creates a shared non-durable subscription with the specified name on the specified topic - # (if one does not already exist) specifying a message selector, and creates a consumer on that subscription. - # - # + topic - the Topic to subscribe to - # + subscriberName - the name used to identify the shared non-durable subscription - # + messageSelector - only messages with properties matching the message selector expression are added to the shared - # non-durable subscription. A value of null or an empty string indicates that there is no message - # selector for the shared non-durable subscription. - # + return - Returns a jms:MessageConsumer - public remote function createSharedConsumer(Destination topic, string subscriberName, - string messageSelector = "") returns MessageConsumer|error { - var val = createJmsSharedConsumer(self.jmsSession, topic.getJmsDestination(), - java:fromString(subscriberName), java:fromString(messageSelector)); - registerAndIncrementCounter(new observe:Counter(TOTAL_JMS_SHARED_CONSUMERS)); - if (val is handle) { - MessageConsumer consumer = new(val); - return consumer; - } else { - return val; - } - } - - # Creates a shared durable subscription on the specified topic (if one does not already exist), - # specifying a message selector, and creates a consumer on that durable subscription. - # - # + topic - the non-temporary Topic to subscribe to - # + subscriberName - the name used to identify this subscription - # + messageSelector - only messages with properties matching the message selector expression are added to the durable subscription. - # A value of null or an empty string indicates that there is no message selector for the durable subscription. - # + return - Returns a jms:MessageConsumer - public remote function createSharedDurableConsumer(Destination topic, string subscriberName, - string messageSelector = "") returns MessageConsumer|error { - var val = createJmsSharedDurableConsumer(self.jmsSession, topic.getJmsDestination(), - java:fromString(subscriberName), java:fromString(messageSelector)); - registerAndIncrementCounter(new observe:Counter(TOTAL_JMS_SHARED_DURABLE_CONSUMERS)); - if (val is handle) { - MessageConsumer consumer = new(val); - return consumer; - } else { - return val; - } - } - -}; - -# The Configurations that are related to a JMS session. -# -# + acknowledgementMode - Specifies the session mode that will be used. Valid values are "AUTO_ACKNOWLEDGE", -# "CLIENT_ACKNOWLEDGE", "SESSION_TRANSACTED", and "DUPS_OK_ACKNOWLEDGE". -public type SessionConfiguration record {| - string acknowledgementMode = "AUTO_ACKNOWLEDGE"; -|}; - -function createJmsMessage(handle session) returns handle | error = @java:Method { - name: "createMessage", - class: "javax.jms.Session" -} external; - -function createJmsTextMessage(handle session) returns handle | error = @java:Method { - name: "createTextMessage", - class: "javax.jms.Session" -} external; - -function createJmsTextMessageWithText(handle session, handle text) returns handle | error = @java:Method { - name: "createTextMessage", - paramTypes: ["java.lang.String"], - class: "javax.jms.Session" -} external; - -function createJmsMapMessage(handle session) returns handle | error = @java:Method { - name: "createMapMessage", - class: "javax.jms.Session" -} external; - -function createJmsStreamMessage(handle session) returns handle | error = @java:Method { - name: "createStreamMessage", - class: "javax.jms.Session" -} external; - -function createJmsBytesMessage(handle session) returns handle | error = @java:Method { - name: "createBytesMessage", - class: "javax.jms.Session" -} external; - -function createJmsConsumer(handle jmsSession, handle jmsDestination, - handle selectorString, boolean noLocal) returns handle|error = @java:Method { - name: "createConsumer", - paramTypes: ["javax.jms.Destination", "java.lang.String", "boolean"], - class: "javax.jms.Session" -} external; - -function createJmsSession(handle connection, handle acknowledgmentMode) returns handle | error = @java:Method { - class: "org.ballerinalang.java.jms.JmsSessionUtils" -} external; - -function unsubscribeJmsSubscription(handle session, handle subscriptionId) returns error? = @java:Method { - name: "unsubscribe", - class: "javax.jms.Session" -} external; - -function createJmsProducer(handle session, handle jmsDestination) returns handle|error = @java:Method { - name: "createProducer", - class: "javax.jms.Session" -} external; - -function createJmsDurableSubscriber(handle jmsSession, handle subscriberName, handle jmsDestination, - handle selectorString, boolean noLocal) returns handle|error = @java:Method { - name: "createDurableSubscriber", - paramTypes: ["javax.jms.Topic", "java.lang.String", "java.lang.String", "boolean"], - class: "javax.jms.Session" -} external; - -function createJmsSharedConsumer(handle jmsSession, handle subscriberName, handle jmsDestination, - handle selectorString) returns handle|error = @java:Method { - name: "createSharedConsumer", - paramTypes: ["javax.jms.Topic", "java.lang.String", "java.lang.String"], - class: "javax.jms.Session" -} external; - -function createJmsSharedDurableConsumer(handle jmsSession, handle subscriberName, handle jmsDestination, - handle selectorString) returns handle|error = @java:Method { - name: "createSharedDurableConsumer", - paramTypes: ["javax.jms.Topic", "java.lang.String", "java.lang.String"], - class: "javax.jms.Session" -} external; - -function createJmsQueue(handle session, handle queueName) returns handle | error = @java:Method { - name: "createQueue", - class: "javax.jms.Session" -} external; - -function createJmsTopic(handle session, handle topicName) returns handle | error = @java:Method { - name: "createTopic", - class: "javax.jms.Session" -} external; - -function createTemporaryJmsQueue(handle session) returns handle | error = @java:Method { - class: "org.ballerinalang.java.jms.JmsSessionUtils" -} external; - -function createTemporaryJmsTopic(handle session) returns handle | error = @java:Method { - class: "org.ballerinalang.java.jms.JmsSessionUtils" - -} external; \ No newline at end of file diff --git a/java.jms/src/java.jms/stream_message.bal b/java.jms/src/java.jms/stream_message.bal deleted file mode 100644 index b6f56ae7..00000000 --- a/java.jms/src/java.jms/stream_message.bal +++ /dev/null @@ -1,538 +0,0 @@ -// Copyright (c) 2019 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -// -// WSO2 Inc. licenses this file to you under the Apache License, -// Version 2.0 (the "License"); you may not use this file except -// in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -import ballerina/java; - -# Represent the 'StreamMessage' used to send and receive content from the a JMS provider. -# -# Most message-oriented middleware (MOM) products treat messages as lightweight entities that consist of a header -# and a body. The header contains fields used for message routing and identification; the body contains the -# application data being sent. -public type StreamMessage client object { - - // Add a reference to the `AbstractMessage` object type. - *AbstractMessage; - - # Initialized a `StreamMessage` object. - # - # + handle - The java reference to the jms text message. - function init(handle streamMessage) { - self.jmsMessage = streamMessage; - } - - # Read a boolean from the message. - # - # + return - Returns a boolean value or an error if it fails. - public function readBoolean() returns boolean | error { - return readBoolean(self.jmsMessage); - } - - # Read a byte from the message. - # - # + return - Returns a byte value or an error if it fails. - public function readByte() returns byte | error { - return readByte(self.jmsMessage); - } - -// # Read a byte array from the message. -// # -// # + return - Returns a byte array or an error if it fails. -// public function readBytes(byte[] value, int? length = ()) returns int | error { -// } - -// # Read a unicode character value from the message. -// # -// # + return - Returns a string value or an error if it fails. -// public function readChar() returns string | error { -// returns readChar(self.jmsMessage); -// } - - # Read a double value from the message. - # - # + return - Returns a double value or an error if it fails. - public function readDouble() returns float | error { - return readDouble(self.jmsMessage); - } - - # Read a float value from the message. - # - # + return - Returns a float value or an error if it fails. - public function readFloat() returns float | error { - return readFloat(self.jmsMessage); - } - - # Read an int value from the message. - # - # + return - Returns an int value or an error if it fails. - public function readInt() returns int | error { - return readInt(self.jmsMessage); - } - - # Read a long value from the message. - # - # + return - Returns a long value or an error if it fails. - public function readLong() returns int | error { - return readLong(self.jmsMessage); - } - - # Read a short value from the message. - # - # + return - Returns a short value or an error if it fails. - public function readShort() returns int | error { - return readShort(self.jmsMessage); - } - - # Read a string from the message. - # - # + return - Returns a string value or an error if it fails. - public function readString() returns string? | error { - handle|error val = readString(self.jmsMessage); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Puts the message body in read-only mode and repositions the stream of bytes to the beginning. - # - # + return - Returns an error if it fails. - public function reset() returns error? { - return reset(self.jmsMessage); - } - - # Write a boolean to the message stream as a 1-byte value. - # - # + value - The boolean value to be written - # + return - Returns an error if it fails. - public function writeBoolean(boolean value) returns error? { - return writeBoolean(self.jmsMessage, value); - } - - # Write a byte to the message. - # - # + value - The byte value to be written - # + return - Returns an error if it fails. - public function writeByte(byte value) returns error? { - return writeByte(self.jmsMessage, value); - } - - # Write a byte array to the message. - # - # + value - The byte array value to be written - # + offset - The initial offset within the byte array - # + length - The number of bytes to use - # + return - Returns an error if it fails. - public function writeBytes(byte[] value, int? offset = (), int? length = ()) returns error? { - if(offset is int && length is int) { -// return writePortionOfBytes(self.jmsMessage, value, offset, length); - } else { -// return writeBytes(self.jmsMessage, value); - } - } - -// # Write a char to the message. -// # -// # + value - The char value to be written -// # + return - Returns an error if it fails. -// public function writeChar(string value) returns error? { -// return writeChar(self.jmsMessage, java:fromString(value)); -// } - - # Write a double to the message. - # - # + value - The double value to be written - # + return - Returns an error if it fails. - public function writeDouble(float value) returns error? { - return writeDouble(self.jmsMessage, value); - } - - # Write a float to the message. - # - # + value - The float value to be written - # + return - Returns an error if it fails. - public function writeFloat(float value) returns error? { - return writeFloat(self.jmsMessage, value); - } - - # Write an int to the message. - # - # + value - The int value to be written - # + return - Returns an error if it fails. - public function writeInt(int value) returns error? { - return writeInt(self.jmsMessage, value); - } - - # Write a long to the message. - # - # + value - The long value to be written - # + return - Returns an error if it fails. - public function writeLong(int value) returns error? { - return writeLong(self.jmsMessage, value); - } - - # Write a short to the message. - # - # + value - The short value to be written - # + return - Returns an error if it fails. - public function writeShort(int value) returns error? { - return writeShort(self.jmsMessage, value); - } - - # Write a string to the message. - # - # + value - The string value to be written - # + return - Returns an error if it fails. - public function writeString(string value) returns error? { - return writeString(self.jmsMessage, java:fromString(value)); - } - - # Acknowledges the reception of this message. This is used when the consumer has chosen CLIENT_ACKNOWLEDGE as its - # acknowledgment mode. - # - # + return - If an error occurred while acknowledging the message. - public remote function acknowledge() returns error? { - return acknowledge(self.jmsMessage); - } - - # Clears out the message body. - # - # + return - If an error occurred while clearing out the message properties. - public function clearBody() returns error? { - return clearBody(self.jmsMessage); - } - - # Clears a message's properties. - # - # + return - If an error occurred while clearing out the message properties. - public function clearProperties() returns error? { - return clearProperties(self.jmsMessage); - } - - # Get the given boolean property. - # - # + name - The name of the boolean property - # + return - Returns the boolean value or an error if it fails. - public function getBooleanProperty(string name) returns boolean | error { - return getBooleanProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given byte property. - # - # + name - The name of the byte property - # + return - Returns the byte value or an error if it fails. - public function getByteProperty(string name) returns byte | error { - return getByteProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given double property. - # - # + name - The name of the double property - # + return - Returns the double value or an error if it fails. - public function getDoubleProperty(string name) returns float | error { - return getDoubleProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given float property. - # - # + name - The name of the float property - # + return - Returns the float value or an error if it fails. - public function getFloatProperty(string name) returns float | error { - return getFloatProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given int property. - # - # + name - The name of the int property - # + return - Returns the int value or an error if it fails. - public function getIntProperty(string name) returns int | error { - return getIntProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the message correlation ID. - # - # + return - Returns the message correlation ID or an error if it fails. - public function getJMSCorrelationID() returns string? | error { - handle|error val = getJMSCorrelationID(self.jmsMessage); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Get the message correlation ID as an array of bytes. - # - # + return - Returns the message correlation ID as an byte array or an error if it fails. - public function getJMSCorrelationIDAsBytes() returns byte[] | error { - return getJMSCorrelationIDAsBytes(self.jmsMessage); - } - - # Get the message delivery mode. - # - # + return - Returns the message delivery mode or an error if it fails. - public function getJMSDeliveryMode() returns int | error { - return getJMSDeliveryMode(self.jmsMessage); - } - - # Get the message delivery time. - # - # + return - Returns the message delivery time or an error if it fails. - public function getJMSDeliveryTime() returns int | error { - return getJMSDeliveryTime(self.jmsMessage); - } - - # Get the message destination object. - # - # + return - Returns the message destination object or an error if it fails. - public function getJMSDestination() returns Destination | error { - handle|error val = getJMSDestination(self.jmsMessage); - if (val is handle) { - return getDestination(val); - } else { - return val; - } - } - - # Get the message expiration time. - # - # + return - Returns the message expiration time or an error if it fails. - public function getJMSExpiration() returns int | error { - return getJMSExpiration(self.jmsMessage); - } - - # Get the message ID. - # - # + return - Returns the message ID or an error if it fails. - public function getJMSMessageID() returns string? | error { - handle|error val = getJMSMessageID(self.jmsMessage); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Get the message priority. - # - # + return - Returns the message priority or an error if it fails. - public function getJMSPriority() returns int | error { - return getJMSPriority(self.jmsMessage); - } - - # Get an indication whether the message being redelivered. - # - # + return - Returns the message redelivered or an error if it fails. - public function getJMSRedelivered() returns boolean | error { - return getJMSRedelivered(self.jmsMessage); - } - - # Get the Destination object to which a reply to this message should be sent. - # - # + return - Returns the reply to destination or an error if it fails. - public function getJMSReplyTo() returns Destination | error { - handle|error val = getJMSReplyTo(self.jmsMessage); - if (val is handle) { - return getDestination(val); - } else { - return val; - } - } - - # Get the message timestamp. - # - # + return - Returns the message timestamp or an error if it fails. - public function getJMSTimestamp() returns int | error { - return getJMSTimestamp(self.jmsMessage); - } - - # Get the message type identifier. - # - # + return - Returns the message type or an error if it fails. - public function getJMSType() returns (string|error)? { - handle|error val = getJMSType(self.jmsMessage); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Get the given long property. - # - # + name - The name of the long property - # + return - Returns the int value or an error if it fails. - public function getLongProperty(string name) returns int | error { - return getLongProperty(self.jmsMessage, java:fromString(name)); - } - - # Get string array of property names. - # - # + return - Returns the string array of property names or an error if it fails. - public function getPropertyNames() returns string[] | error { - return getPropertyNames(self.jmsMessage); - } - - # Get the given short property. - # - # + name - The name of the short property - # + return - Returns the int value or an error if it fails. - public function getShortProperty(string name) returns int | error { - return getShortProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given string property. - # - # + name - The name of the string property - # + return - Returns the string value or an error if it fails. - public function getStringProperty(string name) returns (string|error)? { - handle|error val = getStringProperty(self.jmsMessage, java:fromString(name)); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Indicate whether a property value exists. - # - # + name - The name of the property to test - # + return - Returns true if the property exists or an error if it fails. - public function propertyExists(string name) returns boolean | error { - return propertyExists(self.jmsMessage, java:fromString(name)); - } - - # Set the boolean value with the specified name into the message. - # - # + name - The name of the boolean property - # + value - The boolean property value to set - # + return - Returns an error if it fails. - public function setBooleanProperty(string name, boolean value) returns error? { - return setBooleanProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the byte value with the specified name into the message. - # - # + name - The name of the byte property - # + value - The byte property value to set - # + return - Returns an error if it fails. - public function setByteProperty(string name, byte value) returns error? { - return setByteProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the double value with the specified name into the message. - # - # + name - The name of the double property - # + value - The double property value to set - # + return - Returns an error if it fails. - public function setDoubleProperty(string name, float value) returns error? { - return setDoubleProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the float value with the specified name into the message. - # - # + name - The name of the float property - # + value - The float property value to set - # + return - Returns an error if it fails. - public function setFloatProperty(string name, float value) returns error? { - return setFloatProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the int value with the specified name into the message. - # - # + name - The name of the int property - # + value - The int property value to set - # + return - Returns an error if it fails. - public function setIntProperty(string name, int value) returns error? { - return setIntProperty(self.jmsMessage, java:fromString(name), value); - } - - # Sets the correlation id for the message. - # - # + correlationId - correlation id of a message as a string - # + return - Returns an error if it fails. - public function setJMSCorrelationID(string correlationId) returns error? { - return setJMSCorrelationID(self.jmsMessage, java:fromString(correlationId)); - } - - # Sets the correlation id an array of bytes for the message. - # - # + correlationId - correlation id value as an array of bytes - # + return - Returns an error if it fails. - public function setJMSCorrelationIDAsBytes(byte[] correlationId) returns error? { - return setJMSCorrelationIDAsBytes(self.jmsMessage, correlationId); - } - - # Set the reply destination to the message which a reply should send. - # - # + replyTo - Destination to which to send a response to this message - # + return - Returns an error if it fails. - public function setJMSReplyTo(Destination replyTo) returns error? { - return setJMSReplyTo(self.jmsMessage, replyTo.getJmsDestination()); - } - - # Set the message type. - # - # + jmsType - The message type - # + return - Returns an error if it fails. - public function setJMSType(string jmsType) returns error? { - return setJMSType(self.jmsMessage, java:fromString(jmsType)); - } - - # Set the long value with the specified name into the message. - # - # + name - The name of the long property - # + value - The long property value to set - # + return - Returns an error if it fails. - public function setLongProperty(string name, int value) returns error? { - return setLongProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the short value with the specified name into the message. - # - # + name - The name of the short property - # + value - The short property value to set - # + return - Returns an error if it fails. - public function setShortProperty(string name, int value) returns error? { - return setShortProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the string value with the specified name into the message. - # - # + name - The name of the string property - # + value - The string property value to set - # + return - Returns an error if it fails. - public function setStringProperty(string name, string value) returns error? { - return setStringProperty(self.jmsMessage, java:fromString(name), java:fromString(value)); - } - - # Get the JMS stream message - # - # + return - Returns the java reference to the jms stream message - function getJmsMessage() returns handle { - return self.jmsMessage; - } - -}; - -function readString(handle message) returns handle | error = @java:Method { - class: "javax.jms.StreamMessage" -} external; - -function writeString(handle message, handle value) returns error? = @java:Method { - class: "javax.jms.StreamMessage" -} external; - diff --git a/java.jms/src/java.jms/text_message.bal b/java.jms/src/java.jms/text_message.bal deleted file mode 100644 index e2cc39fb..00000000 --- a/java.jms/src/java.jms/text_message.bal +++ /dev/null @@ -1,390 +0,0 @@ -// Copyright (c) 2019 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -// -// WSO2 Inc. licenses this file to you under the Apache License, -// Version 2.0 (the "License"); you may not use this file except -// in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -import ballerina/java; - -# Represent the 'TextMessage' used to send and receive content from the a JMS provider. -# -# Most message-oriented middleware (MOM) products treat messages as lightweight entities that consist of a header -# and a body. The header contains fields used for message routing and identification; the body contains the -# application data being sent. -public type TextMessage client object { - - // Add a reference to the `AbstractMessage` object type. - *AbstractMessage; - - # Initialized a `TextMessage` object. - # - # + handle - The java reference to the jms text message. - function init(handle textMessage) { - self.jmsMessage = textMessage; - } - - # Set the text message. - # - # + data - the string containing the message's data - # + return - If an error occurred while setting the message's data. - public function setText(string data) returns error? { - return setText(self.jmsMessage, java:fromString(data)); - } - - # Get the text message. - # - # + return - Returns the message's data or an error if it fails. - public function getText() returns string?|error { - handle|error val = getText(self.jmsMessage); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Acknowledges the reception of this message. This is used when the consumer has chosen CLIENT_ACKNOWLEDGE as its - # acknowledgment mode. - # - # + return - If an error occurred while acknowledging the message. - public remote function acknowledge() returns error? { - return acknowledge(self.jmsMessage); - } - - # Clears out the message body. - # - # + return - If an error occurred while clearing out the message properties. - public function clearBody() returns error? { - return clearBody(self.jmsMessage); - } - - # Clears a message's properties. - # - # + return - If an error occurred while clearing out the message properties. - public function clearProperties() returns error? { - return clearProperties(self.jmsMessage); - } - - # Get the given boolean property. - # - # + name - The name of the boolean property - # + return - Returns the boolean value or an error if it fails. - public function getBooleanProperty(string name) returns boolean | error { - return getBooleanProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given byte property. - # - # + name - The name of the byte property - # + return - Returns the byte value or an error if it fails. - public function getByteProperty(string name) returns byte | error { - return getByteProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given double property. - # - # + name - The name of the double property - # + return - Returns the double value or an error if it fails. - public function getDoubleProperty(string name) returns float | error { - return getDoubleProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given float property. - # - # + name - The name of the float property - # + return - Returns the float value or an error if it fails. - public function getFloatProperty(string name) returns float | error { - return getFloatProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given int property. - # - # + name - The name of the int property - # + return - Returns the int value or an error if it fails. - public function getIntProperty(string name) returns int | error { - return getIntProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the message correlation ID. - # - # + return - Returns the message correlation ID or an error if it fails. - public function getJMSCorrelationID() returns string? | error { - handle|error val = getJMSCorrelationID(self.jmsMessage); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Get the message correlation ID as an array of bytes. - # - # + return - Returns the message correlation ID as an byte array or an error if it fails. - public function getJMSCorrelationIDAsBytes() returns byte[] | error { - return getJMSCorrelationIDAsBytes(self.jmsMessage); - } - - # Get the message delivery mode. - # - # + return - Returns the message delivery mode or an error if it fails. - public function getJMSDeliveryMode() returns int | error { - return getJMSDeliveryMode(self.jmsMessage); - } - - # Get the message delivery time. - # - # + return - Returns the message delivery time or an error if it fails. - public function getJMSDeliveryTime() returns int | error { - return getJMSDeliveryTime(self.jmsMessage); - } - - # Get the message destination object. - # - # + return - Returns the message destination object or an error if it fails. - public function getJMSDestination() returns Destination | error { - handle|error val = getJMSDestination(self.jmsMessage); - if (val is handle) { - return getDestination(val); - } else { - return val; - } - } - - # Get the message expiration time. - # - # + return - Returns the message expiration time or an error if it fails. - public function getJMSExpiration() returns int | error { - return getJMSExpiration(self.jmsMessage); - } - - # Get the message ID. - # - # + return - Returns the message ID or an error if it fails. - public function getJMSMessageID() returns string? | error { - handle|error val = getJMSMessageID(self.jmsMessage); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Get the message priority. - # - # + return - Returns the message priority or an error if it fails. - public function getJMSPriority() returns int | error { - return getJMSPriority(self.jmsMessage); - } - - # Get an indication whether the message being redelivered. - # - # + return - Returns the message redelivered or an error if it fails. - public function getJMSRedelivered() returns boolean | error { - return getJMSRedelivered(self.jmsMessage); - } - - # Get the Destination object to which a reply to this message should be sent. - # - # + return - Returns the reply to destination or an error if it fails. - public function getJMSReplyTo() returns Destination | error { - handle|error val = getJMSReplyTo(self.jmsMessage); - if (val is handle) { - return getDestination(val); - } else { - return val; - } - } - - # Get the message timestamp. - # - # + return - Returns the message timestamp or an error if it fails. - public function getJMSTimestamp() returns int | error { - return getJMSTimestamp(self.jmsMessage); - } - - # Get the message type identifier. - # - # + return - Returns the message type or an error if it fails. - public function getJMSType() returns (string|error)? { - handle|error val = getJMSType(self.jmsMessage); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Get the given long property. - # - # + name - The name of the long property - # + return - Returns the int value or an error if it fails. - public function getLongProperty(string name) returns int | error { - return getLongProperty(self.jmsMessage, java:fromString(name)); - } - - # Get string array of property names. - # - # + return - Returns the string array of property names or an error if it fails. - public function getPropertyNames() returns string[] | error { - return getPropertyNames(self.jmsMessage); - } - - # Get the given short property. - # - # + name - The name of the short property - # + return - Returns the int value or an error if it fails. - public function getShortProperty(string name) returns int | error { - return getShortProperty(self.jmsMessage, java:fromString(name)); - } - - # Get the given string property. - # - # + name - The name of the string property - # + return - Returns the string value or an error if it fails. - public function getStringProperty(string name) returns (string|error)? { - handle|error val = getStringProperty(self.jmsMessage, java:fromString(name)); - if (val is handle) { - return java:toString(val); - } else { - return val; - } - } - - # Indicate whether a property value exists. - # - # + name - The name of the property to test - # + return - Returns true if the property exists or an error if it fails. - public function propertyExists(string name) returns boolean | error { - return propertyExists(self.jmsMessage, java:fromString(name)); - } - - # Set the boolean value with the specified name into the message. - # - # + name - The name of the boolean property - # + value - The boolean property value to set - # + return - Returns an error if it fails. - public function setBooleanProperty(string name, boolean value) returns error? { - return setBooleanProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the byte value with the specified name into the message. - # - # + name - The name of the byte property - # + value - The byte property value to set - # + return - Returns an error if it fails. - public function setByteProperty(string name, byte value) returns error? { - return setByteProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the double value with the specified name into the message. - # - # + name - The name of the double property - # + value - The double property value to set - # + return - Returns an error if it fails. - public function setDoubleProperty(string name, float value) returns error? { - return setDoubleProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the float value with the specified name into the message. - # - # + name - The name of the float property - # + value - The float property value to set - # + return - Returns an error if it fails. - public function setFloatProperty(string name, float value) returns error? { - return setFloatProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the int value with the specified name into the message. - # - # + name - The name of the int property - # + value - The int property value to set - # + return - Returns an error if it fails. - public function setIntProperty(string name, int value) returns error? { - return setIntProperty(self.jmsMessage, java:fromString(name), value); - } - - # Sets the correlation id for the message. - # - # + correlationId - correlation id of a message as a string - # + return - Returns an error if it fails. - public function setJMSCorrelationID(string correlationId) returns error? { - return setJMSCorrelationID(self.jmsMessage, java:fromString(correlationId)); - } - - # Sets the correlation id an array of bytes for the message. - # - # + correlationId - correlation id value as an array of bytes - # + return - Returns an error if it fails. - public function setJMSCorrelationIDAsBytes(byte[] correlationId) returns error? { - return setJMSCorrelationIDAsBytes(self.jmsMessage, correlationId); - } - - # Set the reply destination to the message which a reply should send. - # - # + replyTo - Destination to which to send a response to this message - # + return - Returns an error if it fails. - public function setJMSReplyTo(Destination replyTo) returns error? { - return setJMSReplyTo(self.jmsMessage, replyTo.getJmsDestination()); - } - - # Set the message type. - # - # + jmsType - The message type - # + return - Returns an error if it fails. - public function setJMSType(string jmsType) returns error? { - return setJMSType(self.jmsMessage, java:fromString(jmsType)); - } - - # Set the long value with the specified name into the message. - # - # + name - The name of the long property - # + value - The long property value to set - # + return - Returns an error if it fails. - public function setLongProperty(string name, int value) returns error? { - return setLongProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the short value with the specified name into the message. - # - # + name - The name of the short property - # + value - The short property value to set - # + return - Returns an error if it fails. - public function setShortProperty(string name, int value) returns error? { - return setShortProperty(self.jmsMessage, java:fromString(name), value); - } - - # Set the string value with the specified name into the message. - # - # + name - The name of the string property - # + value - The string property value to set - # + return - Returns an error if it fails. - public function setStringProperty(string name, string value) returns error? { - return setStringProperty(self.jmsMessage, java:fromString(name), java:fromString(value)); - } - - # Get the JMS text message - # - # + return - Returns the java reference to the jms text message - function getJmsMessage() returns handle { - return self.jmsMessage; - } - -}; - -function setText(handle textMessage, handle data) returns error? = @java:Method { - class: "javax.jms.TextMessage" -} external; - -function getText(handle textMessage) returns handle | error = @java:Method { - class: "javax.jms.TextMessage" -} external; diff --git a/native/build.gradle b/native/build.gradle new file mode 100644 index 00000000..39ea835f --- /dev/null +++ b/native/build.gradle @@ -0,0 +1,71 @@ +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +plugins { + id 'java' + id 'checkstyle' + id 'com.github.spotbugs' +} + +dependencies { + checkstyle project(':checkstyle') + checkstyle "com.puppycrawl.tools:checkstyle:${checkstylePluginVersion}" + + implementation group: 'org.ballerinalang', name: 'ballerina-lang', version: "${ballerinaLangVersion}" + implementation group: 'org.ballerinalang', name: 'ballerina-runtime', version: "${ballerinaLangVersion}" + implementation group: 'org.slf4j', name: 'slf4j-api', version: "${slf4jVersion}" + implementation group: 'javax.jms', name: 'javax.jms-api', version: "${javaxJmsVersion}" +} + +def excludePattern = '**/module-info.java' +tasks.withType(Checkstyle) { + exclude excludePattern +} + +checkstyle { + toolVersion "${project.checkstylePluginVersion}" + configFile rootProject.file("build-config/checkstyle/build/checkstyle.xml") + configProperties = ["suppressionFile" : file("${rootDir}/build-config/checkstyle/build/suppressions.xml")] +} + +checkstyleMain.dependsOn(":checkstyle:downloadCheckstyleRuleFiles") + +spotbugsMain { + effort "max" + reportLevel "low" + reportsDir = file("$project.buildDir/reports/spotbugs") + reports { + html.enabled true + text.enabled = true + } + def excludeFile = file("${rootDir}/spotbugs-exclude.xml") + if(excludeFile.exists()) { + excludeFilter = excludeFile + } +} + +spotbugsTest { + enabled = false +} + +compileJava { + doFirst { + options.compilerArgs = [ + '--module-path', classpath.asPath, + ] + classpath = files() + } +} diff --git a/utils/src/main/java/org/ballerinalang/java/jms/BallerinaJmsException.java b/native/src/main/java/io/ballerina/stdlib/java.jms/BallerinaJmsException.java similarity index 72% rename from utils/src/main/java/org/ballerinalang/java/jms/BallerinaJmsException.java rename to native/src/main/java/io/ballerina/stdlib/java.jms/BallerinaJmsException.java index 63f91413..1c3f2b4a 100644 --- a/utils/src/main/java/org/ballerinalang/java/jms/BallerinaJmsException.java +++ b/native/src/main/java/io/ballerina/stdlib/java.jms/BallerinaJmsException.java @@ -1,12 +1,12 @@ /* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -14,13 +14,12 @@ * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. - * */ -package org.ballerinalang.java.jms; +package io.ballerina.stdlib.java.jms; /** - * Representation of the custom exception in the JMS module + * Representation of the custom exception in the JMS module. */ public class BallerinaJmsException extends Exception { diff --git a/utils/src/main/java/org/ballerinalang/java/jms/Constants.java b/native/src/main/java/io/ballerina/stdlib/java.jms/Constants.java similarity index 70% rename from utils/src/main/java/org/ballerinalang/java/jms/Constants.java rename to native/src/main/java/io/ballerina/stdlib/java.jms/Constants.java index 664ba724..666c1c58 100644 --- a/utils/src/main/java/org/ballerinalang/java/jms/Constants.java +++ b/native/src/main/java/io/ballerina/stdlib/java.jms/Constants.java @@ -1,12 +1,12 @@ /* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -14,14 +14,17 @@ * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. - * */ -package org.ballerinalang.java.jms; +package io.ballerina.stdlib.java.jms; + +import io.ballerina.runtime.api.utils.StringUtils; +import io.ballerina.runtime.api.values.BString; import java.util.Collections; import java.util.HashMap; import java.util.Map; + import javax.naming.Context; /** @@ -35,6 +38,9 @@ public class Constants { static final String PACKAGE_NAME = "java.jms"; public static final String VERSION = "0.99.0"; + // Error names for JMS package + public static final String JMS_ERROR = "Error"; + // Destination types public static final String DESTINATION_TYPE_QUEUE = "queue"; public static final String DESTINATION_TYPE_TOPIC = "topic"; @@ -116,6 +122,35 @@ public class Constants { static final String BYTE_MESSAGE_BAL_OBJECT_NAME = "BytesMessage"; static final String STREAM_MESSAGE_BAL_OBJECT_NAME = "StreamMessage"; + + static final String NATIVE_MESSAGE = "message"; + static final String MESSAGE_BAL_RECORD_NAME = "Message"; + static final String TEXT_MESSAGE_BAL_RECORD_NAME = "TextMessage"; + static final String MAP_MESSAGE_BAL_RECORD_NAME = "MapMessage"; + static final String BYTE_MESSAGE_BAL_RECORD_NAME = "BytesMessage"; + + // JMS message parameters + static final BString MESSAGE_ID = StringUtils.fromString("messageId"); + static final BString TIMESTAMP = StringUtils.fromString("timestamp"); + static final BString CORRELATION_ID = StringUtils.fromString("correlationId"); + static final BString TYPE = StringUtils.fromString("'type"); + static final BString NAME = StringUtils.fromString("name"); + static final BString REPLY_TO = StringUtils.fromString("replyTo"); + static final BString DESTINATION = StringUtils.fromString("destination"); + static final BString DELIVERY_MODE = StringUtils.fromString("deliveryMode"); + static final BString REDELIVERED = StringUtils.fromString("redelivered"); + static final BString JMS_TYPE = StringUtils.fromString("jmsType"); + static final BString EXPIRATION = StringUtils.fromString("expiration"); + static final BString DELIVERED_TIME = StringUtils.fromString("deliveredTime"); + static final BString PRIORITY = StringUtils.fromString("priority"); + static final BString PROPERTIES = StringUtils.fromString("properties"); + static final BString CONTENT = StringUtils.fromString("content"); + + static final BString QUEUE = StringUtils.fromString("QUEUE"); + static final BString TEMPORARY_QUEUE = StringUtils.fromString("TEMPORARY_QUEUE"); + static final BString TOPIC = StringUtils.fromString("TOPIC"); + static final BString TEMPORARY_TOPIC = StringUtils.fromString("TEMPORARY_TOPIC"); + static final String SERVICE_RESOURCE_ON_MESSAGE = "onMessage"; static final String SERVICE_RESOURCE_ON_TEXT_MESSAGE = "onTextMessage"; static final String SERVICE_RESOURCE_ON_MAP_MESSAGE = "onMapMessage"; @@ -123,6 +158,8 @@ public class Constants { static final String SERVICE_RESOURCE_ON_STREAM_MESSAGE = "onStreamMessage"; static final String SERVICE_RESOURCE_ON_OTHER_MESSAGE = "onOtherMessage"; + static final String CALLER = "Caller"; + private Constants() { } } diff --git a/native/src/main/java/io/ballerina/stdlib/java.jms/ConsumerCallback.java b/native/src/main/java/io/ballerina/stdlib/java.jms/ConsumerCallback.java new file mode 100644 index 00000000..c4dcf13a --- /dev/null +++ b/native/src/main/java/io/ballerina/stdlib/java.jms/ConsumerCallback.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.ballerina.stdlib.java.jms; + +import io.ballerina.runtime.api.async.Callback; +import io.ballerina.runtime.api.values.BError; + +/** + * Callback code to be executed when the message-listener complete a message producing cycle to the ballerina service. + */ +public class ConsumerCallback implements Callback { + @Override + public void notifySuccess(Object o) { + if (o instanceof BError) { + ((BError) o).printStackTrace(); + } + } + + @Override + public void notifyFailure(BError bError) { + bError.printStackTrace(); + System.exit(1); + } +} diff --git a/native/src/main/java/io/ballerina/stdlib/java.jms/ConsumerUtils.java b/native/src/main/java/io/ballerina/stdlib/java.jms/ConsumerUtils.java new file mode 100644 index 00000000..12b84917 --- /dev/null +++ b/native/src/main/java/io/ballerina/stdlib/java.jms/ConsumerUtils.java @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.ballerina.stdlib.java.jms; + +import io.ballerina.runtime.api.creators.ErrorCreator; +import io.ballerina.runtime.api.creators.ValueCreator; +import io.ballerina.runtime.api.types.Type; +import io.ballerina.runtime.api.utils.StringUtils; +import io.ballerina.runtime.api.utils.TypeUtils; +import io.ballerina.runtime.api.utils.ValueUtils; +import io.ballerina.runtime.api.values.BError; +import io.ballerina.runtime.api.values.BMap; +import io.ballerina.runtime.api.values.BString; + +import java.util.Enumeration; +import java.util.Iterator; +import java.util.Objects; + +import javax.jms.BytesMessage; +import javax.jms.Destination; +import javax.jms.JMSException; +import javax.jms.MapMessage; +import javax.jms.Message; +import javax.jms.MessageConsumer; +import javax.jms.Queue; +import javax.jms.TemporaryQueue; +import javax.jms.TemporaryTopic; +import javax.jms.TextMessage; +import javax.jms.Topic; + +/** + * Represents {@code javax.jms.MessageConsumer} related utility functions. + */ +public class ConsumerUtils { + public static Object receive(MessageConsumer consumer, long timeout) { + try { + Message message = consumer.receive(timeout); + if (Objects.isNull(message)) { + return null; + } + return getBallerinaMessage(message); + } catch (JMSException exception) { + BError cause = ErrorCreator.createError(exception); + return ErrorCreator.createError(ModuleUtils.getModule(), Constants.JMS_ERROR, + StringUtils.fromString("Error occurred while receiving messages"), cause, null); + } catch (BallerinaJmsException exception) { + BError cause = ErrorCreator.createError(exception); + return ErrorCreator.createError(ModuleUtils.getModule(), Constants.JMS_ERROR, + StringUtils.fromString("Error occurred while processing the received messages"), + cause, null); + } catch (Exception exception) { + BError cause = ErrorCreator.createError(exception); + return ErrorCreator.createError(ModuleUtils.getModule(), Constants.JMS_ERROR, + StringUtils.fromString("Unknown error occurred while processing the received messages"), + cause, null); + } + } + + public static Object receiveNoWait(MessageConsumer consumer) { + try { + Message message = consumer.receiveNoWait(); + if (Objects.isNull(message)) { + return null; + } + return getBallerinaMessage(message); + } catch (JMSException exception) { + BError cause = ErrorCreator.createError(exception); + return ErrorCreator.createError(ModuleUtils.getModule(), Constants.JMS_ERROR, + StringUtils.fromString("Error occurred while receiving messages"), cause, null); + } catch (BallerinaJmsException exception) { + BError cause = ErrorCreator.createError(exception); + return ErrorCreator.createError(ModuleUtils.getModule(), Constants.JMS_ERROR, + StringUtils.fromString("Error occurred while processing the received messages"), + cause, null); + } catch (Exception exception) { + BError cause = ErrorCreator.createError(exception); + return ErrorCreator.createError(ModuleUtils.getModule(), Constants.JMS_ERROR, + StringUtils.fromString("Unknown error occurred while processing the received messages"), + cause, null); + } + } + + public static Object acknowledge(BMap message) { + try { + Object nativeMessage = message.getNativeData(Constants.NATIVE_MESSAGE); + if (Objects.nonNull(nativeMessage)) { + ((Message) nativeMessage).acknowledge(); + } + } catch (JMSException exception) { + BError cause = ErrorCreator.createError(exception); + return ErrorCreator.createError(ModuleUtils.getModule(), Constants.JMS_ERROR, + StringUtils.fromString("Error occurred while sending acknowledgement for the message"), + cause, null); + } + return null; + } + + public static BMap getBallerinaMessage(Message message) + throws JMSException, BallerinaJmsException { + String messageType = getMessageType(message); + BMap ballerinaMessage = ValueCreator.createRecordValue(ModuleUtils.getModule(), messageType); + ballerinaMessage.put(Constants.MESSAGE_ID, StringUtils.fromString(message.getJMSMessageID())); + ballerinaMessage.put(Constants.TIMESTAMP, message.getJMSTimestamp()); + ballerinaMessage.put(Constants.CORRELATION_ID, StringUtils.fromString(message.getJMSCorrelationID())); + if (Objects.nonNull(message.getJMSReplyTo())) { + ballerinaMessage.put(Constants.REPLY_TO, getJmsDestinationField(message.getJMSReplyTo())); + } + if (Objects.nonNull(message.getJMSDestination())) { + ballerinaMessage.put(Constants.DESTINATION, getJmsDestinationField(message.getJMSDestination())); + } + ballerinaMessage.put(Constants.DELIVERY_MODE, message.getJMSDeliveryMode()); + ballerinaMessage.put(Constants.REDELIVERED, message.getJMSRedelivered()); + ballerinaMessage.put(Constants.JMS_TYPE, StringUtils.fromString(message.getJMSType())); + ballerinaMessage.put(Constants.EXPIRATION, message.getJMSExpiration()); + ballerinaMessage.put(Constants.DELIVERED_TIME, message.getJMSDeliveryTime()); + ballerinaMessage.put(Constants.PRIORITY, message.getJMSPriority()); + ballerinaMessage.put(Constants.PROPERTIES, getMessageProperties(message)); + Object content = getMessageContent(message); + ballerinaMessage.put(Constants.CONTENT, content); + ballerinaMessage.addNativeData(Constants.NATIVE_MESSAGE, message); + return ballerinaMessage; + } + + private static String getMessageType(Message message) { + if (message instanceof TextMessage) { + return Constants.TEXT_MESSAGE_BAL_RECORD_NAME; + } else if (message instanceof MapMessage) { + return Constants.MAP_MESSAGE_BAL_RECORD_NAME; + } else if (message instanceof BytesMessage) { + return Constants.BYTE_MESSAGE_BAL_RECORD_NAME; + } else { + return Constants.MESSAGE_BAL_RECORD_NAME; + } + } + + private static BMap getJmsDestinationField(Destination destination) throws JMSException { + BMap destRecord = ValueCreator.createMapValue(); + if (destination instanceof TemporaryQueue) { + destRecord.put(Constants.TYPE, Constants.TEMPORARY_QUEUE); + } else if (destination instanceof Queue) { + String queueName = ((Queue) destination).getQueueName(); + destRecord.put(Constants.TYPE, Constants.QUEUE); + destRecord.put(Constants.NAME, StringUtils.fromString(queueName)); + } else if (destination instanceof TemporaryTopic) { + destRecord.put(Constants.TYPE, Constants.TEMPORARY_TOPIC); + } else { + String topicName = ((Topic) destination).getTopicName(); + destRecord.put(Constants.TYPE, Constants.TOPIC); + destRecord.put(Constants.NAME, StringUtils.fromString(topicName)); + } + return destRecord; + } + + @SuppressWarnings("unchecked") + private static BMap getMessageProperties(Message message) + throws JMSException, BallerinaJmsException { + BMap messageProperties = ValueCreator.createMapValue(); + Enumeration propertyNames = message.getPropertyNames(); + Iterator iterator = propertyNames.asIterator(); + while (iterator.hasNext()) { + String key = iterator.next(); + Object value = ((MapMessage) message).getObject(key); + messageProperties.put(StringUtils.fromString(key), getMapValue(value)); + } + return messageProperties; + } + + @SuppressWarnings("unchecked") + private static Object getMessageContent(Message message) throws JMSException, BallerinaJmsException { + if (message instanceof TextMessage) { + return StringUtils.fromString(((TextMessage) message).getText()); + } else if (message instanceof MapMessage) { + BMap content = ValueCreator.createMapValue(); + Enumeration mapNames = (((MapMessage) message)).getMapNames(); + Iterator iterator = mapNames.asIterator(); + while (iterator.hasNext()) { + String key = iterator.next(); + Object value = ((MapMessage) message).getObject(key); + content.put(StringUtils.fromString(key), getMapValue(value)); + } + return content; + } else if (message instanceof BytesMessage) { + long bodyLength = ((BytesMessage) message).getBodyLength(); + byte[] payload = new byte[(int) bodyLength]; + ((BytesMessage) message).readBytes(payload); + return ValueCreator.createArrayValue(payload); + } + throw new BallerinaJmsException( + String.format("Unsupported message type: %s", message.getClass().getTypeName())); + } + + private static Object getMapValue(Object value) throws BallerinaJmsException { + if (isPrimitive(value)) { + Type type = TypeUtils.getType(value); + return ValueUtils.convert(value, type); + } + if (value instanceof String) { + return StringUtils.fromString((String) value); + } + if (value instanceof byte[]) { + return ValueCreator.createArrayValue((byte[]) value); + } + throw new BallerinaJmsException( + String.format("Unidentified map value type: %s", value.getClass().getTypeName())); + } + + private static boolean isPrimitive(Object value) { + return value instanceof Boolean || value instanceof Byte || value instanceof Character || + value instanceof Integer || value instanceof Long || value instanceof Float || value instanceof Double; + } +} diff --git a/native/src/main/java/io/ballerina/stdlib/java.jms/JmsBytesMessageUtils.java b/native/src/main/java/io/ballerina/stdlib/java.jms/JmsBytesMessageUtils.java new file mode 100644 index 00000000..a931c3db --- /dev/null +++ b/native/src/main/java/io/ballerina/stdlib/java.jms/JmsBytesMessageUtils.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.ballerina.stdlib.java.jms; + +import io.ballerina.runtime.api.creators.ErrorCreator; +import io.ballerina.runtime.api.creators.ValueCreator; +import io.ballerina.runtime.api.utils.StringUtils; +import io.ballerina.runtime.api.values.BArray; +import io.ballerina.runtime.api.values.BError; + +import javax.jms.BytesMessage; +import javax.jms.JMSException; + +import static io.ballerina.stdlib.java.jms.Constants.JMS_ERROR; + +/** + * Representation of {@link javax.jms.BytesMessage} with utility methods to invoke as inter-op functions. + */ +public class JmsBytesMessageUtils { + private JmsBytesMessageUtils() { + } + + /** + * Reads a byte array from the bytes message stream. + * + * @param message {@link javax.jms.BytesMessage} object + * @return Total number of bytes read into the buffer, or -1 if there is no more data + */ + public static Object readJavaBytes(BytesMessage message) { + try { + int bodyLength = (int) message.getBodyLength(); + byte[] bytes = new byte[bodyLength]; + message.readBytes(bytes); + return ValueCreator.createArrayValue(bytes); + } catch (JMSException e) { + BError cause = ErrorCreator.createError(e); + return ErrorCreator.createError(ModuleUtils.getModule(), JMS_ERROR, + StringUtils.fromString("Error occurred while reading bytes message."), cause, null); + } + } + + /** + * Reads a portion of the bytes message stream. + * + * @param message {@link javax.jms.BytesMessage} object + * @param length Number of bytes to read + * @return Total number of bytes read into the buffer, or -1 if there is no more data + */ + public static Object readPortionOfJavaBytes(BytesMessage message, int length) { + try { + long bodyLength = message.getBodyLength(); + if (length > bodyLength) { + return ErrorCreator.createError(ModuleUtils.getModule(), JMS_ERROR, + StringUtils.fromString("Length should be less than or equal to the message's body length."), + null, null); + } + byte[] bytes = new byte[length]; + message.readBytes(bytes, length); + return ValueCreator.createArrayValue(bytes); + } catch (JMSException e) { + BError cause = ErrorCreator.createError(e); + return ErrorCreator.createError(ModuleUtils.getModule(), JMS_ERROR, + StringUtils.fromString("Error occurred while reading portion of the bytes message."), + cause, null); + } + } + + /** + * Writes a byte array to the bytes message stream. + * + * @param message {@link javax.jms.BytesMessage} object + * @param value byte[] array as ballerina + */ + public static Object writeBytes(BytesMessage message, BArray value) { + try { + byte[] bytes = value.getBytes(); + message.writeBytes(bytes); + } catch (JMSException e) { + BError cause = ErrorCreator.createError(e); + return ErrorCreator.createError(ModuleUtils.getModule(), JMS_ERROR, + StringUtils.fromString("Error occurred while writing the bytes message."), + cause, null); + } + return null; + } + + /** + * Writes a portion of a byte array to the bytes message stream. + * + * @param message {@link javax.jms.BytesMessage} object + * @param value byte[] array as ballerina {@link BArray} + * @param offset Initial offset within the byte array + * @param length Number of bytes to use + */ + public static Object writePortionOfBytes(BytesMessage message, BArray value, int offset, int length) + throws BallerinaJmsException { + try { + byte[] bytes = value.getBytes(); + message.writeBytes(bytes, offset, length); + } catch (JMSException e) { + BError cause = ErrorCreator.createError(e); + return ErrorCreator.createError(ModuleUtils.getModule(), JMS_ERROR, + StringUtils.fromString("Error occurred while writing a portion of the bytes message."), + cause, null); + } + return null; + } +} diff --git a/utils/src/main/java/org/ballerinalang/java/jms/JmsConnectionUtils.java b/native/src/main/java/io/ballerina/stdlib/java.jms/JmsConnectionUtils.java similarity index 62% rename from utils/src/main/java/org/ballerinalang/java/jms/JmsConnectionUtils.java rename to native/src/main/java/io/ballerina/stdlib/java.jms/JmsConnectionUtils.java index f6b229ee..8b716894 100644 --- a/utils/src/main/java/org/ballerinalang/java/jms/JmsConnectionUtils.java +++ b/native/src/main/java/io/ballerina/stdlib/java.jms/JmsConnectionUtils.java @@ -1,12 +1,12 @@ /* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -14,13 +14,15 @@ * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. - * */ -package org.ballerinalang.java.jms; +package io.ballerina.stdlib.java.jms; -import org.ballerinalang.jvm.values.api.BMap; -import org.ballerinalang.jvm.values.api.BString; +import io.ballerina.runtime.api.creators.ErrorCreator; +import io.ballerina.runtime.api.utils.StringUtils; +import io.ballerina.runtime.api.values.BError; +import io.ballerina.runtime.api.values.BMap; +import io.ballerina.runtime.api.values.BString; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -29,22 +31,21 @@ import java.util.Map; import java.util.Properties; import java.util.UUID; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; import javax.naming.InitialContext; import javax.naming.NamingException; +import static io.ballerina.stdlib.java.jms.Constants.JMS_ERROR; + /** * Representation of {@link javax.jms.Connection} with utility methods to invoke as inter-op functions. */ public class JmsConnectionUtils { - private static final Logger LOGGER = LoggerFactory.getLogger(JmsConnectionUtils.class); - private JmsConnectionUtils() { - } - /** * Creates a connection with the default user identity. * @@ -52,67 +53,33 @@ private JmsConnectionUtils() { * @param providerUrl URL of the JNDI provider. * @param connectionFactoryName Name of connection factory * @param optionalConfigs Other JMS configs - * @return {@link javax.jms.Connection} object - * @throws BallerinaJmsException in an error situation + * @return {@link javax.jms.Connection} object or else an error */ - public static Connection createJmsConnection(BString initialContextFactory, BString providerUrl, - BString connectionFactoryName, - BMap optionalConfigs) throws BallerinaJmsException { - Connection connection = createConnection(initialContextFactory, providerUrl, connectionFactoryName, - optionalConfigs); + public static Object createJmsConnection(BString initialContextFactory, BString providerUrl, + BString connectionFactoryName, BMap optionalConfigs) { try { + Connection connection = createConnection( + initialContextFactory, providerUrl, connectionFactoryName, optionalConfigs); if (connection.getClientID() == null) { connection.setClientID(UUID.randomUUID().toString()); } connection.setExceptionListener(new LoggingExceptionListener()); connection.start(); + return connection; + } catch (BallerinaJmsException e) { + BError cause = ErrorCreator.createError(e); + return ErrorCreator.createError(ModuleUtils.getModule(), JMS_ERROR, + StringUtils.fromString(e.getMessage()), cause, null); } catch (JMSException e) { - throw new BallerinaJmsException("Error occurred while starting connection.", e); - } - return connection; - } - - /** - * Starts (or restarts) a connection's delivery of incoming messages. - * - * @param connection {@javax.jms.Connection} object to start the connection - * @throws BallerinaJmsException in an error situation - */ - public static void startJmsConnection(Connection connection) throws BallerinaJmsException { - try { - connection.start(); - } catch (JMSException e) { - throw new BallerinaJmsException("Error starting connection", e); + BError cause = ErrorCreator.createError(e); + return ErrorCreator.createError(ModuleUtils.getModule(), JMS_ERROR, + StringUtils.fromString("Error occurred while starting connection"), cause, null); } } - /** - * Temporarily stops a connection's delivery of incoming messages. - * - * @param connection {@link javax.jms.Connection} object to stop the connection - * @throws BallerinaJmsException in an error situation - */ - public static void stopJmsConnection(Connection connection) throws BallerinaJmsException { - try { - connection.stop(); - } catch (JMSException e) { - throw new BallerinaJmsException("Error stopping connection", e); - } - } - - /** - * Read ConnectionConfiguration and create connection with relevant JMS provider - * - * @param initialContextFactory JNDI config that can be used to lookup JMS connection factory object - * @param providerUrl URL of the JNDI provider. - * @param connectionFactoryName Name of connection factory - * @param optionalConfigs Other JMS configs - * @return {@javax.jms.Connection} object - * @throws BallerinaJmsException in an error situation - */ private static Connection createConnection(BString initialContextFactory, BString providerUrl, - BString connectionFactoryName , - BMap optionalConfigs) throws BallerinaJmsException{ + BString connectionFactoryName, BMap optionalConfigs) + throws BallerinaJmsException { Map configParams = new HashMap<>(); configParams.put(Constants.ALIAS_INITIAL_CONTEXT_FACTORY, initialContextFactory.getValue()); configParams.put(Constants.ALIAS_PROVIDER_URL, providerUrl.getValue()); @@ -122,7 +89,7 @@ private static Connection createConnection(BString initialContextFactory, BStrin updateMappedParameters(configParams); Properties properties = new Properties(); - configParams.forEach(properties::put); + properties.putAll(configParams); optionalConfigs.entrySet().forEach(e -> { properties.setProperty(e.getKey().getValue(), e.getValue().getValue()); }); @@ -139,7 +106,7 @@ private static Connection createConnection(BString initialContextFactory, BStrin if (optionalConfigs.containsKey(Constants.ALIAS_PASSWORD)) { password = optionalConfigs.get(Constants.ALIAS_PASSWORD).getValue(); } - if (JmsUtils.notNullOrEmptyAfterTrim(username) && password != null) { + if (notNullOrEmptyAfterTrim(username) && password != null) { return connectionFactory.createConnection(username, password); } else { return connectionFactory.createConnection(); @@ -151,13 +118,6 @@ private static Connection createConnection(BString initialContextFactory, BStrin } } - - /** - * If ConnectionConfiguration, then default to WSO2 MB as the JMS provider - * - * @param configParams JMS provider specific parameters - * @throws BallerinaJmsException in an error situation - */ private static void preProcessIfWso2MB(Map configParams) throws BallerinaJmsException { String initialConnectionFactoryName = configParams.get(Constants.ALIAS_INITIAL_CONTEXT_FACTORY); if (Constants.BMB_ICF_ALIAS.equalsIgnoreCase(initialConnectionFactoryName) @@ -167,9 +127,9 @@ private static void preProcessIfWso2MB(Map configParams) throws String connectionFactoryName = configParams.get(Constants.ALIAS_CONNECTION_FACTORY_NAME); if (configParams.get(Constants.ALIAS_PROVIDER_URL) != null) { System.setProperty("qpid.dest_syntax", "BURL"); - if (JmsUtils.notNullOrEmptyAfterTrim(connectionFactoryName)) { + if (notNullOrEmptyAfterTrim(connectionFactoryName)) { configParams.put(Constants.MB_CF_NAME_PREFIX + connectionFactoryName, - configParams.get(Constants.ALIAS_PROVIDER_URL)); + configParams.get(Constants.ALIAS_PROVIDER_URL)); configParams.remove(Constants.ALIAS_PROVIDER_URL); } else { throw new BallerinaJmsException( @@ -182,11 +142,6 @@ private static void preProcessIfWso2MB(Map configParams) throws } } - /** - * Update JMS provider specific config parameter - * - * @param configParams JMS provider specific parameters - */ private static void updateMappedParameters(Map configParams) { Iterator> iterator = configParams.entrySet().iterator(); Map tempMap = new HashMap<>(); @@ -200,4 +155,8 @@ private static void updateMappedParameters(Map configParams) { } configParams.putAll(tempMap); } + + private static boolean notNullOrEmptyAfterTrim(String str) { + return !(str == null || str.trim().isEmpty()); + } } diff --git a/utils/src/main/java/org/ballerinalang/java/jms/JmsDestinationUtils.java b/native/src/main/java/io/ballerina/stdlib/java.jms/JmsDestinationUtils.java similarity index 75% rename from utils/src/main/java/org/ballerinalang/java/jms/JmsDestinationUtils.java rename to native/src/main/java/io/ballerina/stdlib/java.jms/JmsDestinationUtils.java index 0f1320b6..5439f23e 100644 --- a/utils/src/main/java/org/ballerinalang/java/jms/JmsDestinationUtils.java +++ b/native/src/main/java/io/ballerina/stdlib/java.jms/JmsDestinationUtils.java @@ -1,12 +1,12 @@ /* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -14,19 +14,11 @@ * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. - * */ -package org.ballerinalang.java.jms; - -import org.ballerinalang.jvm.types.BTupleType; -import org.ballerinalang.jvm.types.BType; -import org.ballerinalang.jvm.types.BTypes; -import org.ballerinalang.jvm.values.ArrayValue; -import org.ballerinalang.jvm.values.HandleValue; +package io.ballerina.stdlib.java.jms; import javax.jms.Destination; -import javax.jms.JMSException; import javax.jms.Queue; import javax.jms.TemporaryQueue; import javax.jms.TemporaryTopic; @@ -36,16 +28,16 @@ * Representation of {@link javax.jms.Destination} with utility methods to invoke as inter-op functions. */ public class JmsDestinationUtils { + private JmsDestinationUtils() {} /** - * Get the {@link javax.jms.Destination} type + * Get the {@link javax.jms.Destination} type. * * @param destination {@link javax.jms.Destination} object * @return Ballerina Tuple represent {@link javax.jms.Destination} */ public static String getDestinationType(Destination destination) { String destinationType = null; - if (destination instanceof TemporaryQueue) { destinationType = Constants.DESTINATION_TYPE_TEMP_QUEUE; } else if (destination instanceof TemporaryTopic) { @@ -55,8 +47,6 @@ public static String getDestinationType(Destination destination) { } else if (destination instanceof Topic) { destinationType = Constants.DESTINATION_TYPE_TOPIC; } - return destinationType; } - } diff --git a/native/src/main/java/io/ballerina/stdlib/java.jms/JmsListener.java b/native/src/main/java/io/ballerina/stdlib/java.jms/JmsListener.java new file mode 100644 index 00000000..cb9a5ace --- /dev/null +++ b/native/src/main/java/io/ballerina/stdlib/java.jms/JmsListener.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.ballerina.stdlib.java.jms; + +import io.ballerina.runtime.api.Module; +import io.ballerina.runtime.api.PredefinedTypes; +import io.ballerina.runtime.api.Runtime; +import io.ballerina.runtime.api.async.Callback; +import io.ballerina.runtime.api.async.StrandMetadata; +import io.ballerina.runtime.api.creators.ValueCreator; +import io.ballerina.runtime.api.types.MethodType; +import io.ballerina.runtime.api.types.ObjectType; +import io.ballerina.runtime.api.types.Parameter; +import io.ballerina.runtime.api.types.Type; +import io.ballerina.runtime.api.utils.TypeUtils; +import io.ballerina.runtime.api.values.BObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Optional; +import java.util.stream.Stream; + +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageListener; + +import static io.ballerina.runtime.api.TypeTags.OBJECT_TYPE_TAG; +import static io.ballerina.runtime.api.TypeTags.RECORD_TYPE_TAG; +import static io.ballerina.stdlib.java.jms.ConsumerUtils.getBallerinaMessage; + +/** + * A {@link javax.jms.MessageListener} implementation. + */ +public class JmsListener implements MessageListener { + private static final Logger LOGGER = LoggerFactory.getLogger(JmsListener.class); + + private final BObject consumerService; + private final Runtime ballerinaRuntime; + private final Callback callback = new ConsumerCallback(); + + public JmsListener(BObject consumerService, Runtime ballerinaRuntime) { + this.consumerService = consumerService; + this.ballerinaRuntime = ballerinaRuntime; + } + + @Override + public void onMessage(Message message) { + try { + Module module = ModuleUtils.getModule(); + StrandMetadata metadata = new StrandMetadata( + module.getOrg(), module.getName(), module.getVersion(), Constants.SERVICE_RESOURCE_ON_MESSAGE); + ObjectType serviceType = (ObjectType) TypeUtils.getReferredType(TypeUtils.getType(consumerService)); + Object[] params = methodParameters(serviceType, message); + if (serviceType.isIsolated() && serviceType.isIsolated(Constants.SERVICE_RESOURCE_ON_MESSAGE)) { + ballerinaRuntime.invokeMethodAsyncConcurrently( + consumerService, Constants.SERVICE_RESOURCE_ON_MESSAGE, null, metadata, callback, + null, PredefinedTypes.TYPE_NULL, params); + } else { + ballerinaRuntime.invokeMethodAsyncSequentially( + consumerService, Constants.SERVICE_RESOURCE_ON_MESSAGE, null, metadata, callback, + null, PredefinedTypes.TYPE_NULL, params); + } + } catch (JMSException | BallerinaJmsException e) { + LOGGER.error("Unexpected error occurred while async message processing", e); + } + } + + private Object[] methodParameters(ObjectType serviceType, Message message) + throws JMSException, BallerinaJmsException { + Optional onMessageFuncOpt = Stream.of(serviceType.getMethods()) + .filter(methodType -> Constants.SERVICE_RESOURCE_ON_MESSAGE.equals(methodType.getName())) + .findFirst(); + if (onMessageFuncOpt.isPresent()) { + MethodType onMessageFunction = onMessageFuncOpt.get(); + Parameter[] parameters = onMessageFunction.getParameters(); + Object[] args = new Object[parameters.length * 2]; + int idx = 0; + for (Parameter param: parameters) { + Type referredType = TypeUtils.getReferredType(param.type); + switch (referredType.getTag()) { + case OBJECT_TYPE_TAG: + args[idx++] = ValueCreator.createObjectValue(ModuleUtils.getModule(), Constants.CALLER); + args[idx++] = true; + break; + case RECORD_TYPE_TAG: + args[idx++] = getBallerinaMessage(message); + args[idx++] = true; + break; + default: + throw new BallerinaJmsException( + String.format("Unknown service method parameter type: %s", referredType)); + } + } + return args; + } + throw new BallerinaJmsException("Required method `onMessage` not found in the service"); + } +} diff --git a/native/src/main/java/io/ballerina/stdlib/java.jms/JmsMapMessageUtils.java b/native/src/main/java/io/ballerina/stdlib/java.jms/JmsMapMessageUtils.java new file mode 100644 index 00000000..3ba48581 --- /dev/null +++ b/native/src/main/java/io/ballerina/stdlib/java.jms/JmsMapMessageUtils.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.ballerina.stdlib.java.jms; + +import io.ballerina.runtime.api.creators.ErrorCreator; +import io.ballerina.runtime.api.creators.ValueCreator; +import io.ballerina.runtime.api.utils.StringUtils; +import io.ballerina.runtime.api.values.BError; +import io.ballerina.runtime.api.values.BString; + +import java.util.Collections; +import java.util.List; + +import javax.jms.JMSException; +import javax.jms.MapMessage; +import javax.jms.Message; + +import static io.ballerina.stdlib.java.jms.Constants.JMS_ERROR; + +/** + * Representation of {@link javax.jms.MapMessage} with utility methods to invoke as inter-op functions. + */ +public class JmsMapMessageUtils { + private JmsMapMessageUtils() {} + + /** + * Return all names in the {@link javax.jms.MapMessage} as Ballerina array. + * + * @param message {@link javax.jms.MapMessage} object + * @return Ballerina array consist of map names + */ + public static Object getJmsMapNames(MapMessage message) { + try { + List propertyNames = Collections.list(message.getMapNames()); + return ValueCreator.createArrayValue(propertyNames.toArray(new BString[0])); + } catch (JMSException e) { + BError cause = ErrorCreator.createError(e); + return ErrorCreator.createError(ModuleUtils.getModule(), JMS_ERROR, + StringUtils.fromString("Error occurred while getting property names"), cause, null); + } + } + + /** + * Returns the byte array value with the specified name. + * + * @param message {@link javax.jms.Message} object + * @param name Field name + * @return a copy of the byte array value with the specified name; if there is no item by this name, + * a null value is returned. + */ + public static Object getBytes(Message message, String name) { + try { + MapMessage m = (MapMessage) message; + byte[] bytearray = m.getBytes(name); + return ValueCreator.createArrayValue(bytearray); + } catch (JMSException e) { + BError cause = ErrorCreator.createError(e); + return ErrorCreator.createError(ModuleUtils.getModule(), JMS_ERROR, + StringUtils.fromString("Error occurred while getting property names."), cause, null); + } + } +} diff --git a/native/src/main/java/io/ballerina/stdlib/java.jms/JmsMessageListenerUtils.java b/native/src/main/java/io/ballerina/stdlib/java.jms/JmsMessageListenerUtils.java new file mode 100644 index 00000000..2c828390 --- /dev/null +++ b/native/src/main/java/io/ballerina/stdlib/java.jms/JmsMessageListenerUtils.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.ballerina.stdlib.java.jms; + +import io.ballerina.runtime.api.Environment; +import io.ballerina.runtime.api.Runtime; +import io.ballerina.runtime.api.creators.ErrorCreator; +import io.ballerina.runtime.api.utils.StringUtils; +import io.ballerina.runtime.api.values.BError; +import io.ballerina.runtime.api.values.BObject; + +import javax.jms.JMSException; +import javax.jms.MessageConsumer; + +import static io.ballerina.stdlib.java.jms.Constants.JMS_ERROR; + +/** + * Representation of {@link javax.jms.MessageListener} with utility methods to invoke as inter-op functions. + */ +public class JmsMessageListenerUtils { + private JmsMessageListenerUtils() { + } + + public static Object setMessageListener(Environment environment, MessageConsumer consumer, + BObject serviceObject) { + Runtime bRuntime = environment.getRuntime(); + try { + consumer.setMessageListener(new JmsListener(serviceObject, bRuntime)); + } catch (JMSException e) { + BError cause = ErrorCreator.createError(e); + return ErrorCreator.createError(ModuleUtils.getModule(), JMS_ERROR, + StringUtils.fromString("Error occurred while setting the message listener"), cause, null); + } + return null; + } +} diff --git a/native/src/main/java/io/ballerina/stdlib/java.jms/JmsMessageUtils.java b/native/src/main/java/io/ballerina/stdlib/java.jms/JmsMessageUtils.java new file mode 100644 index 00000000..b6fd73bb --- /dev/null +++ b/native/src/main/java/io/ballerina/stdlib/java.jms/JmsMessageUtils.java @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.ballerina.stdlib.java.jms; + +import io.ballerina.runtime.api.creators.ErrorCreator; +import io.ballerina.runtime.api.creators.ValueCreator; +import io.ballerina.runtime.api.utils.StringUtils; +import io.ballerina.runtime.api.values.BArray; +import io.ballerina.runtime.api.values.BError; +import io.ballerina.runtime.api.values.BString; + +import java.util.Collections; +import java.util.List; + +import javax.jms.BytesMessage; +import javax.jms.JMSException; +import javax.jms.MapMessage; +import javax.jms.Message; +import javax.jms.StreamMessage; +import javax.jms.TextMessage; + +import static io.ballerina.stdlib.java.jms.Constants.JMS_ERROR; + +/** + * Representation of {@link Message} with utility methods to invoke as inter-op functions. + */ +public class JmsMessageUtils { + + private JmsMessageUtils() {} + + /** + * Check whether {@link Message} is {@link TextMessage}. + * + * @param message {@link Message} object + * @return true/false based on the evaluation + */ + public static boolean isTextMessage(Message message) { + return message instanceof TextMessage; + } + + /** + * Check whether {@link Message} is {@link MapMessage}. + * + * @param message {@link Message} object + * @return true/false based on the evaluation + */ + public static boolean isMapMessage(Message message) { + return message instanceof MapMessage; + } + + /** + * Check whether {@link Message} is {@link BytesMessage}. + * + * @param message {@link Message} object + * @return true/false based on the evaluation + */ + public static boolean isBytesMessage(Message message) { + return message instanceof BytesMessage; + } + + /** + * Check whether {@link Message} is {@link StreamMessage}. + * + * @param message {@link Message} object + * @return true/false based on the evaluation + */ + public static boolean isStreamMessage(Message message) { + return message instanceof StreamMessage; + } + + /** + * Return all property names in the {@link MapMessage} as Ballerina array. + * + * @param message {@link Message} object + * @return Ballerina array consist of property names + */ + public static Object getJmsPropertyNames(Message message) { + try { + List propertyNames = Collections.list(message.getPropertyNames()); + return ValueCreator.createArrayValue(propertyNames.toArray(new BString[0])); + } catch (JMSException e) { + BError cause = ErrorCreator.createError(e); + return ErrorCreator.createError(ModuleUtils.getModule(), JMS_ERROR, + StringUtils.fromString("Error occurred while getting property names."), cause, null); + } + } + + public static Object getJMSCorrelationIDAsBytes(Message message) { + try { + MapMessage m = (MapMessage) message; + return ValueCreator.createArrayValue(m.getJMSCorrelationIDAsBytes()); + } catch (JMSException e) { + BError cause = ErrorCreator.createError(e); + return ErrorCreator.createError(ModuleUtils.getModule(), JMS_ERROR, + StringUtils.fromString("Error occurred while getting property names."), cause, null); + } + } + + /** + * Set the JMS correlation id value as an array of byte. + * + * @param message {@link Message} object + * @param value correlation id value as an array of byte + */ + public static Object setJMSCorrelationIDAsBytes(Message message, BArray value) { + try { + byte[] correlationId = value.getBytes(); + message.setJMSCorrelationIDAsBytes(correlationId); + } catch (JMSException e) { + BError cause = ErrorCreator.createError(e); + return ErrorCreator.createError(ModuleUtils.getModule(), JMS_ERROR, + StringUtils.fromString("Error occurred while setting correlationId value as an array of bytes."), + cause, null); + } + return null; + } +} diff --git a/utils/src/main/java/org/ballerinalang/java/jms/JmsSessionUtils.java b/native/src/main/java/io/ballerina/stdlib/java.jms/JmsSessionUtils.java similarity index 64% rename from utils/src/main/java/org/ballerinalang/java/jms/JmsSessionUtils.java rename to native/src/main/java/io/ballerina/stdlib/java.jms/JmsSessionUtils.java index dbd89fe1..6a0617d6 100644 --- a/utils/src/main/java/org/ballerinalang/java/jms/JmsSessionUtils.java +++ b/native/src/main/java/io/ballerina/stdlib/java.jms/JmsSessionUtils.java @@ -1,12 +1,12 @@ /* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -14,11 +14,13 @@ * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. - * */ -package org.ballerinalang.java.jms; +package io.ballerina.stdlib.java.jms; +import io.ballerina.runtime.api.creators.ErrorCreator; +import io.ballerina.runtime.api.utils.StringUtils; +import io.ballerina.runtime.api.values.BError; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,24 +30,25 @@ import javax.jms.TemporaryQueue; import javax.jms.TemporaryTopic; +import static io.ballerina.stdlib.java.jms.Constants.JMS_ERROR; + /** * Representation of {@link javax.jms.Session} with utility methods to invoke as inter-op functions. */ public class JmsSessionUtils { - private static final Logger LOGGER = LoggerFactory.getLogger(JmsSessionUtils.class); private JmsSessionUtils() {} /** - * Creates a {@link javax.jms.Session} object with given {@link javax.jms.Connection} + * Creates a {@link javax.jms.Session} object with given {@link javax.jms.Connection}. * * @param connection {@link javax.jms.Connection} object * @param ackModeString Acknowledgment mode * @return {@link javax.jms.Session} object * @throws BallerinaJmsException in an error situation */ - public static Session createJmsSession(Connection connection, String ackModeString) throws BallerinaJmsException { + public static Object createJmsSession(Connection connection, String ackModeString) throws BallerinaJmsException { int sessionAckMode; boolean transactedSession = false; @@ -68,13 +71,18 @@ public static Session createJmsSession(Connection connection, String ackModeStri sessionAckMode = Session.AUTO_ACKNOWLEDGE; break; default: - throw new BallerinaJmsException("Unknown acknowledgment mode: " + ackModeString); + return ErrorCreator.createError(ModuleUtils.getModule(), JMS_ERROR, + StringUtils.fromString(String.format("Unknown acknowledgment mode: %s", ackModeString)), + null, null); } try { return connection.createSession(transactedSession, sessionAckMode); } catch (JMSException e) { - throw new BallerinaJmsException("Error while creating session." + e.getMessage(), e); + BError cause = ErrorCreator.createError(e); + return ErrorCreator.createError(ModuleUtils.getModule(), JMS_ERROR, + StringUtils.fromString(String.format("Error while creating session: %s", e.getMessage())), + cause, null); } } @@ -83,14 +91,15 @@ public static Session createJmsSession(Connection connection, String ackModeStri * * @param session {@link javax.jms.Session} object * @return return temporary queue name - * @throws BallerinaJmsException in an error situation */ - public static String createTemporaryJmsQueue(Session session) throws BallerinaJmsException { + public static Object createTemporaryJmsQueue(Session session) { try { TemporaryQueue temporaryQueue = session.createTemporaryQueue(); return temporaryQueue.getQueueName(); } catch (JMSException e) { - throw new BallerinaJmsException("Error creating temporary queue.", e); + BError cause = ErrorCreator.createError(e); + return ErrorCreator.createError(ModuleUtils.getModule(), JMS_ERROR, + StringUtils.fromString("Error creating temporary queue."), cause, null); } } @@ -99,15 +108,15 @@ public static String createTemporaryJmsQueue(Session session) throws BallerinaJm * * @param session {@link javax.jms.Session} object * @return return temporary topic name - * @throws BallerinaJmsException in an error situation */ - public static String createTemporaryJmsTopic(Session session) throws BallerinaJmsException { + public static Object createTemporaryJmsTopic(Session session) { try { TemporaryTopic temporaryTopic = session.createTemporaryTopic(); return temporaryTopic.getTopicName(); } catch (JMSException e) { - throw new BallerinaJmsException("Error creating temporary topic.", e); + BError cause = ErrorCreator.createError(e); + return ErrorCreator.createError(ModuleUtils.getModule(), JMS_ERROR, + StringUtils.fromString("Error creating temporary topic."), cause, null); } } - } diff --git a/utils/src/main/java/org/ballerinalang/java/jms/LoggingExceptionListener.java b/native/src/main/java/io/ballerina/stdlib/java.jms/LoggingExceptionListener.java similarity index 71% rename from utils/src/main/java/org/ballerinalang/java/jms/LoggingExceptionListener.java rename to native/src/main/java/io/ballerina/stdlib/java.jms/LoggingExceptionListener.java index 5d1db71f..78b1944a 100644 --- a/utils/src/main/java/org/ballerinalang/java/jms/LoggingExceptionListener.java +++ b/native/src/main/java/io/ballerina/stdlib/java.jms/LoggingExceptionListener.java @@ -1,12 +1,12 @@ /* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -14,10 +14,9 @@ * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. - * */ -package org.ballerinalang.java.jms; +package io.ballerina.stdlib.java.jms; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -32,7 +31,7 @@ public class LoggingExceptionListener implements ExceptionListener { private static final Logger LOGGER = LoggerFactory.getLogger(LoggingExceptionListener.class); @Override - public void onException(JMSException exception) { - LOGGER.error("Connection exception received.", exception); + public void onException(JMSException connectionException) { + LOGGER.error("Connection exception received.", connectionException); } } diff --git a/native/src/main/java/io/ballerina/stdlib/java.jms/ModuleUtils.java b/native/src/main/java/io/ballerina/stdlib/java.jms/ModuleUtils.java new file mode 100644 index 00000000..4dbf6f6d --- /dev/null +++ b/native/src/main/java/io/ballerina/stdlib/java.jms/ModuleUtils.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.ballerina.stdlib.java.jms; + +import io.ballerina.runtime.api.Environment; +import io.ballerina.runtime.api.Module; + +/** + * {@code ModuleUtils} contains the utility methods for the module. + */ +public class ModuleUtils { + private static Module module; + + private ModuleUtils() { + } + + public static void setModule(Environment environment) { + module = environment.getCurrentModule(); + } + + public static Module getModule() { + return module; + } +} diff --git a/native/src/main/java/module-info.java b/native/src/main/java/module-info.java new file mode 100644 index 00000000..63ba20e7 --- /dev/null +++ b/native/src/main/java/module-info.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +module io.ballerina.stdlib.java.jms { + requires io.ballerina.runtime; + requires org.slf4j; + requires java.naming; + requires javax.jms.api; +} diff --git a/pom.xml b/pom.xml deleted file mode 100644 index 2d1d35cc..00000000 --- a/pom.xml +++ /dev/null @@ -1,137 +0,0 @@ - - - - - - org.wso2 - wso2 - 1.1 - - 4.0.0 - org.ballerinalang - module-jms - pom - 0.99.0 - Ballerina JMS Module - - - utils - compiler-plugin - java.jms - - - - https://github.com/ballerina-platform/module-jms.git - scm:git:https://github.com/ballerina-platform/module-jms.git - scm:git:https://github.com/ballerina-platform/module-jms.git - HEAD - - - - - - org.slf4j - slf4j-api - ${slf4j.version} - compile - - - org.ballerinalang - ballerina-runtime - ${ballerina.version} - compile - - - org.ballerinalang - ballerina-lang - ${ballerina.version} - compile - - - javax.jms - javax.jms-api - ${jms.version} - - - org.slf4j - slf4j-simple - ${slf4j.version} - test - - - - - - - - - org.codehaus.mojo - exec-maven-plugin - ${exec.maven.plugin.version} - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven.compiler.plugin.version} - - - org.apache.maven.plugins - maven-dependency-plugin - ${maven.dependeny.plugin} - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - UTF-8 - 1.8 - 1.8 - - - - - - - wso2-nexus - WSO2 internal Repository - http://maven.wso2.org/nexus/content/groups/wso2-public/ - - true - daily - ignore - - - - - ${project.basedir} - UTF-8 - 2.0.0-Preview1 - 1.6.0 - 3.5.1 - 3.1.1 - **/generated/** - spotbugs-exclude.xml - 1.7.21 - 2.0.1 - - diff --git a/pull_request_template.md b/pull_request_template.md deleted file mode 100644 index 9b32185a..00000000 --- a/pull_request_template.md +++ /dev/null @@ -1,52 +0,0 @@ -## Purpose -> Describe the problems, issues, or needs driving this feature/fix and include links to related issues in the following format: Resolves issue1, issue2, etc. - -## Goals -> Describe the solutions that this feature/fix will introduce to resolve the problems described above - -## Approach -> Describe how you are implementing the solutions. Include an animated GIF or screenshot if the change affects the UI (email documentation@wso2.com to review all UI text). Include a link to a Markdown file or Google doc if the feature write-up is too long to paste here. - -## User stories -> Summary of user stories addressed by this change> - -## Release note -> Brief description of the new feature or bug fix as it will appear in the release notes - -## Documentation -> Link(s) to product documentation that addresses the changes of this PR. If no doc impact, enter “N/A” plus brief explanation of why there’s no doc impact - -## Training -> Link to the PR for changes to the training content in https://github.com/wso2/WSO2-Training, if applicable - -## Certification -> Type “Sent” when you have provided new/updated certification questions, plus four answers for each question (correct answer highlighted in bold), based on this change. Certification questions/answers should be sent to certification@wso2.com and NOT pasted in this PR. If there is no impact on certification exams, type “N/A” and explain why. - -## Marketing -> Link to drafts of marketing content that will describe and promote this feature, including product page changes, technical articles, blog posts, videos, etc., if applicable - -## Automation tests - - Unit tests - > Code coverage information - - Integration tests - > Details about the test cases and coverage - -## Security checks - - Followed secure coding standards in http://wso2.com/technical-reports/wso2-secure-engineering-guidelines? yes/no - - Ran FindSecurityBugs plugin and verified report? yes/no - - Confirmed that this PR doesn't commit any keys, passwords, tokens, usernames, or other secrets? yes/no - -## Samples -> Provide high-level details about the samples related to this feature - -## Related PRs -> List any other related PRs - -## Migrations (if applicable) -> Describe migration steps and platforms on which migration has been tested - -## Test environment -> List all JDK versions, operating systems, databases, and browser/versions on which this feature/fix was tested - -## Learning -> Describe the research phase and any blog posts, patterns, libraries, or add-ons you used to solve the problem. \ No newline at end of file diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 00000000..38950d8c --- /dev/null +++ b/settings.gradle @@ -0,0 +1,36 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * The settings file is used to specify which projects to include in your build. + * + * Detailed information about configuring a multi-project build in Gradle can be found + * in the user manual at https://docs.gradle.org/7.6/userguide/multi_project_builds.html + */ + +pluginManagement { + plugins { + id "com.github.spotbugs-base" version "${spotbugsPluginVersion}" + id "com.github.johnrengelman.shadow" version "${shadowJarPluginVersion}" + id "de.undercouch.download" version "${downloadPluginVersion}" + id "net.researchgate.release" version "${releasePluginVersion}" + } +} + +plugins { + id "com.gradle.enterprise" version "3.2" +} + +include ':checkstyle' +include ':java.jms-ballerina' +include ':java.jms-native' + +project(':checkstyle').projectDir = file("build-config${File.separator}checkstyle") +project(':java.jms-ballerina').projectDir = file('ballerina') +project(':java.jms-native').projectDir = file('native') + +gradleEnterprise { + buildScan { + termsOfServiceUrl = 'https://gradle.com/terms-of-service' + termsOfServiceAgree = 'yes' + } +} diff --git a/spotbugs-exclude.xml b/spotbugs-exclude.xml new file mode 100644 index 00000000..6814254c --- /dev/null +++ b/spotbugs-exclude.xml @@ -0,0 +1,23 @@ + + + + + + + \ No newline at end of file diff --git a/utils/pom.xml b/utils/pom.xml deleted file mode 100644 index b52477b2..00000000 --- a/utils/pom.xml +++ /dev/null @@ -1,81 +0,0 @@ - - - - - - module-jms - org.ballerinalang - 0.99.0 - ../pom.xml - - 4.0.0 - 0.99.0 - jms-utils - jar - JMS Utils - - - - org.slf4j - slf4j-api - - - org.ballerinalang - ballerina-runtime - - - javax.jms - javax.jms-api - - - - - - src/main/resources - - ballerina/** - - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-dependencies - prepare-package - - copy-dependencies - - - ${project.build.directory}/classes/lib - false - false - true - - - - - - - diff --git a/utils/src/main/java/org/ballerinalang/java/jms/JmsBytesMessageUtils.java b/utils/src/main/java/org/ballerinalang/java/jms/JmsBytesMessageUtils.java deleted file mode 100644 index ce013af8..00000000 --- a/utils/src/main/java/org/ballerinalang/java/jms/JmsBytesMessageUtils.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.ballerinalang.java.jms; - -import org.ballerinalang.jvm.util.exceptions.BallerinaException; -import org.ballerinalang.jvm.values.api.BValueCreator; -import org.ballerinalang.jvm.values.api.BArray; - -import javax.jms.BytesMessage; -import javax.jms.JMSException; - -/** - * Representation of {@link javax.jms.BytesMessage} with utility methods to invoke as inter-op functions. - */ -public class JmsBytesMessageUtils { - - /** - * Reads a byte array from the bytes message stream. - * - * @param message {@link javax.jms.BytesMessage} object - * @return Total number of bytes read into the buffer, or -1 if there is no more data - * @throws BallerinaException throw a RuntimeException in an error situation - */ - //TODO: Fix this workaround when Ballerina lang support to return primitive array and error as a union type - public static BArray readJavaBytes(BytesMessage message) { - try { - int bodyLength = (int)message.getBodyLength(); - byte[] bytes = new byte[bodyLength]; - message.readBytes(bytes); - return BValueCreator.createArrayValue(bytes); - } catch (JMSException e) { - throw new BallerinaException("Error occurred while reading bytes message.", e); - } - } - - /** - * Reads a portion of the bytes message stream. - * - * @param message {@link javax.jms.BytesMessage} object - * @param length Number of bytes to read - * @return Total number of bytes read into the buffer, or -1 if there is no more data - * @throws BallerinaException throw a RuntimeException in an error situation - */ - //TODO: Fix this workaround when Ballerina lang support to return primitive array and error as a union type - public static BArray readPortionOfJavaBytes(BytesMessage message, int length) { - try { - long bodyLength = message.getBodyLength(); - if (length > bodyLength) { - throw new BallerinaException("Length should be less than or equal to the message's body length."); - } - byte[] bytes = new byte[length]; - message.readBytes(bytes, length); - return BValueCreator.createArrayValue(bytes); - } catch (JMSException e) { - throw new BallerinaException("Error occurred while reading portion of the bytes message.", e); - } - } - - /** - * Writes a byte array to the bytes message stream. - * - * @param message {@link javax.jms.BytesMessage} object - * @param value byte[] array as ballerina {@link BArray} - * @throws BallerinaJmsException in an error situation - */ - public static void writeBytes(BytesMessage message, BArray value) throws BallerinaJmsException { - try { - byte[] bytes = value.getBytes(); - message.writeBytes(bytes); - } catch (JMSException e) { - throw new BallerinaJmsException("Error occurred while writing the bytes message.", e); - } - } - - /** - * Writes a portion of a byte array to the bytes message stream. - * - * @param message {@link javax.jms.BytesMessage} object - * @param value byte[] array as ballerina {@link BArray} - * @param offset Initial offset within the byte array - * @param length Number of bytes to use - * @throws BallerinaJmsException in an error situation - */ - public static void writePortionOfBytes(BytesMessage message, BArray value, int offset, int length) - throws BallerinaJmsException { - try { - byte[] bytes = value.getBytes(); - message.writeBytes(bytes, offset, length); - } catch (JMSException e) { - throw new BallerinaJmsException("Error occurred while reading bytes.", e); - } - } -} diff --git a/utils/src/main/java/org/ballerinalang/java/jms/JmsMapMessageUtils.java b/utils/src/main/java/org/ballerinalang/java/jms/JmsMapMessageUtils.java deleted file mode 100644 index 0bb74344..00000000 --- a/utils/src/main/java/org/ballerinalang/java/jms/JmsMapMessageUtils.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.ballerinalang.java.jms; - -import org.ballerinalang.jvm.util.exceptions.BallerinaException; -import org.ballerinalang.jvm.values.api.BArray; -import org.ballerinalang.jvm.values.api.BString; -import org.ballerinalang.jvm.values.api.BValueCreator; - -import javax.jms.JMSException; -import javax.jms.MapMessage; -import javax.jms.Message; -import java.util.Collections; -import java.util.List; - -/** - * Representation of {@link javax.jms.MapMessage} with utility methods to invoke as inter-op functions. - */ -public class JmsMapMessageUtils { - - /** - * Return all names in the {@link javax.jms.MapMessage} as Ballerina array - * - * @param message {@link javax.jms.MapMessage} object - * @return Ballerina array consist of map names - * @throws BallerinaException throw a RuntimeException in an error situation - */ - //TODO: Fix this workaround when Ballerina lang support to return primitive array and error as a union type - public static BArray getJmsMapNames(MapMessage message) { - try { - List propertyNames = Collections.list(message.getMapNames()); - return BValueCreator.createArrayValue(propertyNames.toArray(new BString[0])); - - } catch (JMSException e) { - throw new BallerinaException("Error occurred while getting property names.", e); - } - } - - public static BArray getBytes(Message message, String name) { - try { - MapMessage m = (MapMessage) message; - byte[] bytearray = m.getBytes(name); - return BValueCreator.createArrayValue(bytearray); - } catch (JMSException e) { - throw new BallerinaException("Error occurred while getting property names.", e); - } - } - -} diff --git a/utils/src/main/java/org/ballerinalang/java/jms/JmsMessageListenerUtils.java b/utils/src/main/java/org/ballerinalang/java/jms/JmsMessageListenerUtils.java deleted file mode 100644 index 264c4b48..00000000 --- a/utils/src/main/java/org/ballerinalang/java/jms/JmsMessageListenerUtils.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.ballerinalang.java.jms; - -import org.ballerinalang.jvm.BRuntime; -import org.ballerinalang.jvm.BallerinaValues; -import org.ballerinalang.jvm.types.AttachedFunction; -import org.ballerinalang.jvm.types.BPackage; -import org.ballerinalang.jvm.values.HandleValue; -import org.ballerinalang.jvm.values.ObjectValue; - -import javax.jms.BytesMessage; -import javax.jms.JMSException; -import javax.jms.MapMessage; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.StreamMessage; -import javax.jms.TextMessage; - -/** - * Representation of {@link javax.jms.MessageListener} with utility methods to invoke as inter-op functions. - */ -public class JmsMessageListenerUtils { - - private JmsMessageListenerUtils() { - } - - /** - * Set {@link javax.jms.MessageListener} to a {@link javax.jms.MessageConsumer} - * - * @param consumer {@link javax.jms.MessageConsumer} object - * @param serviceObject Ballerina service object - * @throws BallerinaJmsException in an error situation - */ - public static void setMessageListener(MessageConsumer consumer, ObjectValue serviceObject) throws BallerinaJmsException { - BRuntime runtime = BRuntime.getCurrentRuntime(); - try { - consumer.setMessageListener(new ListenerImpl(serviceObject, runtime)); - } catch (JMSException e) { - throw new BallerinaJmsException("Error occurred while setting the message listener"); - } - } - - /** - * Passes a message to the listener. - */ - private static class ListenerImpl implements MessageListener { - - private final ObjectValue serviceObject; - private final BRuntime runtime; - - ListenerImpl(ObjectValue serviceObject, BRuntime runtime) { - this.serviceObject = serviceObject; - this.runtime = runtime; - } - - @Override - public void onMessage(Message message) { - - String messageObjectName; - String specificFunctionName; - if (message instanceof TextMessage) { - messageObjectName = Constants.TEXT_MESSAGE_BAL_OBJECT_NAME; - specificFunctionName = Constants.SERVICE_RESOURCE_ON_TEXT_MESSAGE; - } else if (message instanceof MapMessage) { - messageObjectName = Constants.MAP_MESSAGE_BAL_OBJECT_NAME; - specificFunctionName = Constants.SERVICE_RESOURCE_ON_MAP_MESSAGE; - } else if (message instanceof BytesMessage) { - messageObjectName = Constants.BYTE_MESSAGE_BAL_OBJECT_NAME; - specificFunctionName = Constants.SERVICE_RESOURCE_ON_BYTES_MESSAGE; - } else if (message instanceof StreamMessage) { - messageObjectName = Constants.STREAM_MESSAGE_BAL_OBJECT_NAME; - specificFunctionName = Constants.SERVICE_RESOURCE_ON_STREAM_MESSAGE; - } else { - messageObjectName = Constants.MESSAGE_BAL_OBJECT_NAME; - specificFunctionName = Constants.SERVICE_RESOURCE_ON_OTHER_MESSAGE; - } - - BPackage jmsPackage = new BPackage(Constants.ORG, Constants.PACKAGE_NAME, Constants.VERSION); - ObjectValue param = BallerinaValues.createObjectValue(jmsPackage, messageObjectName, - new HandleValue(message)); - Object[] params = {param, true}; - - AttachedFunction[] attachedFunctions = serviceObject.getType().getAttachedFunctions(); - if (isMessageTypeSpecificFunction(attachedFunctions)) { - invokeMessageSpecificFunctions(specificFunctionName, attachedFunctions, params); - } else { - runtime.invokeMethodAsync(serviceObject, Constants.SERVICE_RESOURCE_ON_MESSAGE, params); - } - } - - /** - * With compiler plugin we guarantee that there are more than 1 resource in a message type specific scenario - * with the inclusion of mandatory onOtherMessage function. - * - * @param functions functions list - * @return true if there are message type specific functions found. - */ - private boolean isMessageTypeSpecificFunction(AttachedFunction[] functions) { - return functions.length > 1; - } - - private void invokeMessageSpecificFunctions(String specificFunctionName, AttachedFunction[] attachedFunctions, Object[] params) { - boolean functionFound = false; - for(AttachedFunction function: attachedFunctions) { - if (specificFunctionName.equals(function.getName())) { - functionFound = true; - runtime.invokeMethodAsync(serviceObject, specificFunctionName, params); - break; - } - } - if (!functionFound) { - runtime.invokeMethodAsync(serviceObject, Constants.SERVICE_RESOURCE_ON_OTHER_MESSAGE, params); - } - } - - } - -} diff --git a/utils/src/main/java/org/ballerinalang/java/jms/JmsMessageUtils.java b/utils/src/main/java/org/ballerinalang/java/jms/JmsMessageUtils.java deleted file mode 100644 index d286e11c..00000000 --- a/utils/src/main/java/org/ballerinalang/java/jms/JmsMessageUtils.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.ballerinalang.java.jms; - -import org.ballerinalang.jvm.util.exceptions.BallerinaException; -import org.ballerinalang.jvm.values.api.BArray; -import org.ballerinalang.jvm.values.api.BString; -import org.ballerinalang.jvm.values.api.BValueCreator; - -import javax.jms.BytesMessage; -import javax.jms.JMSException; -import javax.jms.MapMessage; -import javax.jms.Message; -import javax.jms.StreamMessage; -import javax.jms.TextMessage; -import java.util.Collections; -import java.util.List; - -/** - * Representation of {@link javax.jms.Message} with utility methods to invoke as inter-op functions. - */ -public class JmsMessageUtils { - - private JmsMessageUtils() {} - - /** - * Check whether {@link javax.jms.Message} is {@link javax.jms.TextMessage} - * - * @param message {@link javax.jms.Message} object - * @return true/false based on the evaluation - */ - public static boolean isTextMessage(Message message) { - return message instanceof TextMessage; - } - - /** - * Check whether {@link javax.jms.Message} is {@link javax.jms.MapMessage} - * - * @param message {@link javax.jms.Message} object - * @return true/false based on the evaluation - */ - public static boolean isMapMessage(Message message) { - return message instanceof MapMessage; - } - - /** - * Check whether {@link javax.jms.Message} is {@link javax.jms.BytesMessage} - * - * @param message {@link javax.jms.Message} object - * @return true/false based on the evaluation - */ - public static boolean isBytesMessage(Message message) { - return message instanceof BytesMessage; - } - - /** - * Check whether {@link javax.jms.Message} is {@link javax.jms.StreamMessage} - * - * @param message {@link javax.jms.Message} object - * @return true/false based on the evaluation - */ - public static boolean isStreamMessage(Message message) { - return message instanceof StreamMessage; - } - - /** - * Return all property names in the {@link javax.jms.MapMessage} as Ballerina array - * - * @param message {@link javax.jms.Message} object - * @return Ballerina array consist of property names - * @throws BallerinaException throw a RuntimeException in an error situation - */ - //TODO: Fix this workaround when Ballerina lang support to return primitive array and error as a union type - public static BArray getJmsPropertyNames(Message message) { - try { - List propertyNames = Collections.list(message.getPropertyNames()); - return BValueCreator.createArrayValue(propertyNames.toArray(new BString[0])); - - } catch (JMSException e) { - throw new BallerinaException("Error occurred while getting property names.", e); - } - } - - public static BArray getJMSCorrelationIDAsBytes(Message message) { - try { - MapMessage m = (MapMessage) message; - return BValueCreator.createArrayValue(m.getJMSCorrelationIDAsBytes()); - } catch (JMSException e) { - throw new BallerinaException("Error occurred while getting property names.", e); - } - } - - /** - * Set the JMS correlation id value as an array of byte - * - * @param message {@link javax.jms.Message} object - * @param value correlation id value as an array of byte - * @throws BallerinaJmsException in an error situation - */ - public static void setJMSCorrelationIDAsBytes(Message message, BArray value) throws BallerinaJmsException { - try { - byte[] correlationId = value.getBytes(); - message.setJMSCorrelationIDAsBytes(correlationId); - } catch (JMSException e) { - throw new BallerinaJmsException("Error occurred while setting correlationId value " + - "as an array of bytes", e); - } - } -} diff --git a/utils/src/main/java/org/ballerinalang/java/jms/JmsProducerUtils.java b/utils/src/main/java/org/ballerinalang/java/jms/JmsProducerUtils.java deleted file mode 100644 index b1674771..00000000 --- a/utils/src/main/java/org/ballerinalang/java/jms/JmsProducerUtils.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.ballerinalang.java.jms; - -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MessageProducer; -import javax.jms.Session; - -/** - * Representation of {@link javax.jms.MessageProducer} with utility methods to invoke as inter-op functions. - */ -public class JmsProducerUtils { - - private JmsProducerUtils() {} - - /** - * Creates a MessageProducer to send messages to the specified destination. - * - * @param session {@link javax.jms.Session} object - * @param destination {@link javax.jms.Destination} object - * @return {@link javax.jms.MessageProducer} object - * @throws BallerinaJmsException in an error situation - */ - public static MessageProducer createJmsProducer(Session session, Destination destination) - throws BallerinaJmsException { - try { - return session.createProducer(destination); - } catch (JMSException e) { - throw new BallerinaJmsException("Error creating queue sender.", e); - } - } -} diff --git a/utils/src/main/java/org/ballerinalang/java/jms/JmsUtils.java b/utils/src/main/java/org/ballerinalang/java/jms/JmsUtils.java deleted file mode 100644 index 7feeea24..00000000 --- a/utils/src/main/java/org/ballerinalang/java/jms/JmsUtils.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.ballerinalang.java.jms; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Utility class for JMS related common operations. - */ -public class JmsUtils { - - private static final Logger LOGGER = LoggerFactory.getLogger(JmsUtils.class); - - /** - * Utility class cannot be instantiated. - */ - private JmsUtils() { - } - - /** - * Check given string is not null or empty after trimming - * @param str String value - * @return true/false based on the input - */ - static boolean notNullOrEmptyAfterTrim(String str) { - return !(str == null || str.trim().isEmpty()); - } -} -