From 57e40d5b0c4114e4a4531da2b53e490e2eaa19db Mon Sep 17 00:00:00 2001 From: Alex Imenes <132364326+aleximenes@users.noreply.github.com> Date: Tue, 3 Mar 2026 09:36:35 +0100 Subject: [PATCH 01/71] Allow zero as value to certain tracking parameters (#362) --- .../matomo/java/tracking/MatomoRequest.java | 12 ++--- .../java/tracking/QueryCreatorTest.java | 53 ++++++++++++++++++- servlet-javax/pom.xml | 2 +- 3 files changed, 59 insertions(+), 8 deletions(-) diff --git a/core/src/main/java/org/matomo/java/tracking/MatomoRequest.java b/core/src/main/java/org/matomo/java/tracking/MatomoRequest.java index d9349836..42ef0c29 100644 --- a/core/src/main/java/org/matomo/java/tracking/MatomoRequest.java +++ b/core/src/main/java/org/matomo/java/tracking/MatomoRequest.java @@ -355,7 +355,7 @@ public class MatomoRequest { /** * The grand total for the ecommerce order (required when tracking an ecommerce order). */ - @TrackingParameter(name = "revenue") + @TrackingParameter(name = "revenue", min = 0) private Double ecommerceRevenue; /** @@ -433,7 +433,7 @@ public class MatomoRequest { /** * Some numeric value that represents the event value. */ - @TrackingParameter(name = "e_v") + @TrackingParameter(name = "e_v", min = 0) private Double eventValue; /** @@ -476,25 +476,25 @@ public class MatomoRequest { /** * The subtotal of the order; excludes shipping. */ - @TrackingParameter(name = "ec_st") + @TrackingParameter(name = "ec_st", min = 0) private Double ecommerceSubtotal; /** * Tax amount of the order. */ - @TrackingParameter(name = "ec_tx") + @TrackingParameter(name = "ec_tx", min = 0) private Double ecommerceTax; /** * Shipping cost of the order. */ - @TrackingParameter(name = "ec_sh") + @TrackingParameter(name = "ec_sh", min = 0) private Double ecommerceShippingCost; /** * Discount offered. */ - @TrackingParameter(name = "ec_dt") + @TrackingParameter(name = "ec_dt", min = 0) private Double ecommerceDiscount; /** diff --git a/core/src/test/java/org/matomo/java/tracking/QueryCreatorTest.java b/core/src/test/java/org/matomo/java/tracking/QueryCreatorTest.java index 8611d106..a4e87e5b 100644 --- a/core/src/test/java/org/matomo/java/tracking/QueryCreatorTest.java +++ b/core/src/test/java/org/matomo/java/tracking/QueryCreatorTest.java @@ -550,4 +550,55 @@ void tracksEvent() { assertThat(query).isEqualTo("idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&apiv=1&_id=112210f47de98115&e_c=Event+Category&e_a=Event+Action&e_n=Event+Name&e_v=23.456&send_image=0&rand=random-value"); } -} + @Test + void allowsZeroForEventValue() { + matomoRequestBuilder.eventName("Event Name") + .eventValue(0.0) + .eventAction("Event Action") + .eventCategory("Event Category"); + + whenCreatesQuery(); + + assertThat(query) + .isEqualTo("idsite=42&" + + "token_auth=876de1876fb2cda2816c362a61bfc712&" + + "rec=1&" + + "apiv=1&" + + "_id=112210f47de98115&" + + "e_c=Event+Category&" + + "e_a=Event+Action&" + + "e_n=Event+Name&" + + "e_v=0.0&" + + "send_image=0&" + + "rand=random-value" + ); + } + + @Test + void allowsZeroForEcommerceValues() { + matomoRequestBuilder + .ecommerceRevenue(0.0) + .ecommerceSubtotal(0.0) + .ecommerceTax(0.0) + .ecommerceShippingCost(0.0) + .ecommerceDiscount(0.0); + + whenCreatesQuery(); + + assertThat(query) + .isEqualTo("idsite=42&" + + "token_auth=876de1876fb2cda2816c362a61bfc712&" + + "rec=1&" + + "apiv=1&" + + "_id=112210f47de98115&" + + "revenue=0.0&" + + "ec_st=0.0&" + + "ec_tx=0.0&" + + "ec_sh=0.0&" + + "ec_dt=0.0&" + + "send_image=0&" + + "rand=random-value" + ); + } + +} \ No newline at end of file diff --git a/servlet-javax/pom.xml b/servlet-javax/pom.xml index 26c169b5..7e76f0a5 100644 --- a/servlet-javax/pom.xml +++ b/servlet-javax/pom.xml @@ -53,7 +53,7 @@ org.eclipse.jetty jetty-servlet - 11.0.0 + 10.0.24 test From 970e2f043e49c544dc796bb0d532f55fa45f8d36 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 3 Mar 2026 09:51:18 +0100 Subject: [PATCH 02/71] build(deps): bump org.apache.maven.plugins:maven-clean-plugin from 3.4.0 to 3.4.1 (#351) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index d28931b9..ee204290 100644 --- a/pom.xml +++ b/pom.xml @@ -127,7 +127,7 @@ org.apache.maven.plugins maven-clean-plugin - 3.4.0 + 3.5.0 org.apache.maven.plugins From 40fe3f0e34aba0c7dae9440fb67e0d8182aebe9d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 3 Mar 2026 09:51:30 +0100 Subject: [PATCH 03/71] build(deps): bump com.github.spotbugs:spotbugs-annotations from 4.9.0 to 4.9.3 (#355) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index ee204290..e481ba3d 100644 --- a/pom.xml +++ b/pom.xml @@ -71,7 +71,7 @@ com.github.spotbugs spotbugs-annotations - 4.9.0 + 4.9.8 provided From fec2e5fbe9f8a880abf7fd57a61881c4a1dfaebf Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 3 Mar 2026 09:51:45 +0100 Subject: [PATCH 04/71] build(deps): bump com.github.spotbugs:spotbugs-maven-plugin from 4.8.6.6 to 4.9.3.0 (#356) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index e481ba3d..3aac5f84 100644 --- a/pom.xml +++ b/pom.xml @@ -354,7 +354,7 @@ com.github.spotbugs spotbugs-maven-plugin - 4.8.6.6 + 4.9.8.2 org.owasp From bea60d5289fe5a1047c5c6c6f4a2644ebb1af851 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 3 Mar 2026 09:51:59 +0100 Subject: [PATCH 05/71] build(deps): bump org.owasp:dependency-check-maven from 12.0.2 to 12.1.1 (#357) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 3aac5f84..28e7248d 100644 --- a/pom.xml +++ b/pom.xml @@ -359,7 +359,7 @@ org.owasp dependency-check-maven - 12.0.2 + 12.2.0 true From 2143624c829f046ed32edabc3ed5d93a198c1b2f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 3 Mar 2026 09:52:13 +0100 Subject: [PATCH 06/71] build(deps-dev): bump org.wiremock:wiremock from 3.11.0 to 3.13.0 (#359) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- java11/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java11/pom.xml b/java11/pom.xml index 677f0c18..fb03eedf 100644 --- a/java11/pom.xml +++ b/java11/pom.xml @@ -48,7 +48,7 @@ org.wiremock wiremock - 3.11.0 + 3.13.2 test From b66ef234580703a36aa7002ee92cdd35b1b18b45 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 3 Mar 2026 09:59:34 +0100 Subject: [PATCH 07/71] build(deps): bump org.assertj:assertj-core from 3.27.3 to 3.27.7 (#363) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 28e7248d..6d23254f 100644 --- a/pom.xml +++ b/pom.xml @@ -94,7 +94,7 @@ org.assertj assertj-core - 3.27.3 + 3.27.7 test From 5700bf42ee8688f8ee26a2ca2840c0064e15e1cb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 3 Mar 2026 10:00:53 +0100 Subject: [PATCH 08/71] build(deps): bump madrapps/jacoco-report from 1.7.1 to 1.7.2 (#360) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 607838f4..d8f4898a 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -21,7 +21,7 @@ jobs: distribution: 'temurin' cache: maven - run: mvn -B verify - - uses: madrapps/jacoco-report@v1.7.1 + - uses: madrapps/jacoco-report@v1.7.2 with: paths: ${{ github.workspace }}/target/site/jacoco/jacoco.xml token: ${{ secrets.GITHUB_TOKEN }} From 60cee9f757c4c2046fb8913920c7fd11e03d0fa8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 10 Mar 2026 09:37:25 +0100 Subject: [PATCH 09/71] build(deps): bump actions/setup-java from 4 to 5 (#373) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/build.yml | 2 +- .github/workflows/codeql-analysis.yml | 2 +- .github/workflows/release.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d8f4898a..aaad7c01 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -15,7 +15,7 @@ jobs: contents: read steps: - uses: actions/checkout@v4 - - uses: actions/setup-java@v4 + - uses: actions/setup-java@v5 with: java-version: '17' distribution: 'temurin' diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index f6ad8c52..d1cf4457 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -24,7 +24,7 @@ jobs: steps: - uses: actions/checkout@v4 - - uses: actions/setup-java@v4 + - uses: actions/setup-java@v5 with: java-version: '17' distribution: 'temurin' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 69ce43c6..ea458515 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -6,7 +6,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: actions/setup-java@v4 + - uses: actions/setup-java@v5 with: java-version: '17' distribution: 'temurin' From c0ad294136ffd45cfb850d0a98ed03e3a4bdcec5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 10 Mar 2026 09:38:12 +0100 Subject: [PATCH 10/71] build(deps): bump org.apache.maven.plugins:maven-failsafe-plugin from 3.5.2 to 3.5.5 (#368) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 6d23254f..cafc547d 100644 --- a/pom.xml +++ b/pom.xml @@ -202,7 +202,7 @@ org.apache.maven.plugins maven-failsafe-plugin - 3.5.2 + 3.5.5 From e67ebdf681e15d7fd593300aaeb4c771663cfd7e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 10 Mar 2026 09:38:28 +0100 Subject: [PATCH 11/71] build(deps-dev): bump org.apache.maven.plugins:maven-deploy-plugin from 3.1.3 to 3.1.4 (#367) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index cafc547d..75c7f967 100644 --- a/pom.xml +++ b/pom.xml @@ -132,7 +132,7 @@ org.apache.maven.plugins maven-deploy-plugin - 3.1.3 + 3.1.4 org.apache.maven.plugins From d25bcd97a22cb05aa924f07179bc54a84c43ee29 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 10 Mar 2026 09:38:47 +0100 Subject: [PATCH 12/71] build(deps-dev): bump org.apache.maven.plugins:maven-release-plugin from 3.1.1 to 3.3.1 (#364) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 75c7f967..f1ba8c43 100644 --- a/pom.xml +++ b/pom.xml @@ -162,7 +162,7 @@ org.apache.maven.plugins maven-release-plugin - 3.1.1 + 3.3.1 true false From e42028d26211b5a5159b9d2a46f44efcbb508c01 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 10 Mar 2026 09:40:49 +0100 Subject: [PATCH 13/71] build(deps-dev): bump org.apache.maven.plugins:maven-compiler-plugin from 3.13.0 to 3.15.0 (#365) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index f1ba8c43..b9bea5ff 100644 --- a/pom.xml +++ b/pom.xml @@ -117,7 +117,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.13.0 + 3.15.0 org.apache.maven.plugins From 160228ef4c3801b084f10902062836358f516a25 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 10 Mar 2026 09:41:09 +0100 Subject: [PATCH 14/71] build(deps-dev): bump org.jacoco:jacoco-maven-plugin from 0.8.12 to 0.8.14 (#366) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b9bea5ff..14a14d62 100644 --- a/pom.xml +++ b/pom.xml @@ -290,7 +290,7 @@ org.jacoco jacoco-maven-plugin - 0.8.12 + 0.8.14 prepare-agent From 0a4521f38b45ca181f83122131c597b3cb23ea37 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 10 Mar 2026 09:41:39 +0100 Subject: [PATCH 15/71] build(deps): bump scacap/action-surefire-report from 1.9.0 to 1.9.1 (#369) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index aaad7c01..fc160921 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -27,4 +27,4 @@ jobs: token: ${{ secrets.GITHUB_TOKEN }} min-coverage-overall: 80 min-coverage-changed-files: 80 - - uses: scacap/action-surefire-report@v1.9.0 \ No newline at end of file + - uses: scacap/action-surefire-report@v1.9.1 \ No newline at end of file From daeaf00605d34a11856daa3d1bd95802e00c2a35 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 10 Mar 2026 09:41:50 +0100 Subject: [PATCH 16/71] build(deps): bump actions/upload-pages-artifact from 3 to 4 (#370) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/gh-pages.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index dcad339d..c9d5cbf8 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -20,7 +20,7 @@ jobs: with: source: ./ destination: ./_site - - uses: actions/upload-pages-artifact@v3 + - uses: actions/upload-pages-artifact@v4 deploy: environment: name: github-pages From 5362c0a0e350fb8c6add571b28d7d2a239668074 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 10 Mar 2026 09:43:33 +0100 Subject: [PATCH 17/71] build(deps): bump github/codeql-action from 3 to 4 (#371) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/codeql-analysis.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index d1cf4457..cc940fba 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -29,8 +29,8 @@ jobs: java-version: '17' distribution: 'temurin' cache: maven - - uses: github/codeql-action/init@v3 + - uses: github/codeql-action/init@v4 with: languages: ${{ matrix.language }} - - uses: github/codeql-action/autobuild@v3 - - uses: github/codeql-action/analyze@v3 + - uses: github/codeql-action/autobuild@v4 + - uses: github/codeql-action/analyze@v4 From 3064425ab9115264a18768bc00616ec838227174 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 10 Mar 2026 09:43:44 +0100 Subject: [PATCH 18/71] build(deps): bump actions/checkout from 4 to 6 (#372) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/build.yml | 2 +- .github/workflows/codeql-analysis.yml | 2 +- .github/workflows/gh-pages.yml | 2 +- .github/workflows/release.yml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fc160921..1711ae4b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -14,7 +14,7 @@ jobs: checks: write contents: read steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - uses: actions/setup-java@v5 with: java-version: '17' diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index cc940fba..c00ed329 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -23,7 +23,7 @@ jobs: language: [ 'java' ] steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - uses: actions/setup-java@v5 with: java-version: '17' diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index c9d5cbf8..ace69696 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -14,7 +14,7 @@ jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - uses: actions/configure-pages@v5 - uses: actions/jekyll-build-pages@v1 with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ea458515..1697b03b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -5,7 +5,7 @@ jobs: publish: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - uses: actions/setup-java@v5 with: java-version: '17' From 2640b7464560fbebe0567aa263e08d5864aae9b8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 17 Mar 2026 10:17:43 +0100 Subject: [PATCH 19/71] build(deps): bump release-drafter/release-drafter from 6 to 7 (#379) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1697b03b..3ab20fb0 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -28,7 +28,7 @@ jobs: OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }} OSSRH_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} - - uses: release-drafter/release-drafter@v6 + - uses: release-drafter/release-drafter@v7 with: version: ${{ steps.version.outputs.version }} publish: true From 16b153779ffe3ead1ce8d8a3b8bd80a055d4429a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 17 Mar 2026 10:17:58 +0100 Subject: [PATCH 20/71] build(deps): bump org.apache.maven.plugins:maven-gpg-plugin from 3.2.7 to 3.2.8 (#378) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 14a14d62..570fdffc 100644 --- a/pom.xml +++ b/pom.xml @@ -174,7 +174,7 @@ org.apache.maven.plugins maven-gpg-plugin - 3.2.7 + 3.2.8 sign-artifacts From 12dbcb9fcc28134acfdcd42e08a085a68f8087e5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 17 Mar 2026 10:18:08 +0100 Subject: [PATCH 21/71] build(deps-dev): bump org.apache.maven.plugins:maven-surefire-plugin from 3.5.2 to 3.5.5 (#376) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 570fdffc..bb102d9b 100644 --- a/pom.xml +++ b/pom.xml @@ -157,7 +157,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.2 + 3.5.5 org.apache.maven.plugins From 433ed938fd8c5bb286f4035d3e8db9ce4fd6aeaf Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 17 Mar 2026 10:18:26 +0100 Subject: [PATCH 22/71] build(deps): bump slf4j.version from 2.0.16 to 2.0.17 (#377) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index bb102d9b..79fd170e 100644 --- a/pom.xml +++ b/pom.xml @@ -63,7 +63,7 @@ 1.8 ${project.build.outputDirectory}/delombok 1.18.36 - 2.0.16 + 2.0.17 From 267b9cffbb0e62e79306bbd4e5af462f7a5f4608 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 17 Mar 2026 10:18:40 +0100 Subject: [PATCH 23/71] build(deps-dev): bump org.apache.maven.plugins:maven-resources-plugin from 3.3.1 to 3.5.0 (#375) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 79fd170e..f4c62914 100644 --- a/pom.xml +++ b/pom.xml @@ -147,7 +147,7 @@ org.apache.maven.plugins maven-resources-plugin - 3.3.1 + 3.5.0 org.apache.maven.plugins From 2b75f59b0f7dc4d96f931b0f3f15be045c1bad65 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 14 Apr 2026 13:03:47 +0200 Subject: [PATCH 24/71] build(deps): bump actions/upload-pages-artifact from 4 to 5 (#387) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/gh-pages.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index ace69696..8d8dcaca 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -20,7 +20,7 @@ jobs: with: source: ./ destination: ./_site - - uses: actions/upload-pages-artifact@v4 + - uses: actions/upload-pages-artifact@v5 deploy: environment: name: github-pages From 52ebeb5e14a2a46cf09d8b200693627018fc6c55 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 14 Apr 2026 13:04:03 +0200 Subject: [PATCH 25/71] build(deps): bump actions/deploy-pages from 4 to 5 (#385) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/gh-pages.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index 8d8dcaca..daf39620 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -29,4 +29,4 @@ jobs: needs: build steps: - id: deployment - uses: actions/deploy-pages@v4 + uses: actions/deploy-pages@v5 From a23f74aeb7b8bd170c1839666c2dcd8f752c7b77 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 14 Apr 2026 13:04:24 +0200 Subject: [PATCH 26/71] build(deps-dev): bump org.apache.maven.plugins:maven-project-info-reports-plugin from 3.8.0 to 3.9.0 (#384) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index f4c62914..a051e3ce 100644 --- a/pom.xml +++ b/pom.xml @@ -122,7 +122,7 @@ org.apache.maven.plugins maven-project-info-reports-plugin - 3.8.0 + 3.9.0 org.apache.maven.plugins From 1d7334b49d626b15d16fd8277db4dcc00c607913 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 14 Apr 2026 13:04:44 +0200 Subject: [PATCH 27/71] build(deps): bump actions/configure-pages from 5 to 6 (#386) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/gh-pages.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index daf39620..5cbcb16e 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -15,7 +15,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - - uses: actions/configure-pages@v5 + - uses: actions/configure-pages@v6 - uses: actions/jekyll-build-pages@v1 with: source: ./ From 2bf4d1a06bbebc0a2458d13293ad0a0027c22e25 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 14 Apr 2026 13:05:04 +0200 Subject: [PATCH 28/71] build(deps-dev): bump org.apache.maven.plugins:maven-jar-plugin from 3.4.2 to 3.5.0 (#383) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index a051e3ce..e8fd16ed 100644 --- a/pom.xml +++ b/pom.xml @@ -142,7 +142,7 @@ org.apache.maven.plugins maven-jar-plugin - 3.4.2 + 3.5.0 org.apache.maven.plugins From fab01d6b22efe287ae6df66fe7cc08bcbbc7b48a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 14 Apr 2026 13:05:19 +0200 Subject: [PATCH 29/71] build(deps-dev): bump org.apache.maven.plugins:maven-install-plugin from 3.1.3 to 3.1.4 (#380) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index e8fd16ed..210cfe3a 100644 --- a/pom.xml +++ b/pom.xml @@ -137,7 +137,7 @@ org.apache.maven.plugins maven-install-plugin - 3.1.3 + 3.1.4 org.apache.maven.plugins From 630439bc2834f4fb91919f7ad5d497c922a1d54a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 16 Apr 2026 12:11:43 +0200 Subject: [PATCH 30/71] build(deps): bump org.junit.jupiter:junit-jupiter from 5.11.4 to 6.0.3 (#381) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Daniel Heid --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 210cfe3a..9e639923 100644 --- a/pom.xml +++ b/pom.xml @@ -88,7 +88,7 @@ org.junit.jupiter junit-jupiter - 5.11.4 + 6.0.3 test From 76d7cea9e7165e07a16465e8d2f85824af5fdae3 Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Thu, 16 Apr 2026 15:24:26 +0200 Subject: [PATCH 31/71] #382 Update to Spring Boot 4.0.5 --- .github/ISSUE_TEMPLATE/bug_report.md | 1 + .github/ISSUE_TEMPLATE/feature_request.md | 1 + .github/dependabot.yml | 6 + .github/pull_request_template.md | 1 - .github/workflows/dependabot-auto-merge.yml | 17 + CONTRIBUTING.md | 2 +- README.md | 82 ++-- SECURITY.md | 4 +- core/pom.xml | 3 +- .../org/matomo/java/tracking/ActionType.java | 14 +- .../org/matomo/java/tracking/AuthToken.java | 15 +- .../org/matomo/java/tracking/BulkRequest.java | 10 +- .../matomo/java/tracking/CustomVariable.java | 2 +- .../java/tracking/DaemonThreadFactory.java | 5 +- .../matomo/java/tracking/EcommerceItem.java | 12 +- .../java/tracking/ExecutorServiceCloser.java | 11 +- .../java/tracking/InvalidUrlException.java | 4 +- .../org/matomo/java/tracking/MatomoDate.java | 15 +- .../matomo/java/tracking/MatomoException.java | 4 +- .../matomo/java/tracking/MatomoLocale.java | 6 +- .../matomo/java/tracking/MatomoRequest.java | 374 +++++------------- .../java/tracking/MatomoRequestBuilder.java | 10 +- .../matomo/java/tracking/MatomoRequests.java | 218 +++++----- .../matomo/java/tracking/MatomoTracker.java | 233 +++++------ .../java/tracking/ProxyAuthenticator.java | 7 +- .../matomo/java/tracking/QueryCreator.java | 51 ++- .../java/tracking/RequestValidator.java | 26 +- .../java/org/matomo/java/tracking/Sender.java | 14 +- .../matomo/java/tracking/SenderFactory.java | 5 +- .../matomo/java/tracking/SenderProvider.java | 1 - .../tracking/ServiceLoaderSenderFactory.java | 14 +- .../java/tracking/TrackerConfiguration.java | 89 ++--- .../java/tracking/TrackingParameter.java | 1 - .../tracking/TrackingParameterMethod.java | 40 +- .../tracking/TrustingX509TrustManager.java | 8 +- .../matomo/java/tracking/package-info.java | 17 +- .../tracking/parameters/AcceptLanguage.java | 30 +- .../java/tracking/parameters/Country.java | 33 +- .../tracking/parameters/CustomVariable.java | 28 +- .../tracking/parameters/CustomVariables.java | 34 +- .../tracking/parameters/DeviceResolution.java | 10 +- .../tracking/parameters/EcommerceItem.java | 16 +- .../tracking/parameters/EcommerceItems.java | 9 +- .../matomo/java/tracking/parameters/Hex.java | 1 - .../java/tracking/parameters/RandomValue.java | 8 +- .../java/tracking/parameters/UniqueId.java | 8 +- .../java/tracking/parameters/VisitorId.java | 28 +- .../tracking/parameters/package-info.java | 10 +- .../java/tracking/servlet/CookieWrapper.java | 5 +- .../servlet/HttpServletRequestWrapper.java | 27 +- .../servlet/ServletMatomoRequest.java | 64 ++- .../piwik/java/tracking/CustomVariable.java | 2 +- .../piwik/java/tracking/EcommerceItem.java | 7 +- .../org/piwik/java/tracking/PiwikDate.java | 13 +- .../org/piwik/java/tracking/PiwikLocale.java | 4 +- .../org/piwik/java/tracking/PiwikRequest.java | 6 +- .../org/piwik/java/tracking/PiwikTracker.java | 17 +- .../org/piwik/java/tracking/package-info.java | 5 +- .../matomo/java/tracking/AuthTokenTest.java | 40 +- .../matomo/java/tracking/BulkRequestTest.java | 17 +- .../java/tracking/CustomVariableTest.java | 20 +- .../tracking/DaemonThreadFactoryTest.java | 19 +- .../java/tracking/EcommerceItemTest.java | 24 +- .../tracking/ExecutorServiceCloserTest.java | 30 +- .../tracking/InvalidUrlExceptionTest.java | 2 - .../java/tracking/MatomoExceptionTest.java | 1 - .../java/tracking/MatomoLocaleTest.java | 1 - .../tracking/MatomoRequestBuilderTest.java | 78 ++-- .../java/tracking/MatomoRequestTest.java | 21 +- .../java/tracking/MatomoRequestsTest.java | 123 +++--- .../matomo/java/tracking/MatomoTrackerIT.java | 75 ++-- .../matomo/java/tracking/PiwikDateTest.java | 9 +- .../matomo/java/tracking/PiwikLocaleTest.java | 8 +- .../java/tracking/PiwikRequestTest.java | 259 +++--------- .../java/tracking/ProxyAuthenticatorTest.java | 35 +- .../java/tracking/QueryCreatorTest.java | 305 +++++++------- .../java/tracking/RequestValidatorTest.java | 20 +- .../ServiceLoaderSenderFactoryTest.java | 14 +- .../org/matomo/java/tracking/TestSender.java | 20 +- .../java/tracking/TestSenderFactory.java | 3 +- .../matomo/java/tracking/TestThrowable.java | 1 - .../tracking/TrackerConfigurationTest.java | 21 +- .../tracking/TrackingParameterMethodTest.java | 39 +- .../TrustingX509TrustManagerTest.java | 3 +- .../parameters/AcceptLanguageTest.java | 13 +- .../java/tracking/parameters/CountryTest.java | 28 +- .../parameters/CustomVariableTest.java | 1 - .../parameters/CustomVariablesTest.java | 8 +- .../parameters/DeviceResolutionTest.java | 3 - .../parameters/EcommerceItemsTest.java | 47 +-- .../java/tracking/parameters/HexTest.java | 8 +- .../tracking/parameters/UniqueIdTest.java | 3 - .../tracking/parameters/VisitorIdTest.java | 41 +- .../servlet/ServletMatomoRequestTest.java | 88 ++--- .../java/tracking/CustomVariableTest.java | 1 - .../piwik/java/tracking/PiwikTrackerIT.java | 7 +- docker-compose.yml | 5 +- java11/pom.xml | 5 +- .../matomo/java/tracking/Java11Sender.java | 120 +++--- .../java/tracking/Java11SenderProvider.java | 47 +-- .../matomo/java/tracking/Java11SenderIT.java | 302 +++++++------- .../matomo/java/tracking/MatomoTrackerIT.java | 302 ++++++++------ .../matomo/java/tracking/PiwikTrackerIT.java | 187 ++++----- java8/pom.xml | 5 +- .../org/matomo/java/tracking/Java8Sender.java | 136 ++++--- .../java/tracking/Java8SenderProvider.java | 11 +- .../tracking/TrustingHostnameVerifier.java | 7 +- .../matomo/java/tracking/Java8SenderIT.java | 200 +++++----- .../matomo/java/tracking/MatomoTrackerIT.java | 300 ++++++++------ .../matomo/java/tracking/PiwikTrackerIT.java | 179 +++++---- .../TrustingHostnameVerifierTest.java | 3 +- pom.xml | 93 +++-- servlet-jakarta/pom.xml | 7 +- .../servlet/JakartaHttpServletWrapper.java | 30 +- .../tracking/servlet/MatomoTrackerFilter.java | 8 +- .../java/tracking/MatomoTrackerFilterIT.java | 54 ++- .../org/matomo/java/tracking/TestSender.java | 11 +- .../java/tracking/TestSenderFactory.java | 3 +- .../JakartaHttpServletWrapperTest.java | 11 +- .../servlet/MockHttpServletRequest.java | 29 +- servlet-javax/pom.xml | 7 +- .../servlet/JavaxHttpServletWrapper.java | 31 +- .../tracking/servlet/MatomoTrackerFilter.java | 11 +- .../java/tracking/MatomoTrackerFilterIT.java | 54 ++- .../org/matomo/java/tracking/TestSender.java | 11 +- .../java/tracking/TestSenderFactory.java | 3 +- .../servlet/JavaxHttpServletWrapperTest.java | 12 +- .../servlet/MockHttpServletRequest.java | 30 +- spring/pom.xml | 5 +- .../MatomoTrackerAutoConfiguration.java | 46 +-- .../spring/MatomoTrackerProperties.java | 55 ++- ...TrackerConfigurationBuilderCustomizer.java | 13 +- ...TrackerConfigurationBuilderCustomizer.java | 14 +- .../java/tracking/spring/package-info.java | 10 +- .../MatomoTrackerAutoConfigurationIT.java | 43 +- ...ackerConfigurationBuilderCustomizerIT.java | 7 +- test/pom.xml | 5 +- .../java/tracking/test/BulkExample.java | 29 +- .../java/tracking/test/ConsumerExample.java | 36 +- .../java/tracking/test/EcommerceExample.java | 67 ++-- .../tracking/test/MatomoServletTester.java | 26 +- .../tracking/test/MatomoTrackerTester.java | 86 ++-- .../java/tracking/test/SendExample.java | 28 +- .../test/ServletMatomoRequestExample.java | 26 +- 144 files changed, 2646 insertions(+), 3188 deletions(-) create mode 100644 .github/workflows/dependabot-auto-merge.yml diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index adbb253e..dfe985ab 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -1,4 +1,5 @@ --- + name: Bug report about: Create a report to help us improve title: "[BUG]" diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index d5a45c1a..71529ebf 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -1,4 +1,5 @@ --- + name: Feature request about: Suggest an idea for this project title: "[REQUEST]" diff --git a/.github/dependabot.yml b/.github/dependabot.yml index cd85bf2d..9334a827 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -12,3 +12,9 @@ updates: interval: weekly assignees: - dheid + - package-ecosystem: docker + directory: / + schedule: + interval: weekly + assignees: + - dheid diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 42d2b4f0..d05f593c 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,5 +1,4 @@ - - [ ] Ensure that the pull request title represents the desired changelog entry - [ ] Please describe what you did - [ ] Link to relevant issues in GitHub diff --git a/.github/workflows/dependabot-auto-merge.yml b/.github/workflows/dependabot-auto-merge.yml new file mode 100644 index 00000000..3936911a --- /dev/null +++ b/.github/workflows/dependabot-auto-merge.yml @@ -0,0 +1,17 @@ +name: Dependabot auto-merge + +on: pull_request + +jobs: + auto-merge: + runs-on: ubuntu-latest + if: github.actor == 'dependabot[bot]' + permissions: + pull-requests: write + contents: write + steps: + - uses: dependabot/fetch-metadata@v2 + - run: gh pr merge --auto --squash "$PR_URL" + env: + PR_URL: ${{ github.event.pull_request.html_url }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7dfdf721..3cd587b1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -89,5 +89,5 @@ This Code of Conduct is adapted from the [Contributor Covenant][homepage], versi available at [https://contributor-covenant.org/version/1/4][version] [homepage]: https://contributor-covenant.org - [version]: https://contributor-covenant.org/version/1/4/ + diff --git a/README.md b/README.md index db941103..0bd92494 100644 --- a/README.md +++ b/README.md @@ -69,9 +69,22 @@ Projects that use Matomo Java Tracker: ## What Is New? +### Version 3.5.x + +The Spring Boot Starter now requires Spring Boot 4. The `@NonNull` annotation has been migrated from +`org.springframework.lang.NonNull` to `org.jspecify.annotations.NonNull` across the Spring module. The +`PropertyMapper` usage was updated to align with the Spring Boot 4 API (`alwaysApplyingWhenNonNull()` was removed). + +Fixed a Java 8 compatibility issue in `JavaxHttpServletWrapper` where `Enumeration.asIterator()` (introduced in +Java 9) was used to iterate over HTTP header names. It has been replaced with a standard `while` loop. + +Dependency updates: Spring Boot 3.4.2 → 4.0.5, Jetty EE10 12.0.16 → 12.1.8, Jetty (javax) 10.0.24 → 10.0.26. + +The local testing Docker setup now uses MariaDB 12 and Matomo 5. + ### Version 3.4.x -We fixed a synchronization issue in the Java 8 sender (https://github.com/matomo-org/matomo-java-tracker/issues/168). +We fixed a synchronization issue in the Java 8 sender (https://github.com/matomo-org/matomo-java-tracker/issues/168). To consume the exact amount of space needed for the queries to send to Matomo, we need the collection size of the incoming requests. So we changed `Iterable` to `Collection` in some `MatomoTracker`. This could affect users, that use parameters of type `Iterable` in the tracker. Please use `Collection` instead. @@ -84,7 +97,7 @@ dependencies. Release notes can be found here: https://github.com/matomo-org/mat Here are the most important changes: -* Matomo Java Tracker 3.4.0 is compatible with Matomo 4 and 5 +* Matomo Java Tracker is compatible with Matomo 4 and 5 * less dependencies * new dimension parameter * special types allow to provide valid parameters now @@ -149,7 +162,7 @@ Add a dependency on Matomo Java Tracker using Maven. For Java 8: org.piwik.java.tracking matomo-java-tracker - 3.4.0 + 3.5.0 ``` @@ -160,7 +173,7 @@ For Java 11: org.piwik.java.tracking matomo-java-tracker-java11 - 3.4.0 + 3.5.0 ``` @@ -168,7 +181,7 @@ or Gradle (Java 8): ```groovy dependencies { - implementation("org.piwik.java.tracking:matomo-java-tracker:3.4.0") + implementation("org.piwik.java.tracking:matomo-java-tracker:3.5.0") } ``` @@ -176,25 +189,25 @@ or Gradle (Java 11): ```groovy dependencies { - implementation("org.piwik.java.tracking:matomo-java-tracker-java11:3.4.0") + implementation("org.piwik.java.tracking:matomo-java-tracker-java11:3.5.0") } ``` or Gradle with Kotlin DSL (Java 8) ```kotlin -implementation("org.piwik.java.tracking:matomo-java-tracker:3.4.0") +implementation("org.piwik.java.tracking:matomo-java-tracker:3.5.0") ``` or Gradle with Kotlin DSL (Java 11) ```kotlin -implementation("org.piwik.java.tracking:matomo-java-tracker-java11:3.4.0") +implementation("org.piwik.java.tracking:matomo-java-tracker-java11:3.5.0") ``` ### Spring Boot Module -If you use Spring Boot 3, you can use the Spring Boot Starter artifact. It will create a MatomoTracker bean for you +If you use Spring Boot 4, you can use the Spring Boot Starter artifact. It will create a MatomoTracker bean for you and allows you to configure the tracker via application properties. Add the following dependency to your build: ```xml @@ -202,7 +215,7 @@ and allows you to configure the tracker via application properties. Add the foll org.piwik.java.tracking matomo-java-tracker-spring-boot-starter - 3.4.0 + 3.5.0 ``` @@ -210,19 +223,19 @@ or Gradle: ```groovy dependencies { - implementation("org.piwik.java.tracking:matomo-java-tracker-spring-boot-starter:3.4.0") + implementation("org.piwik.java.tracking:matomo-java-tracker-spring-boot-starter:3.5.0") } ``` or Gradle with Kotlin DSL ```kotlin -implementation("org.piwik.java.tracking:matomo-java-tracker-spring-boot-starter:3.4.0") +implementation("org.piwik.java.tracking:matomo-java-tracker-spring-boot-starter:3.5.0") ``` The following properties are supported: -| Property Name | Description | +| Property Name | Description | |----------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------| | matomo.tracker.api-endpoint (required) | The URL to the Matomo Tracking API endpoint. Must be set. | | matomo.tracker.default-site-id | If you provide a default site id, it will be taken if the action does not contain a site id. | @@ -319,9 +332,8 @@ public class SendExample { ``` -This will send a request to the Matomo instance at https://www.yourdomain.com/matomo.php and track a page view for the -visitor customer@mail.com with the action name "Checkout" and action URL "https://www.yourdomain.com/checkout" for -the site with id 1. The request will be sent asynchronously, that means the method will return immediately and your +This will send a request to the Matomo instance at https://www.yourdomain.com/matomo.php and track an event in the +category "Training" with action "Workout completed" for the visitor customer@mail.com for the site with id 1. The request will be sent asynchronously, that means the method will return immediately and your application will not wait for the response of the Matomo server. In the configuration we set the default site id to 1 and configure the default auth token. With `logFailedTracking` we enable logging of failed tracking requests. @@ -429,11 +441,11 @@ public class BulkExample { } ``` -This will send two requests in a single HTTP call. The requests will be sent asynchronously. +This will send three requests in a single HTTP call. The requests will be sent asynchronously. Per default every request has the following default parameters: -| Parameter Name | Default Value | +| Parameter Name | Default Value | |-----------------|--------------------------------| | required | true | | visitorId | random 16 character hex string | @@ -687,7 +699,7 @@ version can be used in your local Maven repository for testing purposes, e.g. org.piwik.java.tracking matomo-java-tracker - 3.4.1-SNAPSHOT + 3.5.0-SNAPSHOT ``` @@ -700,34 +712,13 @@ Start the docker containers with docker-compose up -d ``` -You need to adapt your config.ini.php file and change -the following line: - -```ini -[General] -trusted_hosts[] = "localhost:8080" -``` - -to - -```ini -[General] -trusted_hosts[] = "localhost:8080" -``` - After that you can access Matomo at http://localhost:8080. You have to set up Matomo first. The database credentials are `matomo` and `matomo`. The database name is `matomo`. The (internal) database host address is `database`. The database -port is `3306`. Set the URL to http://localhost and enable ecommerce. +port is `3306`. Set the URL to http://localhost and enable ecommerce. Configure an auth token using the user interface +without HTTPS encryption enabled. -The following snippets helps you to do this quickly: - -```shell -docker-compose exec matomo sed -i 's/localhost/localhost:8080/g' /var/www/html/config/config.ini.php -``` - -After the installation you can run `MatomoTrackerTester` in the module `test` to test the tracker. It will send -multiple randomized -requests to the local Matomo instance. +After the installation you can run `MatomoTrackerTester` in the module `test` to test the tracker. Configure a valid +auth token before running the tests. The tester will send multiple randomized requests to the local Matomo instance. To enable debug logging, you append the following line to the `config.ini.php` file: @@ -780,7 +771,7 @@ provide tests for your changes. We use JUnit 5 for testing. Coverage should be a * [The original Piwik Java Tracker Implementation](https://github.com/summitsystemsinc/piwik-java-tracking) * [Matomo SDK for Android](https://github.com/matomo-org/matomo-sdk-android) -* [Piwik SDK Android]( https://github.com/lkogler/piwik-sdk-android) +* [Piwik SDK Android](https://github.com/lkogler/piwik-sdk-android) * [piwik-tracking](https://github.com/ralscha/piwik-tracking) * [Matomo Tracking API Java Client](https://github.com/dheid/matomo-tracker) -> Most of the code was integrated in the official Matomo Java Tracker @@ -793,4 +784,3 @@ This software is released under the BSD 3-Clause license. See [LICENSE](LICENSE) Copyright (c) 2015 General Electric Company. All rights reserved. - diff --git a/SECURITY.md b/SECURITY.md index 2ebd49e5..641463ae 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -5,10 +5,10 @@ The following versions of this library are currently being supported with security updates. -| Version | Supported | +| Version | Supported | |---------|------------------------| | >3 | :white_check_mark: yes | -| <=2 | ✖️ no | +| <=2 | ✖️ no | ## Reporting a Vulnerability diff --git a/core/pom.xml b/core/pom.xml index a716cbbb..e5949bd8 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -1,10 +1,11 @@ + 4.0.0 org.piwik.java.tracking matomo-java-tracker-parent - 3.4.1-SNAPSHOT + 3.5.0-SNAPSHOT ../pom.xml diff --git a/core/src/main/java/org/matomo/java/tracking/ActionType.java b/core/src/main/java/org/matomo/java/tracking/ActionType.java index 5033a776..f6431e68 100644 --- a/core/src/main/java/org/matomo/java/tracking/ActionType.java +++ b/core/src/main/java/org/matomo/java/tracking/ActionType.java @@ -4,29 +4,23 @@ import lombok.NonNull; import lombok.RequiredArgsConstructor; -/** - * The type of action performed (download or outlink). - */ +/** The type of action performed (download or outlink). */ @RequiredArgsConstructor public enum ActionType { DOWNLOAD(MatomoRequest.MatomoRequestBuilder::downloadUrl), LINK(MatomoRequest.MatomoRequestBuilder::outlinkUrl); - @NonNull - private final BiConsumer consumer; + @NonNull private final BiConsumer consumer; /** * Applies the action URL to the given builder. * - * @param builder The builder to apply the action URL to. + * @param builder The builder to apply the action URL to. * @param actionUrl The action URL to apply. - * * @return The builder with the action URL applied. */ public MatomoRequest.MatomoRequestBuilder applyUrl( - @NonNull MatomoRequest.MatomoRequestBuilder builder, - @NonNull String actionUrl - ) { + @NonNull MatomoRequest.MatomoRequestBuilder builder, @NonNull String actionUrl) { consumer.accept(builder, actionUrl); return builder; } diff --git a/core/src/main/java/org/matomo/java/tracking/AuthToken.java b/core/src/main/java/org/matomo/java/tracking/AuthToken.java index 1c775234..af8c62bb 100644 --- a/core/src/main/java/org/matomo/java/tracking/AuthToken.java +++ b/core/src/main/java/org/matomo/java/tracking/AuthToken.java @@ -17,13 +17,9 @@ private AuthToken() { @Nullable static String determineAuthToken( - @Nullable - String overrideAuthToken, - @Nullable - Iterable requests, - @Nullable - TrackerConfiguration trackerConfiguration - ) { + @Nullable String overrideAuthToken, + @Nullable Iterable requests, + @Nullable TrackerConfiguration trackerConfiguration) { if (isNotBlank(overrideAuthToken)) { return overrideAuthToken; } @@ -40,10 +36,7 @@ static String determineAuthToken( return null; } - private static boolean isNotBlank( - @Nullable - String str - ) { + private static boolean isNotBlank(@Nullable String str) { return str != null && !str.isEmpty() && !str.trim().isEmpty(); } } diff --git a/core/src/main/java/org/matomo/java/tracking/BulkRequest.java b/core/src/main/java/org/matomo/java/tracking/BulkRequest.java index 10483dc5..1c894ddf 100644 --- a/core/src/main/java/org/matomo/java/tracking/BulkRequest.java +++ b/core/src/main/java/org/matomo/java/tracking/BulkRequest.java @@ -12,15 +12,12 @@ @Value class BulkRequest { - @NonNull - Collection queries; + @NonNull Collection queries; - @Nullable - String authToken; + @Nullable String authToken; - byte[] toBytes( + byte[] toBytes() { - ) { if (queries.isEmpty()) { throw new IllegalArgumentException("Queries must not be empty"); } @@ -39,5 +36,4 @@ byte[] toBytes( } return payload.append('}').toString().getBytes(StandardCharsets.UTF_8); } - } diff --git a/core/src/main/java/org/matomo/java/tracking/CustomVariable.java b/core/src/main/java/org/matomo/java/tracking/CustomVariable.java index 04cbbee5..ad148b46 100644 --- a/core/src/main/java/org/matomo/java/tracking/CustomVariable.java +++ b/core/src/main/java/org/matomo/java/tracking/CustomVariable.java @@ -21,7 +21,7 @@ public class CustomVariable extends org.matomo.java.tracking.parameters.CustomVa /** * Instantiates a new custom variable. * - * @param key the key of the custom variable (required) + * @param key the key of the custom variable (required) * @param value the value of the custom variable (required) */ public CustomVariable(@NonNull String key, @NonNull String value) { diff --git a/core/src/main/java/org/matomo/java/tracking/DaemonThreadFactory.java b/core/src/main/java/org/matomo/java/tracking/DaemonThreadFactory.java index 9dc93b45..72e1bf0f 100644 --- a/core/src/main/java/org/matomo/java/tracking/DaemonThreadFactory.java +++ b/core/src/main/java/org/matomo/java/tracking/DaemonThreadFactory.java @@ -10,8 +10,9 @@ class DaemonThreadFactory implements ThreadFactory { @Override public Thread newThread(@NonNull Runnable r) { - Thread thread = new Thread(null, r, String.format("MatomoJavaTracker-%d", count.getAndIncrement())); + Thread thread = + new Thread(null, r, String.format("MatomoJavaTracker-%d", count.getAndIncrement())); thread.setDaemon(true); return thread; } -} \ No newline at end of file +} diff --git a/core/src/main/java/org/matomo/java/tracking/EcommerceItem.java b/core/src/main/java/org/matomo/java/tracking/EcommerceItem.java index 64ac6037..96f32379 100644 --- a/core/src/main/java/org/matomo/java/tracking/EcommerceItem.java +++ b/core/src/main/java/org/matomo/java/tracking/EcommerceItem.java @@ -7,7 +7,6 @@ package org.matomo.java.tracking; - /** * A user defined custom variable. * @@ -17,19 +16,16 @@ @Deprecated public class EcommerceItem extends org.matomo.java.tracking.parameters.EcommerceItem { - /** * Instantiates a new ecommerce item. * - * @param sku the sku (Stock Keeping Unit) of the item - * @param name the name of the item + * @param sku the sku (Stock Keeping Unit) of the item + * @param name the name of the item * @param category the category of the item - * @param price the price of the item + * @param price the price of the item * @param quantity the quantity of the item */ - public EcommerceItem( - String sku, String name, String category, Double price, Integer quantity - ) { + public EcommerceItem(String sku, String name, String category, Double price, Integer quantity) { super(sku, name, category, price, quantity); } } diff --git a/core/src/main/java/org/matomo/java/tracking/ExecutorServiceCloser.java b/core/src/main/java/org/matomo/java/tracking/ExecutorServiceCloser.java index 1ef11c97..b1f09920 100644 --- a/core/src/main/java/org/matomo/java/tracking/ExecutorServiceCloser.java +++ b/core/src/main/java/org/matomo/java/tracking/ExecutorServiceCloser.java @@ -4,17 +4,15 @@ import java.util.concurrent.TimeUnit; import lombok.NonNull; -/** - * Helps to close an executor service. - */ +/** Helps to close an executor service. */ public class ExecutorServiceCloser { /** * Closes the given executor service. * - *

This will check whether the executor service is already terminated, and if not, it - * initiates a shutdown and waits a minute. If the minute expires, the executor service - * is shutdown immediately. + *

This will check whether the executor service is already terminated, and if not, it initiates + * a shutdown and waits a minute. If the minute expires, the executor service is shutdown + * immediately. * * @param executorService The executor service to close */ @@ -38,5 +36,4 @@ public static void close(@NonNull ExecutorService executorService) { } } } - } diff --git a/core/src/main/java/org/matomo/java/tracking/InvalidUrlException.java b/core/src/main/java/org/matomo/java/tracking/InvalidUrlException.java index 0b243ab0..2f4c56e9 100644 --- a/core/src/main/java/org/matomo/java/tracking/InvalidUrlException.java +++ b/core/src/main/java/org/matomo/java/tracking/InvalidUrlException.java @@ -7,9 +7,7 @@ package org.matomo.java.tracking; -/** - * Thrown when an invalid URL is passed to the tracker. - */ +/** Thrown when an invalid URL is passed to the tracker. */ public class InvalidUrlException extends RuntimeException { InvalidUrlException(Throwable cause) { diff --git a/core/src/main/java/org/matomo/java/tracking/MatomoDate.java b/core/src/main/java/org/matomo/java/tracking/MatomoDate.java index 331f4923..3927dc2b 100644 --- a/core/src/main/java/org/matomo/java/tracking/MatomoDate.java +++ b/core/src/main/java/org/matomo/java/tracking/MatomoDate.java @@ -26,8 +26,8 @@ public class MatomoDate { private ZonedDateTime zonedDateTime; /** - * Allocates a Date object and initializes it so that it represents the time - * at which it was allocated, measured to the nearest millisecond. + * Allocates a Date object and initializes it so that it represents the time at which it was + * allocated, measured to the nearest millisecond. */ @Deprecated public MatomoDate() { @@ -35,9 +35,8 @@ public MatomoDate() { } /** - * Allocates a Date object and initializes it to represent the specified number - * of milliseconds since the standard base time known as "the epoch", namely - * January 1, 1970, 00:00:00 GMT. + * Allocates a Date object and initializes it to represent the specified number of milliseconds + * since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT. * * @param epochMilli the milliseconds since January 1, 1970, 00:00:00 GMT. */ @@ -47,8 +46,7 @@ public MatomoDate(long epochMilli) { } /** - * Sets the time zone of the String that will be returned by {@link #toString()}. - * Defaults to UTC. + * Sets the time zone of the String that will be returned by {@link #toString()}. Defaults to UTC. * * @param zone the TimeZone to set */ @@ -57,8 +55,7 @@ public void setTimeZone(ZoneId zone) { } /** - * Converts this datetime to the number of milliseconds from the epoch - * of 1970-01-01T00:00:00Z. + * Converts this datetime to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z. * * @return the number of milliseconds since the epoch of 1970-01-01T00:00:00Z * @throws ArithmeticException if numeric overflow occurs diff --git a/core/src/main/java/org/matomo/java/tracking/MatomoException.java b/core/src/main/java/org/matomo/java/tracking/MatomoException.java index 1f94a08f..99a3e90b 100644 --- a/core/src/main/java/org/matomo/java/tracking/MatomoException.java +++ b/core/src/main/java/org/matomo/java/tracking/MatomoException.java @@ -8,7 +8,8 @@ package org.matomo.java.tracking; /** - * Thrown when an error occurs while communicating with the Matomo server or when the request is invalid. + * Thrown when an error occurs while communicating with the Matomo server or when the request is + * invalid. */ public class MatomoException extends RuntimeException { @@ -21,5 +22,4 @@ public class MatomoException extends RuntimeException { MatomoException(String message, Throwable cause) { super(message, cause); } - } diff --git a/core/src/main/java/org/matomo/java/tracking/MatomoLocale.java b/core/src/main/java/org/matomo/java/tracking/MatomoLocale.java index d0dad67d..d7340351 100644 --- a/core/src/main/java/org/matomo/java/tracking/MatomoLocale.java +++ b/core/src/main/java/org/matomo/java/tracking/MatomoLocale.java @@ -33,11 +33,7 @@ public class MatomoLocale extends Country { * @deprecated Please use {@link Country} */ @Deprecated - public MatomoLocale( - @NonNull - Locale locale - ) { + public MatomoLocale(@NonNull Locale locale) { super(requireNonNull(locale, "Locale must not be null")); } - } diff --git a/core/src/main/java/org/matomo/java/tracking/MatomoRequest.java b/core/src/main/java/org/matomo/java/tracking/MatomoRequest.java index 42ef0c29..8c17fd35 100644 --- a/core/src/main/java/org/matomo/java/tracking/MatomoRequest.java +++ b/core/src/main/java/org/matomo/java/tracking/MatomoRequest.java @@ -59,10 +59,7 @@ public class MatomoRequest { * The ID of the website we're tracking a visit/action for. Only needed, if no default site id is * configured. */ - @TrackingParameter( - name = "idsite", - min = 1 - ) + @TrackingParameter(name = "idsite", min = 1) private Integer siteId; /** @@ -74,15 +71,11 @@ public class MatomoRequest { @TrackingParameter(name = "action_name") private String actionName; - /** - * The full URL for the current action. - */ + /** The full URL for the current action. */ @TrackingParameter(name = "url") private String actionUrl; - /** - * Defines the API version to use (default: 1). - */ + /** Defines the API version to use (default: 1). */ @TrackingParameter(name = "apiv") @Default private String apiVersion = "1"; @@ -91,9 +84,9 @@ public class MatomoRequest { * The unique visitor ID. See {@link VisitorId}. Default is {@link VisitorId#random()} * *

Since version 3.0.0 this parameter is of type {@link VisitorId} and not a String anymore. - * Use {@link VisitorId#fromHex(String)} to create a VisitorId from a hex string, - * {@link VisitorId#fromUUID(UUID)} to create it from a UUID or {@link VisitorId#fromHash(long)} - * to create it from a long value. + * Use {@link VisitorId#fromHex(String)} to create a VisitorId from a hex string, {@link + * VisitorId#fromUUID(UUID)} to create it from a UUID or {@link VisitorId#fromHash(long)} to + * create it from a long value. */ @TrackingParameter(name = "_id") @Default @@ -144,121 +137,76 @@ public class MatomoRequest { @TrackingParameter(name = "_idts") private Instant visitorFirstVisitTimestamp; - /** - * The campaign name. This parameter will only be used for the first pageview of a visit. - */ + /** The campaign name. This parameter will only be used for the first pageview of a visit. */ @TrackingParameter(name = "_rcn") private String campaignName; /** - * The campaign keyword (see - * Tracking Campaigns). Used to - * populate the Referrers > Campaigns report (clicking on a campaign loads all - * keywords for this campaign). This parameter will only be used for the first pageview of a - * visit. + * The campaign keyword (see Tracking + * Campaigns). Used to populate the Referrers > Campaigns report (clicking on a + * campaign loads all keywords for this campaign). This parameter will only be used for the first + * pageview of a visit. */ @TrackingParameter(name = "_rck") private String campaignKeyword; - /** - * The resolution of the device the visitor is using. - */ + /** The resolution of the device the visitor is using. */ @TrackingParameter(name = "res") private DeviceResolution deviceResolution; - /** - * The current hour (local time). - */ - @TrackingParameter( - name = "h", - min = 0, - max = 23 - ) + /** The current hour (local time). */ + @TrackingParameter(name = "h", min = 0, max = 23) private Integer currentHour; - /** - * The current minute (local time). - */ - @TrackingParameter( - name = "m", - min = 0, - max = 59 - ) + /** The current minute (local time). */ + @TrackingParameter(name = "m", min = 0, max = 59) private Integer currentMinute; - /** - * The current second (local time). - */ - @TrackingParameter( - name = "s", - min = 0, - max = 59 - ) + /** The current second (local time). */ + @TrackingParameter(name = "s", min = 0, max = 59) private Integer currentSecond; - /** - * Does the visitor use the Adobe Flash Plugin. - */ + /** Does the visitor use the Adobe Flash Plugin. */ @TrackingParameter(name = "fla") private Boolean pluginFlash; - /** - * Does the visitor use the Java plugin. - */ + /** Does the visitor use the Java plugin. */ @TrackingParameter(name = "java") private Boolean pluginJava; - /** - * Does the visitor use Director plugin. - */ + /** Does the visitor use Director plugin. */ @TrackingParameter(name = "dir") private Boolean pluginDirector; - /** - * Does the visitor use Quicktime plugin. - */ + /** Does the visitor use Quicktime plugin. */ @TrackingParameter(name = "qt") private Boolean pluginQuicktime; - /** - * Does the visitor use Realplayer plugin. - */ + /** Does the visitor use Realplayer plugin. */ @TrackingParameter(name = "realp") private Boolean pluginRealPlayer; - /** - * Does the visitor use a PDF plugin. - */ + /** Does the visitor use a PDF plugin. */ @TrackingParameter(name = "pdf") private Boolean pluginPDF; - /** - * Does the visitor use a Windows Media plugin. - */ + /** Does the visitor use a Windows Media plugin. */ @TrackingParameter(name = "wma") private Boolean pluginWindowsMedia; - /** - * Does the visitor use a Gears plugin. - */ + /** Does the visitor use a Gears plugin. */ @TrackingParameter(name = "gears") private Boolean pluginGears; - /** - * Does the visitor use a Silverlight plugin. - */ + /** Does the visitor use a Silverlight plugin. */ @TrackingParameter(name = "ag") private Boolean pluginSilverlight; - /** - * Does the visitor's client is known to support cookies. - */ + /** Does the visitor's client is known to support cookies. */ @TrackingParameter(name = "cookie") private Boolean supportsCookies; - /** - * An override value for the User-Agent HTTP header field. - */ + /** An override value for the User-Agent HTTP header field. */ @TrackingParameter(name = "ua") private String headerUserAgent; @@ -279,15 +227,11 @@ public class MatomoRequest { @TrackingParameter(name = "uid") private String userId; - /** - * defines the visitor ID for this request. - */ + /** defines the visitor ID for this request. */ @TrackingParameter(name = "cid") private VisitorId visitorCustomId; - /** - * will force a new visit to be created for this action. - */ + /** will force a new visit to be created for this action. */ @TrackingParameter(name = "new_visit") private Boolean newVisit; @@ -319,9 +263,7 @@ public class MatomoRequest { @TrackingParameter(name = "search") private String searchQuery; - /** - * When search is specified, you can optionally specify a search category with this parameter. - */ + /** When search is specified, you can optionally specify a search category with this parameter. */ @TrackingParameter(name = "search_cat") private String searchCategory; @@ -330,10 +272,7 @@ public class MatomoRequest { * results displayed on the results page. When keywords are tracked with &search_count=0 they will * appear in the "No Result Search Keyword" report. */ - @TrackingParameter( - name = "search_count", - min = 0 - ) + @TrackingParameter(name = "search_count", min = 0) private Long searchResultsCount; /** @@ -352,9 +291,7 @@ public class MatomoRequest { @TrackingParameter(name = "idgoal", min = 0) private Integer goalId; - /** - * The grand total for the ecommerce order (required when tracking an ecommerce order). - */ + /** The grand total for the ecommerce order (required when tracking an ecommerce order). */ @TrackingParameter(name = "revenue", min = 0) private Double ecommerceRevenue; @@ -374,21 +311,15 @@ public class MatomoRequest { @TrackingParameter(name = "ca") private Boolean customAction; - /** - * How long it took to connect to server. - */ + /** How long it took to connect to server. */ @TrackingParameter(name = "pf_net", min = 0) private Long networkTime; - /** - * How long it took the server to generate page. - */ + /** How long it took the server to generate page. */ @TrackingParameter(name = "pf_srv", min = 0) private Long serverTime; - /** - * How long it takes the browser to download the response from the server. - */ + /** How long it takes the browser to download the response from the server. */ @TrackingParameter(name = "pf_tfr", min = 0) private Long transferTime; @@ -406,57 +337,39 @@ public class MatomoRequest { @TrackingParameter(name = "pf_dm2", min = 0) private Long domCompletionTime; - /** - * How long it takes the browser to execute Javascript code waiting for the window.load event. - */ + /** How long it takes the browser to execute Javascript code waiting for the window.load event. */ @TrackingParameter(name = "pf_onl", min = 0) private Long onloadTime; - /** - * eg. Videos, Music, Games... - */ + /** eg. Videos, Music, Games... */ @TrackingParameter(name = "e_c") private String eventCategory; - /** - * An event action like Play, Pause, Duration, Add Playlist, Downloaded, Clicked... - */ + /** An event action like Play, Pause, Duration, Add Playlist, Downloaded, Clicked... */ @TrackingParameter(name = "e_a") private String eventAction; - /** - * The event name for example a Movie name, or Song name, or File name... - */ + /** The event name for example a Movie name, or Song name, or File name... */ @TrackingParameter(name = "e_n") private String eventName; - /** - * Some numeric value that represents the event value. - */ + /** Some numeric value that represents the event value. */ @TrackingParameter(name = "e_v", min = 0) private Double eventValue; - /** - * The name of the content. For instance 'Ad Foo Bar' - */ + /** The name of the content. For instance 'Ad Foo Bar' */ @TrackingParameter(name = "c_n") private String contentName; - /** - * The actual content piece. For instance the path to an image, video, audio, any text - */ + /** The actual content piece. For instance the path to an image, video, audio, any text */ @TrackingParameter(name = "c_p") private String contentPiece; - /** - * The target of the content. For instance the URL of a landing page - */ + /** The target of the content. For instance the URL of a landing page */ @TrackingParameter(name = "c_t") private String contentTarget; - /** - * The name of the interaction with the content. For instance a 'click' - */ + /** The name of the interaction with the content. For instance a 'click' */ @TrackingParameter(name = "c_i") private String contentInteraction; @@ -467,33 +380,23 @@ public class MatomoRequest { @TrackingParameter(name = "ec_id") private String ecommerceId; - /** - * Items in the Ecommerce order. - */ + /** Items in the Ecommerce order. */ @TrackingParameter(name = "ec_items") private EcommerceItems ecommerceItems; - /** - * The subtotal of the order; excludes shipping. - */ + /** The subtotal of the order; excludes shipping. */ @TrackingParameter(name = "ec_st", min = 0) private Double ecommerceSubtotal; - /** - * Tax amount of the order. - */ + /** Tax amount of the order. */ @TrackingParameter(name = "ec_tx", min = 0) private Double ecommerceTax; - /** - * Shipping cost of the order. - */ + /** Shipping cost of the order. */ @TrackingParameter(name = "ec_sh", min = 0) private Double ecommerceShippingCost; - /** - * Discount offered. - */ + /** Discount offered. */ @TrackingParameter(name = "ec_dt", min = 0) private Double ecommerceDiscount; @@ -509,16 +412,10 @@ public class MatomoRequest { * user specifically for accessing the Tracking API, and give the user only write permission on * the website(s). */ - @TrackingParameter( - name = "token_auth", - regex = "[a-z0-9]{32}" - ) + @TrackingParameter(name = "token_auth", regex = "[a-z0-9]{32}") private String authToken; - - /** - * Override value for the visitor IP (both IPv4 and IPv6 notations supported). - */ + /** Override value for the visitor IP (both IPv4 and IPv6 notations supported). */ @TrackingParameter(name = "cip") private String visitorIp; @@ -529,40 +426,26 @@ public class MatomoRequest { @TrackingParameter(name = "cdt") private Instant requestTimestamp; - /** - * An override value for the country. Must be a two-letter ISO 3166 Alpha-2 country code. - */ - @TrackingParameter( - name = "country", - maxLength = 2 - ) + /** An override value for the country. Must be a two-letter ISO 3166 Alpha-2 country code. */ + @TrackingParameter(name = "country", maxLength = 2) private Country visitorCountry; /** * An override value for the region. Should be set to a ISO 3166-2 region code, which are used by * MaxMind's and DB-IP's GeoIP2 databases. See here for a list of them for every country. */ - @TrackingParameter( - name = "region", - maxLength = 2 - ) + @TrackingParameter(name = "region", maxLength = 2) private String visitorRegion; - /** - * An override value for the city. The name of the city the visitor is located in, eg, Tokyo. - */ + /** An override value for the city. The name of the city the visitor is located in, eg, Tokyo. */ @TrackingParameter(name = "city") private String visitorCity; - /** - * An override value for the visitor's latitude, eg 22.456. - */ + /** An override value for the visitor's latitude, eg 22.456. */ @TrackingParameter(name = "lat", min = -90, max = 90) private Double visitorLatitude; - /** - * An override value for the visitor's longitude, eg 22.456. - */ + /** An override value for the visitor's longitude, eg 22.456. */ @TrackingParameter(name = "long", min = -180, max = 180) private Double visitorLongitude; @@ -603,7 +486,6 @@ public class MatomoRequest { @TrackingParameter(name = "bots") private Boolean trackBotRequests; - /** * Meant to hold a random value that is generated before each request. Using it helps avoid the * tracking request being cached by the browser or a proxy. @@ -634,8 +516,8 @@ public class MatomoRequest { * *

Custom action must be enabled for this. * - *

Typically a fully qualified class name of the exception, e.g. - * {@code java.lang.NullPointerException}. + *

Typically a fully qualified class name of the exception, e.g. {@code + * java.lang.NullPointerException}. * *

Optional for crash analytics */ @@ -695,8 +577,8 @@ public class MatomoRequest { /** * The Matomo session ID sent as a cookie {@code MATOMO_SESSID}. * - *

If not null a cookie with the name {@code MATOMO_SESSID} will be sent with the value of - * this parameter. + *

If not null a cookie with the name {@code MATOMO_SESSID} will be sent with the value of this + * parameter. */ private String sessionId; @@ -704,9 +586,8 @@ public class MatomoRequest { * Custom Dimension values for specific Custom Dimension IDs. * *

Custom Dimensions plugin must be - * installed. See the - * Custom Dimensions guide. Requires - * Matomo at least 2.15.1 + * installed. See the Custom Dimensions + * guide. Requires Matomo at least 2.15.1 */ private Map dimensions; @@ -736,21 +617,15 @@ public class MatomoRequest { /** * Create a new request from the id of the site being tracked and the full url for the current - * action. This constructor also sets: - *

-   * {@code
-   * Required = true
-   * Visior Id = random 16 character hex string
-   * Random Value = random 20 character hex string
-   * API version = 1
-   * Response as Image = false
-   * }
-   * 
- * Overwrite these values yourself as desired. + * action. This constructor also sets: * - * @param siteId the id of the website we're tracking a visit/action for - * @param actionUrl the full URL for the current action + *

{@code Required = true Visior Id = random 16 character hex string Random Value = random 20 + * character hex string API version = 1 Response as Image = false } * + *

Overwrite these values yourself as desired. + * + * @param siteId the id of the website we're tracking a visit/action for + * @param actionUrl the full URL for the current action * @deprecated Please use {@link MatomoRequest#request()} */ @Deprecated @@ -765,11 +640,10 @@ public MatomoRequest(int siteId, String actionUrl) { } /** - * Gets the list of objects currently stored at the specified custom tracking parameter. An empty + * Gets the list of objects currently stored at the specified custom tracking parameter. An empty * list will be returned if there are no objects set at that key. * - * @param key the key of the parameter whose list of objects to get. Cannot be null - * + * @param key the key of the parameter whose list of objects to get. Cannot be null * @return the parameter at the specified key, null if nothing at this key */ @Nullable @@ -786,15 +660,12 @@ public Object getCustomTrackingParameter(@NonNull String key) { * overwrite or clear named Matomo parameters with this method. A custom parameter that has the * same name as a named Matomo parameter will be sent in addition to that named parameter. * - * @param key the parameter's key. Cannot be null - * @param value the parameter's value. Removes the parameter if null - * + * @param key the parameter's key. Cannot be null + * @param value the parameter's value. Removes the parameter if null * @deprecated Use {@link MatomoRequest.MatomoRequestBuilder#additionalParameters(Map)} instead. */ @Deprecated - public void setCustomTrackingParameter( - @NonNull String key, @Nullable Object value - ) { + public void setCustomTrackingParameter(@NonNull String key, @Nullable Object value) { if (value == null) { if (additionalParameters != null) { @@ -809,12 +680,11 @@ public void setCustomTrackingParameter( } /** - * Add a custom tracking parameter to the specified key. If there is already a parameter at this + * Add a custom tracking parameter to the specified key. If there is already a parameter at this * key, the new value replaces the old value. * - * @param key the parameter's key. Cannot be null - * @param value the parameter's value. May be null - * + * @param key the parameter's key. Cannot be null + * @param value the parameter's value. May be null * @deprecated Use {@link MatomoRequest.MatomoRequestBuilder#additionalParameters(Map)} instead. */ @Deprecated @@ -829,7 +699,7 @@ public void addCustomTrackingParameter(@NonNull String key, @Nullable Object val * Removes all custom tracking parameters. * * @deprecated Please use {@link MatomoRequest.MatomoRequestBuilder#additionalParameters(Map)} - * instead so that you can manage the map yourself. + * instead so that you can manage the map yourself. */ @Deprecated public void clearCustomTrackingParameter() { @@ -851,10 +721,9 @@ public void enableEcommerce() { * Get the {@link EcommerceItem} at the specified index. * * @param index the index of the {@link EcommerceItem} to return - * * @return the {@link EcommerceItem} at the specified index * @deprecated Use @link {@link MatomoRequest.MatomoRequestBuilder#ecommerceItems(EcommerceItems)} - * instead + * instead */ @Nullable @Deprecated @@ -866,13 +735,12 @@ public EcommerceItem getEcommerceItem(int index) { } /** - * Add an {@link EcommerceItem} to this order. Ecommerce must be enabled, and EcommerceId and + * Add an {@link EcommerceItem} to this order. Ecommerce must be enabled, and EcommerceId and * EcommerceRevenue must first be set. * - * @param item the {@link EcommerceItem} to add. Cannot be null - * + * @param item the {@link EcommerceItem} to add. Cannot be null * @deprecated Use @link {@link MatomoRequest.MatomoRequestBuilder#ecommerceItems(EcommerceItems)} - * instead + * instead */ @Deprecated public void addEcommerceItem(@NonNull EcommerceItem item) { @@ -886,7 +754,7 @@ public void addEcommerceItem(@NonNull EcommerceItem item) { * Clears all {@link EcommerceItem} from this order. * * @deprecated Use @link {@link MatomoRequest.MatomoRequestBuilder#ecommerceItems(EcommerceItems)} - * instead + * instead */ @Deprecated public void clearEcommerceItems() { @@ -897,7 +765,6 @@ public void clearEcommerceItems() { * Get the page custom variable at the specified key. * * @param key the key of the variable to get - * * @return the variable at the specified key, null if key is not present * @deprecated Use the {@link #getPageCustomVariables()} method instead. */ @@ -913,8 +780,7 @@ public String getPageCustomVariable(String key) { /** * Get the page custom variable at the specified index. * - * @param index the index of the variable to get. Must be greater than 0 - * + * @param index the index of the variable to get. Must be greater than 0 * @return the variable at the specified key, null if nothing at this index * @deprecated Use {@link MatomoRequest#getPageCustomVariables()} instead */ @@ -937,16 +803,13 @@ private static CustomVariable getCustomVariable(CustomVariables customVariables, * Set a page custom variable with the specified key and value at the first available index. All * page custom variables with this key will be overwritten or deleted * - * @param key the key of the variable to set - * @param value the value of the variable to set at the specified key. A null value will remove - * this custom variable - * + * @param key the key of the variable to set + * @param value the value of the variable to set at the specified key. A null value will remove + * this custom variable * @deprecated Use {@link MatomoRequest#getPageCustomVariables()} instead */ @Deprecated - public void setPageCustomVariable( - @NonNull String key, @Nullable String value - ) { + public void setPageCustomVariable(@NonNull String key, @Nullable String value) { if (value == null) { if (pageCustomVariables == null) { return; @@ -964,16 +827,13 @@ public void setPageCustomVariable( /** * Set a page custom variable at the specified index. * - * @param customVariable the CustomVariable to set. A null value will remove the CustomVariable - * at the specified index - * @param index the index of he CustomVariable to set - * + * @param customVariable the CustomVariable to set. A null value will remove the CustomVariable at + * the specified index + * @param index the index of he CustomVariable to set * @deprecated Use {@link #getPageCustomVariables()} instead */ @Deprecated - public void setPageCustomVariable( - @Nullable CustomVariable customVariable, int index - ) { + public void setPageCustomVariable(@Nullable CustomVariable customVariable, int index) { if (pageCustomVariables == null) { if (customVariable == null) { return; @@ -985,8 +845,7 @@ public void setPageCustomVariable( @Deprecated private static void setCustomVariable( - CustomVariables customVariables, @Nullable CustomVariable customVariable, int index - ) { + CustomVariables customVariables, @Nullable CustomVariable customVariable, int index) { if (customVariable == null) { customVariables.remove(index); } else { @@ -1012,12 +871,10 @@ public MatomoDate getRequestDatetime() { * record data in the past, you will need to force * Matomo to re-process reports for the past dates. If you set the Request * Datetime to a datetime older than four hours then Auth Token must be set. If you - * set - * Request Datetime with a datetime in the last four hours then you - * don't need to pass Auth Token. - * - * @param matomoDate the datetime of the request to set. A null value will remove this parameter + * set Request Datetime with a datetime in the last four hours then you don't need to + * pass Auth Token. * + * @param matomoDate the datetime of the request to set. A null value will remove this parameter * @deprecated Use {@link #setRequestTimestamp(Instant)} instead */ @Deprecated @@ -1029,12 +886,10 @@ public void setRequestDatetime(MatomoDate matomoDate) { } } - /** * Get the visit custom variable at the specified key. * * @param key the key of the variable to get - * * @return the variable at the specified key, null if key is not present * @deprecated Use the {@link #getVisitCustomVariables()} method instead. */ @@ -1051,7 +906,6 @@ public String getUserCustomVariable(String key) { * Get the visit custom variable at the specified index. * * @param index the index of the variable to get - * * @return the variable at the specified index, null if nothing at this index * @deprecated Use {@link #getVisitCustomVariables()} instead */ @@ -1065,16 +919,13 @@ public CustomVariable getVisitCustomVariable(int index) { * Set a visit custom variable with the specified key and value at the first available index. All * visit custom variables with this key will be overwritten or deleted * - * @param key the key of the variable to set - * @param value the value of the variable to set at the specified key. A null value will remove - * this parameter - * + * @param key the key of the variable to set + * @param value the value of the variable to set at the specified key. A null value will remove + * this parameter * @deprecated Use {@link #setVisitCustomVariables(CustomVariables)} instead */ @Deprecated - public void setUserCustomVariable( - @NonNull String key, @Nullable String value - ) { + public void setUserCustomVariable(@NonNull String key, @Nullable String value) { if (value == null) { if (visitCustomVariables == null) { return; @@ -1092,16 +943,13 @@ public void setUserCustomVariable( /** * Set a user custom variable at the specified key. * - * @param customVariable the CustomVariable to set. A null value will remove the custom variable - * at the specified index - * @param index the index to set the customVariable at. - * + * @param customVariable the CustomVariable to set. A null value will remove the custom variable + * at the specified index + * @param index the index to set the customVariable at. * @deprecated Use {@link #setVisitCustomVariables(CustomVariables)} instead */ @Deprecated - public void setVisitCustomVariable( - @Nullable CustomVariable customVariable, int index - ) { + public void setVisitCustomVariable(@Nullable CustomVariable customVariable, int index) { if (visitCustomVariables == null) { if (customVariable == null) { return; @@ -1117,11 +965,9 @@ public void setVisitCustomVariable( *

Attention: If a parameter with the same name already exists, it will be appended twice! * * @param parameterName The name of the query parameter to append. Must not be null or empty. - * @param value The value of the query parameter to append. To remove the parameter, pass - * null. - * + * @param value The value of the query parameter to append. To remove the parameter, pass null. * @deprecated Use @link {@link MatomoRequest.MatomoRequestBuilder#additionalParameters(Map)} - * instead + * instead */ @Deprecated public void setParameter(@NonNull String parameterName, Object value) { @@ -1155,7 +1001,6 @@ public static org.matomo.java.tracking.MatomoRequestBuilder builder() { * Parses the given device resolution string and sets the {@link #deviceResolution} field. * * @param deviceResolution the device resolution string to parse. Format: "WIDTHxHEIGHT" - * * @deprecated Use {@link #setDeviceResolution(DeviceResolution)} instead. */ @Tolerate @@ -1167,5 +1012,4 @@ public void setDeviceResolution(@Nullable String deviceResolution) { this.deviceResolution = DeviceResolution.fromString(deviceResolution); } } - } diff --git a/core/src/main/java/org/matomo/java/tracking/MatomoRequestBuilder.java b/core/src/main/java/org/matomo/java/tracking/MatomoRequestBuilder.java index 01c43cd2..963e6916 100644 --- a/core/src/main/java/org/matomo/java/tracking/MatomoRequestBuilder.java +++ b/core/src/main/java/org/matomo/java/tracking/MatomoRequestBuilder.java @@ -5,24 +5,23 @@ import org.matomo.java.tracking.parameters.AcceptLanguage; /** - * The former MatomoRequestBuilder class has been moved to MatomoRequest.MatomoRequestBuilder. - * This class is only here for backwards compatibility. + * The former MatomoRequestBuilder class has been moved to MatomoRequest.MatomoRequestBuilder. This + * class is only here for backwards compatibility. * * @deprecated Use {@link MatomoRequest.MatomoRequestBuilder} instead. */ @Deprecated public class MatomoRequestBuilder extends MatomoRequest.MatomoRequestBuilder { - /** * Sets the tracking parameter for the accept languages of a user. Only here for backwards * compatibility. * * @param headerAcceptLanguage The accept language header of a user. Must be in the format - * specified in RFC 2616. + * specified in RFC 2616. * @return This builder * @deprecated Use {@link MatomoRequest.MatomoRequestBuilder#headerAcceptLanguage(AcceptLanguage)} - * in combination with {@link AcceptLanguage#fromHeader(String)} instead. + * in combination with {@link AcceptLanguage#fromHeader(String)} instead. */ @Deprecated public MatomoRequestBuilder headerAcceptLanguage(@Nullable String headerAcceptLanguage) { @@ -45,5 +44,4 @@ public MatomoRequestBuilder customTrackingParameters(@Nullable MapA content impression is a view of a content piece. The content piece can be a product, an - * article, a video, a banner, etc. The content piece can be specified by the parameters - * {@code piece} and {@code target}. The {@code name} parameter is required and should be a - * descriptive name of the content piece. + * article, a video, a banner, etc. The content piece can be specified by the parameters {@code + * piece} and {@code target}. The {@code name} parameter is required and should be a descriptive + * name of the content piece. * - * @param name The name of the content piece, like the name of a product or an article. Must not - * be null. Example: "SuperPhone". - * @param piece The content piece. Can be null. Example: "Smartphone". + * @param name The name of the content piece, like the name of a product or an article. Must not + * be null. Example: "SuperPhone". + * @param piece The content piece. Can be null. Example: "Smartphone". * @param target The target of the content piece, like the URL of a product or an article. Can be - * null. Example: "https://example.com/superphone". - * + * null. Example: "https://example.com/superphone". * @return A {@link MatomoRequest.MatomoRequestBuilder} object to add additional parameters. */ @edu.umd.cs.findbugs.annotations.NonNull public static MatomoRequest.MatomoRequestBuilder contentImpression( - @NonNull String name, @Nullable String piece, @Nullable String target - ) { + @NonNull String name, @Nullable String piece, @Nullable String target) { return MatomoRequest.request().contentName(name).contentPiece(piece).contentTarget(target); } /** * Creates a {@link MatomoRequest} object for a content interaction. * - *

Make sure you have tracked a content impression using the same content name and - * content piece, otherwise it will not count. + *

Make sure you have tracked a content impression using the same content name and content + * piece, otherwise it will not count. * *

A content interaction is an interaction with a content piece. The content piece can be a * product, an article, a video, a banner, etc. The content piece can be specified by the @@ -69,11 +65,10 @@ public static MatomoRequest.MatomoRequestBuilder contentImpression( * should be the type of the interaction, like "click" or "add-to-cart". * * @param interaction The type of the interaction. Must not be null. Example: "click". - * @param name The name of the content piece, like the name of a product or an article. - * @param piece The content piece. Can be null. Example: "Blog Article XYZ". - * @param target The target of the content piece, like the URL of a product or an article. - * Can be null. Example: "https://example.com/blog/article-xyz". - * + * @param name The name of the content piece, like the name of a product or an article. + * @param piece The content piece. Can be null. Example: "Blog Article XYZ". + * @param target The target of the content piece, like the URL of a product or an article. Can be + * null. Example: "https://example.com/blog/article-xyz". * @return A {@link MatomoRequest.MatomoRequestBuilder} object to add additional parameters. */ @edu.umd.cs.findbugs.annotations.NonNull @@ -81,10 +76,8 @@ public static MatomoRequest.MatomoRequestBuilder contentInteraction( @NonNull String interaction, @NonNull String name, @Nullable String piece, - @Nullable String target - ) { - return MatomoRequest - .request() + @Nullable String target) { + return MatomoRequest.request() .contentInteraction(interaction) .contentName(name) .contentPiece(piece) @@ -97,23 +90,21 @@ public static MatomoRequest.MatomoRequestBuilder contentInteraction( *

Requires Crash Analytics plugin to be enabled in the target Matomo instance. * *

A crash is an error that causes the application to stop working. The parameters {@code - * message} and {@code stackTrace} are required. The other parameters are optional. The - * {@code type} parameter can be used to specify the type of the crash, like - * {@code NullPointerException}. The {@code category} parameter can be used to specify the - * category of the crash, like payment failure. The {@code location}, {@code line} and - * {@code column} can be used to specify the location of the crash. The {@code location} parameter - * should be the name of the file where the crash occurred. The {@code line} and {@code column} - * parameters should be the line and column number of the crash. - * - * @param message The message of the crash. Must not be null. - * @param type The type of the crash. Can be null. Example: - * {@code java.lang.NullPointerException} - * @param category The category of the crash. Can be null. Example: "payment failure". + * message} and {@code stackTrace} are required. The other parameters are optional. The {@code + * type} parameter can be used to specify the type of the crash, like {@code + * NullPointerException}. The {@code category} parameter can be used to specify the category of + * the crash, like payment failure. The {@code location}, {@code line} and {@code column} can be + * used to specify the location of the crash. The {@code location} parameter should be the name of + * the file where the crash occurred. The {@code line} and {@code column} parameters should be the + * line and column number of the crash. + * + * @param message The message of the crash. Must not be null. + * @param type The type of the crash. Can be null. Example: {@code java.lang.NullPointerException} + * @param category The category of the crash. Can be null. Example: "payment failure". * @param stackTrace The stack trace of the crash. Must not be null. - * @param location The location of the crash. Can be null. Example: "MainActivity.java". - * @param line The line number of the crash. Can be null. Example: 42. - * @param column The column number of the crash. Can be null. Example: 23. - * + * @param location The location of the crash. Can be null. Example: "MainActivity.java". + * @param line The line number of the crash. Can be null. Example: 42. + * @param column The column number of the crash. Can be null. Example: 23. * @return A {@link MatomoRequest.MatomoRequestBuilder} object to add additional parameters. */ @edu.umd.cs.findbugs.annotations.NonNull @@ -124,16 +115,15 @@ public static MatomoRequest.MatomoRequestBuilder crash( @Nullable String stackTrace, @Nullable String location, @Nullable Integer line, - @Nullable Integer column - ) { + @Nullable Integer column) { return MatomoRequest.request() - .crashMessage(message) - .crashType(type) - .crashCategory(category) - .crashStackTrace(stackTrace) - .crashLocation(location) - .crashLine(line) - .crashColumn(column); + .crashMessage(message) + .crashType(type) + .crashCategory(category) + .crashStackTrace(stackTrace) + .crashLocation(location) + .crashLine(line) + .crashColumn(column); } /** @@ -145,24 +135,19 @@ public static MatomoRequest.MatomoRequestBuilder crash( * payment failure. * * @param throwable The throwable that caused the crash. Must not be null. - * @param category The category of the crash. Can be null. Example: "payment failure". - * + * @param category The category of the crash. Can be null. Example: "payment failure". * @return A {@link MatomoRequest.MatomoRequestBuilder} object to add additional parameters. */ @edu.umd.cs.findbugs.annotations.NonNull public static MatomoRequest.MatomoRequestBuilder crash( - @NonNull Throwable throwable, @Nullable String category - ) { - return MatomoRequest - .request() + @NonNull Throwable throwable, @Nullable String category) { + return MatomoRequest.request() .crashMessage(throwable.getMessage()) .crashCategory(category) .crashStackTrace(formatStackTrace(throwable)) .crashType(throwable.getClass().getName()) .crashLocation( - getFirstStackTraceElement(throwable) - .map(StackTraceElement::getFileName) - .orElse(null)) + getFirstStackTraceElement(throwable).map(StackTraceElement::getFileName).orElse(null)) .crashLine( getFirstStackTraceElement(throwable) .map(StackTraceElement::getLineNumber) @@ -178,8 +163,7 @@ private static String formatStackTrace(@Nullable Throwable throwable) { @edu.umd.cs.findbugs.annotations.NonNull private static Optional getFirstStackTraceElement( - @edu.umd.cs.findbugs.annotations.NonNull Throwable throwable - ) { + @edu.umd.cs.findbugs.annotations.NonNull Throwable throwable) { StackTraceElement[] stackTrace = throwable.getStackTrace(); if (stackTrace == null || stackTrace.length == 0) { return Optional.empty(); @@ -194,13 +178,10 @@ private static Optional getFirstStackTraceElement( *

The {@code revenue} parameter is required and should be the total revenue of the cart. * * @param revenue The total revenue of the cart. Must not be null. - * * @return A {@link MatomoRequest.MatomoRequestBuilder} object to add additional parameters. */ @edu.umd.cs.findbugs.annotations.NonNull - public static MatomoRequest.MatomoRequestBuilder ecommerceCartUpdate( - @NonNull Double revenue - ) { + public static MatomoRequest.MatomoRequestBuilder ecommerceCartUpdate(@NonNull Double revenue) { return MatomoRequest.request().ecommerceRevenue(revenue); } @@ -211,22 +192,20 @@ public static MatomoRequest.MatomoRequestBuilder ecommerceCartUpdate( * and reported in Matomo reports. * *

The {@code id} and {@code revenue} parameters are required and should be the order ID and - * the total revenue of the order. The other parameters are optional. The {@code subtotal}, - * {@code tax}, {@code shippingCost} and {@code discount} parameters should be the subtotal, tax, + * the total revenue of the order. The other parameters are optional. The {@code subtotal}, {@code + * tax}, {@code shippingCost} and {@code discount} parameters should be the subtotal, tax, * shipping cost and discount of the order. * - *

If the Ecommerce order contains items (products), you must call - * {@link MatomoRequest.MatomoRequestBuilder#ecommerceItems(EcommerceItems)} to add the items to - * the request. + *

If the Ecommerce order contains items (products), you must call {@link + * MatomoRequest.MatomoRequestBuilder#ecommerceItems(EcommerceItems)} to add the items to the + * request. * - * @param id An order ID. Can be a stock keeping unit (SKU) or a unique ID. Must not be - * null. - * @param revenue The total revenue of the order. Must not be null. - * @param subtotal The subtotal of the order. Can be null. - * @param tax The tax of the order. Can be null. + * @param id An order ID. Can be a stock keeping unit (SKU) or a unique ID. Must not be null. + * @param revenue The total revenue of the order. Must not be null. + * @param subtotal The subtotal of the order. Can be null. + * @param tax The tax of the order. Can be null. * @param shippingCost The shipping cost of the order. Can be null. - * @param discount The discount of the order. Can be null. - * + * @param discount The discount of the order. Can be null. * @return A {@link MatomoRequest.MatomoRequestBuilder} object to add additional parameters. */ @edu.umd.cs.findbugs.annotations.NonNull @@ -236,32 +215,30 @@ public static MatomoRequest.MatomoRequestBuilder ecommerceOrder( @Nullable Double subtotal, @Nullable Double tax, @Nullable Double shippingCost, - @Nullable Double discount - ) { + @Nullable Double discount) { return MatomoRequest.request() - .ecommerceId(id) - .ecommerceRevenue(revenue) - .ecommerceSubtotal(subtotal) - .ecommerceTax(tax) - .ecommerceShippingCost(shippingCost) - .ecommerceDiscount(discount); + .ecommerceId(id) + .ecommerceRevenue(revenue) + .ecommerceSubtotal(subtotal) + .ecommerceTax(tax) + .ecommerceShippingCost(shippingCost) + .ecommerceDiscount(discount); } /** * Creates a {@link MatomoRequest} object for an event. * *

The {@code category} and {@code action} parameters are required and should be the category - * and action of the event. The {@code name} and {@code value} parameters are optional. The - * {@code category} parameter should be a category of the event, like "Travel". The {@code action} + * and action of the event. The {@code name} and {@code value} parameters are optional. The {@code + * category} parameter should be a category of the event, like "Travel". The {@code action} * parameter should be an action of the event, like "Book flight". The {@code name} parameter * should be the name of the event, like "Flight to Berlin". The {@code value} parameter should be * the value of the event, like the price of the flight. * * @param category The category of the event. Must not be null. Example: "Music" - * @param action The action of the event. Must not be null. Example: "Play" - * @param name The name of the event. Can be null. Example: "Edvard Grieg - The Death of Ase" - * @param value The value of the event. Can be null. Example: 9.99 - * + * @param action The action of the event. Must not be null. Example: "Play" + * @param name The name of the event. Can be null. Example: "Edvard Grieg - The Death of Ase" + * @param value The value of the event. Can be null. Example: 9.99 * @return A {@link MatomoRequest.MatomoRequestBuilder} object to add additional parameters. */ @edu.umd.cs.findbugs.annotations.NonNull @@ -269,13 +246,12 @@ public static MatomoRequest.MatomoRequestBuilder event( @NonNull String category, @NonNull String action, @Nullable String name, - @Nullable Double value - ) { + @Nullable Double value) { return MatomoRequest.request() - .eventCategory(category) - .eventAction(action) - .eventName(name) - .eventValue(value); + .eventCategory(category) + .eventAction(action) + .eventName(name) + .eventValue(value); } /** @@ -286,15 +262,12 @@ public static MatomoRequest.MatomoRequestBuilder event( * the revenue of the conversion. The {@code name} parameter should be the name of the conversion. * The {@code value} parameter should be the value of the conversion. * - * @param id The ID of the goal. Must not be null. Example: 1 + * @param id The ID of the goal. Must not be null. Example: 1 * @param revenue The revenue of the conversion. Can be null. Example: 9.99 - * * @return A {@link MatomoRequest.MatomoRequestBuilder} object to add additional parameters. */ @edu.umd.cs.findbugs.annotations.NonNull - public static MatomoRequest.MatomoRequestBuilder goal( - int id, @Nullable Double revenue - ) { + public static MatomoRequest.MatomoRequestBuilder goal(int id, @Nullable Double revenue) { return MatomoRequest.request().goalId(id).ecommerceRevenue(revenue); } @@ -304,13 +277,10 @@ public static MatomoRequest.MatomoRequestBuilder goal( *

The {@code name} parameter is required and should be the name of the page. * * @param name The name of the page. Must not be null. Example: "Home" - * * @return A {@link MatomoRequest.MatomoRequestBuilder} object to add additional parameters. */ @edu.umd.cs.findbugs.annotations.NonNull - public static MatomoRequest.MatomoRequestBuilder pageView( - @NonNull String name - ) { + public static MatomoRequest.MatomoRequestBuilder pageView(@NonNull String name) { return MatomoRequest.request().actionName(name); } @@ -319,34 +289,32 @@ public static MatomoRequest.MatomoRequestBuilder pageView( * *

These are used to populate reports in Actions > Site Search. * - *

The {@code query} parameter is required and should be the search query. The {@code - * category} and {@code resultsCount} parameters are optional. The {@code category} parameter - * should be the category of the search, like "Music". The {@code resultsCount} parameter should - * be the number of results of the search. + *

The {@code query} parameter is required and should be the search query. The {@code category} + * and {@code resultsCount} parameters are optional. The {@code category} parameter should be the + * category of the search, like "Music". The {@code resultsCount} parameter should be the number + * of results of the search. * - * @param query The search query. Must not be null. Example: "Edvard Grieg" - * @param category The category of the search. Can be null. Example: "Music" + * @param query The search query. Must not be null. Example: "Edvard Grieg" + * @param category The category of the search. Can be null. Example: "Music" * @param resultsCount The number of results of the search. Can be null. Example: 42 - * * @return A {@link MatomoRequest.MatomoRequestBuilder} object to add additional parameters. */ @edu.umd.cs.findbugs.annotations.NonNull public static MatomoRequest.MatomoRequestBuilder siteSearch( - @NonNull String query, @Nullable String category, @Nullable Long resultsCount - ) { + @NonNull String query, @Nullable String category, @Nullable Long resultsCount) { return MatomoRequest.request() - .searchQuery(query) - .searchCategory(category) - .searchResultsCount(resultsCount); + .searchQuery(query) + .searchCategory(category) + .searchResultsCount(resultsCount); } /** * Creates a {@link MatomoRequest} object for a ping. * - *

Ping requests do not track new actions. If they are sent within the standard visit - * length (see global.ini.php), they will extend the existing visit and the current last action - * for the visit. If after the standard visit length, ping requests will create a new visit using - * the last action in the last known visit. + *

Ping requests do not track new actions. If they are sent within the standard visit length + * (see global.ini.php), they will extend the existing visit and the current last action for the + * visit. If after the standard visit length, ping requests will create a new visit using the last + * action in the last known visit. * * @return A {@link MatomoRequest.MatomoRequestBuilder} object to add additional parameters. */ @@ -354,6 +322,4 @@ public static MatomoRequest.MatomoRequestBuilder siteSearch( public static MatomoRequest.MatomoRequestBuilder ping() { return MatomoRequest.request().ping(true); } - - } diff --git a/core/src/main/java/org/matomo/java/tracking/MatomoTracker.java b/core/src/main/java/org/matomo/java/tracking/MatomoTracker.java index 3c38d017..0b382ecc 100644 --- a/core/src/main/java/org/matomo/java/tracking/MatomoTracker.java +++ b/core/src/main/java/org/matomo/java/tracking/MatomoTracker.java @@ -23,13 +23,14 @@ /** * The main class that sends {@link MatomoRequest}s to a specified Matomo server. * - *

Contains several methods to send requests synchronously and asynchronously. The asynchronous methods return a - * {@link CompletableFuture} that can be used to wait for the request to finish. The synchronous methods block until - * the request is finished. The asynchronous methods are more efficient if you want to send multiple requests at once. + *

Contains several methods to send requests synchronously and asynchronously. The asynchronous + * methods return a {@link CompletableFuture} that can be used to wait for the request to finish. + * The synchronous methods block until the request is finished. The asynchronous methods are more + * efficient if you want to send multiple requests at once. * - *

Configure this tracker using the {@link TrackerConfiguration} class. You can use the - * {@link TrackerConfiguration#builder()} to create a new configuration. The configuration is immutable and can be - * reused for multiple trackers. + *

Configure this tracker using the {@link TrackerConfiguration} class. You can use the {@link + * TrackerConfiguration#builder()} to create a new configuration. The configuration is immutable and + * can be reused for multiple trackers. * *

The tracker is thread-safe and can be used by multiple threads at once. * @@ -46,60 +47,55 @@ public class MatomoTracker implements AutoCloseable { private Sender sender; /** - * Creates a tracker that will send {@link MatomoRequest}s to the specified - * Tracking HTTP API endpoint. + * Creates a tracker that will send {@link MatomoRequest}s to the specified Tracking HTTP API + * endpoint. * - * @param hostUrl url endpoint to send requests to. Usually in the format - * https://your-matomo-domain.tld/matomo.php. Must not be null + * @param hostUrl url endpoint to send requests to. Usually in the format + * https://your-matomo-domain.tld/matomo.php. Must not be null * @deprecated Please use {@link MatomoTracker#MatomoTracker(TrackerConfiguration)} */ @Deprecated - public MatomoTracker( - @NonNull String hostUrl - ) { + public MatomoTracker(@NonNull String hostUrl) { this(hostUrl, 0); } /** - * Creates a tracker that will send {@link MatomoRequest}s to the specified - * Tracking HTTP API endpoint. + * Creates a tracker that will send {@link MatomoRequest}s to the specified Tracking HTTP API + * endpoint. * - * @param hostUrl url endpoint to send requests to. Usually in the format - * https://your-matomo-domain.tld/matomo.php. + * @param hostUrl url endpoint to send requests to. Usually in the format + * https://your-matomo-domain.tld/matomo.php. * @param timeout the timeout of the sent request in milliseconds or -1 if not set * @deprecated Please use {@link MatomoTracker#MatomoTracker(TrackerConfiguration)} */ @Deprecated - public MatomoTracker( - @NonNull String hostUrl, int timeout - ) { + public MatomoTracker(@NonNull String hostUrl, int timeout) { this(hostUrl, null, 0, timeout); } /** - * Creates a tracker that will send {@link MatomoRequest}s to the specified - * Tracking HTTP API endpoint. + * Creates a tracker that will send {@link MatomoRequest}s to the specified Tracking HTTP API + * endpoint. * - * @param hostUrl url endpoint to send requests to. Usually in the format - * https://your-matomo-domain.tld/matomo.php. + * @param hostUrl url endpoint to send requests to. Usually in the format + * https://your-matomo-domain.tld/matomo.php. * @param proxyHost The hostname or IP address of an optional HTTP proxy, null allowed * @param proxyPort The port of an HTTP proxy or -1 if not set - * @param timeout the timeout of the request in milliseconds or -1 if not set + * @param timeout the timeout of the request in milliseconds or -1 if not set * @deprecated Please use {@link MatomoTracker#MatomoTracker(TrackerConfiguration)} */ @Deprecated public MatomoTracker( - @NonNull String hostUrl, @Nullable String proxyHost, int proxyPort, int timeout - ) { - this(TrackerConfiguration - .builder() - .enabled(true) - .apiEndpoint(URI.create(hostUrl)) - .proxyHost(proxyHost) - .proxyPort(proxyPort) - .connectTimeout(timeout == -1 ? Duration.ofSeconds(5L) : Duration.ofSeconds(timeout)) - .socketTimeout(timeout == -1 ? Duration.ofSeconds(5L) : Duration.ofSeconds(timeout)) - .build()); + @NonNull String hostUrl, @Nullable String proxyHost, int proxyPort, int timeout) { + this( + TrackerConfiguration.builder() + .enabled(true) + .apiEndpoint(URI.create(hostUrl)) + .proxyHost(proxyHost) + .proxyPort(proxyPort) + .connectTimeout(timeout == -1 ? Duration.ofSeconds(5L) : Duration.ofSeconds(timeout)) + .socketTimeout(timeout == -1 ? Duration.ofSeconds(5L) : Duration.ofSeconds(timeout)) + .build()); } /** @@ -107,36 +103,33 @@ public MatomoTracker( * * @param trackerConfiguration Configurations parameters (you can use a builder) */ - public MatomoTracker( - @NonNull TrackerConfiguration trackerConfiguration - ) { + public MatomoTracker(@NonNull TrackerConfiguration trackerConfiguration) { trackerConfiguration.validate(); this.trackerConfiguration = trackerConfiguration; } /** - * Creates a tracker that will send {@link MatomoRequest}s to the specified - * Tracking HTTP API endpoint via the provided proxy. + * Creates a tracker that will send {@link MatomoRequest}s to the specified Tracking HTTP API + * endpoint via the provided proxy. * - * @param hostUrl url endpoint to send requests to. Usually in the format - * https://your-matomo-domain.tld/matomo.php. + * @param hostUrl url endpoint to send requests to. Usually in the format + * https://your-matomo-domain.tld/matomo.php. * @param proxyHost url endpoint for the proxy, null allowed * @param proxyPort proxy server port number or -1 if not set * @deprecated Please use {@link MatomoTracker#MatomoTracker(TrackerConfiguration)} */ @Deprecated - public MatomoTracker( - @NonNull String hostUrl, @Nullable String proxyHost, int proxyPort - ) { + public MatomoTracker(@NonNull String hostUrl, @Nullable String proxyHost, int proxyPort) { this(hostUrl, proxyHost, proxyPort, -1); } /** * Sends a tracking request to Matomo using the HTTP GET method. * - *

Use this method if you want to send a single request. If you want to send multiple requests at once, use - * {@link #sendBulkRequest(Iterable)} instead. If you want to send multiple requests asynchronously, use - * {@link #sendRequestAsync(MatomoRequest)} or {@link #sendBulkRequestAsync(Collection)} instead. + *

Use this method if you want to send a single request. If you want to send multiple requests + * at once, use {@link #sendBulkRequest(Iterable)} instead. If you want to send multiple requests + * asynchronously, use {@link #sendRequestAsync(MatomoRequest)} or {@link + * #sendBulkRequestAsync(Collection)} instead. * * @param request request to send. must not be null */ @@ -153,45 +146,45 @@ public void sendRequest(@NonNull MatomoRequest request) { private void initializeSender() { if (sender == null) { - sender = senderFactory.createSender(trackerConfiguration, new QueryCreator(trackerConfiguration)); + sender = + senderFactory.createSender(trackerConfiguration, new QueryCreator(trackerConfiguration)); } } /** * Send a request asynchronously via HTTP GET. * - *

Use this method if you want to send a single request. If you want to send multiple requests at once, use - * {@link #sendBulkRequestAsync(Collection)} instead. If you want to send multiple requests synchronously, use - * {@link #sendRequest(MatomoRequest)} or {@link #sendBulkRequest(Iterable)} instead. + *

Use this method if you want to send a single request. If you want to send multiple requests + * at once, use {@link #sendBulkRequestAsync(Collection)} instead. If you want to send multiple + * requests synchronously, use {@link #sendRequest(MatomoRequest)} or {@link + * #sendBulkRequest(Iterable)} instead. * * @param request request to send * @return completable future to let you know when the request is done. Contains the request. */ - public CompletableFuture sendRequestAsync( - @NonNull MatomoRequest request - ) { + public CompletableFuture sendRequestAsync(@NonNull MatomoRequest request) { return sendRequestAsync(request, Function.identity()); } /** - * Send a request asynchronously via HTTP GET and specify a callback that gets executed when the response arrives. + * Send a request asynchronously via HTTP GET and specify a callback that gets executed when the + * response arrives. * - *

Use this method if you want to send a single request. If you want to send multiple requests at once, use - * {@link #sendBulkRequestAsync(Collection, Consumer)} instead. If you want to send multiple requests synchronously, - * use {@link #sendRequest(MatomoRequest)} or {@link #sendBulkRequest(Iterable)} instead. + *

Use this method if you want to send a single request. If you want to send multiple requests + * at once, use {@link #sendBulkRequestAsync(Collection, Consumer)} instead. If you want to send + * multiple requests synchronously, use {@link #sendRequest(MatomoRequest)} or {@link + * #sendBulkRequest(Iterable)} instead. * - * @param request request to send + * @param request request to send * @param callback callback that gets executed when response arrives, must not be null - * @return a completable future to let you know when the request is done. The future contains - * the callback result. - * @deprecated Please use {@link MatomoTracker#sendRequestAsync(MatomoRequest)} in combination with - * {@link CompletableFuture#thenAccept(Consumer)} instead + * @return a completable future to let you know when the request is done. The future contains the + * callback result. + * @deprecated Please use {@link MatomoTracker#sendRequestAsync(MatomoRequest)} in combination + * with {@link CompletableFuture#thenAccept(Consumer)} instead */ @Deprecated public CompletableFuture sendRequestAsync( - @NonNull MatomoRequest request, - @NonNull Function callback - ) { + @NonNull MatomoRequest request, @NonNull Function callback) { if (trackerConfiguration.isEnabled()) { applyGoalIdAndCheckSiteId(request); log.debug("Sending async request via GET: {}", request); @@ -203,14 +196,15 @@ public CompletableFuture sendRequestAsync( return CompletableFuture.completedFuture(null); } - private void applyGoalIdAndCheckSiteId( - @NonNull MatomoRequest request - ) { - if (request.getGoalId() == null && ( - request.getEcommerceId() != null || request.getEcommerceRevenue() != null - || request.getEcommerceDiscount() != null || request.getEcommerceItems() != null + private void applyGoalIdAndCheckSiteId(@NonNull MatomoRequest request) { + if (request.getGoalId() == null + && (request.getEcommerceId() != null + || request.getEcommerceRevenue() != null + || request.getEcommerceDiscount() != null + || request.getEcommerceItems() != null || request.getEcommerceLastOrderTimestamp() != null - || request.getEcommerceShippingCost() != null || request.getEcommerceSubtotal() != null + || request.getEcommerceShippingCost() != null + || request.getEcommerceSubtotal() != null || request.getEcommerceTax() != null)) { request.setGoalId(0); } @@ -222,9 +216,9 @@ private void applyGoalIdAndCheckSiteId( /** * Send multiple requests in a single HTTP POST call. * - *

More efficient than sending several individual requests. If you want to send a single request, use - * {@link #sendRequest(MatomoRequest)} instead. If you want to send multiple requests asynchronously, use - * {@link #sendBulkRequestAsync(Collection)} instead. + *

More efficient than sending several individual requests. If you want to send a single + * request, use {@link #sendRequest(MatomoRequest)} instead. If you want to send multiple requests + * asynchronously, use {@link #sendBulkRequestAsync(Collection)} instead. * * @param requests the requests to send */ @@ -235,9 +229,9 @@ public void sendBulkRequest(MatomoRequest... requests) { /** * Send multiple requests in a single HTTP POST call. * - *

More efficient than sending several individual requests. If you want to send a single request, use - * {@link #sendRequest(MatomoRequest)} instead. If you want to send multiple requests asynchronously, use - * {@link #sendBulkRequestAsync(Collection)} instead. + *

More efficient than sending several individual requests. If you want to send a single + * request, use {@link #sendRequest(MatomoRequest)} instead. If you want to send multiple requests + * asynchronously, use {@link #sendBulkRequestAsync(Collection)} instead. * * @param requests the requests to send */ @@ -246,23 +240,22 @@ public void sendBulkRequest(@NonNull Iterable requests) } /** - * Send multiple requests in a single HTTP POST call. More efficient than sending - * several individual requests. + * Send multiple requests in a single HTTP POST call. More efficient than sending several + * individual requests. * - *

Specify the AuthToken if parameters that require an auth token is used. If you want to send a single request, - * use {@link #sendRequest(MatomoRequest)} instead. If you want to send multiple requests asynchronously, use - * {@link #sendBulkRequestAsync(Collection)} instead. + *

Specify the AuthToken if parameters that require an auth token is used. If you want to send + * a single request, use {@link #sendRequest(MatomoRequest)} instead. If you want to send multiple + * requests asynchronously, use {@link #sendBulkRequestAsync(Collection)} instead. * - * @param requests the requests to send - * @param authToken specify if any of the parameters use require AuthToken, if null the default auth token from the - * request or the tracker configuration is used. - * @deprecated use {@link #sendBulkRequest(Iterable)} instead and set the auth token in the tracker configuration or - * the requests directly. + * @param requests the requests to send + * @param authToken specify if any of the parameters use require AuthToken, if null the default + * auth token from the request or the tracker configuration is used. + * @deprecated use {@link #sendBulkRequest(Iterable)} instead and set the auth token in the + * tracker configuration or the requests directly. */ @Deprecated public void sendBulkRequest( - @NonNull Iterable requests, @Nullable String authToken - ) { + @NonNull Iterable requests, @Nullable String authToken) { if (trackerConfiguration.isEnabled()) { for (MatomoRequest request : requests) { applyGoalIdAndCheckSiteId(request); @@ -276,8 +269,8 @@ public void sendBulkRequest( } /** - * Send multiple requests in a single HTTP call. More efficient than sending - * several individual requests. + * Send multiple requests in a single HTTP call. More efficient than sending several individual + * requests. * * @param requests the requests to send * @return completable future to let you know when the request is done @@ -287,37 +280,34 @@ public CompletableFuture sendBulkRequestAsync(MatomoRequest... requests) { } /** - * Send multiple requests in a single HTTP call. More efficient than sending - * several individual requests. + * Send multiple requests in a single HTTP call. More efficient than sending several individual + * requests. * * @param requests the requests to send * @return completable future to let you know when the request is done */ public CompletableFuture sendBulkRequestAsync( - @NonNull Collection requests - ) { + @NonNull Collection requests) { return sendBulkRequestAsync(requests, null, null); } /** - * Send multiple requests in a single HTTP call. More efficient than sending - * several individual requests. Specify the AuthToken if parameters that require - * an auth token is used. + * Send multiple requests in a single HTTP call. More efficient than sending several individual + * requests. Specify the AuthToken if parameters that require an auth token is used. * - * @param requests the requests to send - * @param authToken specify if any of the parameters use require AuthToken, if null the default auth token from the - * request or the tracker configuration is used - * @param callback callback that gets executed when response arrives, null allowed + * @param requests the requests to send + * @param authToken specify if any of the parameters use require AuthToken, if null the default + * auth token from the request or the tracker configuration is used + * @param callback callback that gets executed when response arrives, null allowed * @return a completable future to let you know when the request is done - * @deprecated Please set the auth token in the tracker configuration or the requests directly and use - * {@link CompletableFuture#thenAccept(Consumer)} instead for the callback. + * @deprecated Please set the auth token in the tracker configuration or the requests directly and + * use {@link CompletableFuture#thenAccept(Consumer)} instead for the callback. */ @Deprecated public CompletableFuture sendBulkRequestAsync( @NonNull Collection requests, @Nullable String authToken, - @Nullable Consumer callback - ) { + @Nullable Consumer callback) { if (trackerConfiguration.isEnabled()) { for (MatomoRequest request : requests) { applyGoalIdAndCheckSiteId(request); @@ -335,34 +325,30 @@ public CompletableFuture sendBulkRequestAsync( } /** - * Send multiple requests in a single HTTP call. More efficient than sending - * several individual requests. + * Send multiple requests in a single HTTP call. More efficient than sending several individual + * requests. * * @param requests the requests to send * @param callback callback that gets executed when response arrives, null allowed * @return completable future to let you know when the request is done */ public CompletableFuture sendBulkRequestAsync( - @NonNull Collection requests, - @Nullable Consumer callback - ) { + @NonNull Collection requests, @Nullable Consumer callback) { return sendBulkRequestAsync(requests, null, callback); } /** - * Send multiple requests in a single HTTP call. More efficient than sending - * several individual requests. Specify the AuthToken if parameters that require - * an auth token is used. + * Send multiple requests in a single HTTP call. More efficient than sending several individual + * requests. Specify the AuthToken if parameters that require an auth token is used. * - * @param requests the requests to send + * @param requests the requests to send * @param authToken specify if any of the parameters use require AuthToken, null allowed * @return completable future to let you know when the request is done - * @deprecated Please set the auth token in the tracker configuration or the requests directly and use - * {@link #sendBulkRequestAsync(Collection)} instead. + * @deprecated Please set the auth token in the tracker configuration or the requests directly and + * use {@link #sendBulkRequestAsync(Collection)} instead. */ public CompletableFuture sendBulkRequestAsync( - @NonNull Collection requests, @Nullable String authToken - ) { + @NonNull Collection requests, @Nullable String authToken) { return sendBulkRequestAsync(requests, authToken, null); } @@ -372,5 +358,4 @@ public void close() throws Exception { sender.close(); } } - } diff --git a/core/src/main/java/org/matomo/java/tracking/ProxyAuthenticator.java b/core/src/main/java/org/matomo/java/tracking/ProxyAuthenticator.java index ec314cde..c237bcb9 100644 --- a/core/src/main/java/org/matomo/java/tracking/ProxyAuthenticator.java +++ b/core/src/main/java/org/matomo/java/tracking/ProxyAuthenticator.java @@ -16,11 +16,9 @@ @RequiredArgsConstructor class ProxyAuthenticator extends Authenticator { - @NonNull - private final String user; + @NonNull private final String user; - @NonNull - private final String password; + @NonNull private final String password; @Nullable @Override @@ -30,5 +28,4 @@ protected PasswordAuthentication getPasswordAuthentication() { } return null; } - } diff --git a/core/src/main/java/org/matomo/java/tracking/QueryCreator.java b/core/src/main/java/org/matomo/java/tracking/QueryCreator.java index 63a2b9d2..04a3967e 100644 --- a/core/src/main/java/org/matomo/java/tracking/QueryCreator.java +++ b/core/src/main/java/org/matomo/java/tracking/QueryCreator.java @@ -47,23 +47,24 @@ private static TrackingParameterMethod[] initializeTrackingParameterMethods() { private static void addMethods( Collection methods, Member member, - TrackingParameter trackingParameter - ) { + TrackingParameter trackingParameter) { try { - for (PropertyDescriptor pd : Introspector.getBeanInfo(MatomoRequest.class) - .getPropertyDescriptors()) { + for (PropertyDescriptor pd : + Introspector.getBeanInfo(MatomoRequest.class).getPropertyDescriptors()) { if (member.getName().equals(pd.getName())) { String regex = trackingParameter.regex(); - methods.add(TrackingParameterMethod - .builder() - .parameterName(trackingParameter.name()) - .min(trackingParameter.min()) - .max(trackingParameter.max()) - .maxLength(trackingParameter.maxLength()) - .method(pd.getReadMethod()) - .pattern(regex == null || regex.isEmpty() || regex.trim().isEmpty() ? null : - Pattern.compile(trackingParameter.regex())) - .build()); + methods.add( + TrackingParameterMethod.builder() + .parameterName(trackingParameter.name()) + .min(trackingParameter.min()) + .max(trackingParameter.max()) + .maxLength(trackingParameter.maxLength()) + .method(pd.getReadMethod()) + .pattern( + regex == null || regex.isEmpty() || regex.trim().isEmpty() + ? null + : Pattern.compile(trackingParameter.regex())) + .build()); } } } catch (IntrospectionException e) { @@ -71,9 +72,7 @@ private static void addMethods( } } - String createQuery( - @NonNull MatomoRequest request, @Nullable String authToken - ) { + String createQuery(@NonNull MatomoRequest request, @Nullable String authToken) { StringBuilder query = new StringBuilder(100); if (request.getSiteId() == null) { appendAmpersand(query); @@ -102,10 +101,11 @@ String createQuery( for (Entry entry : request.getDimensions().entrySet()) { if (entry.getKey() != null && entry.getValue() != null) { appendAmpersand(query); - query.append("dimension") - .append(entry.getKey()) - .append('=') - .append(encode(entry.getValue().toString())); + query + .append("dimension") + .append(entry.getKey()) + .append('=') + .append(encode(entry.getValue().toString())); } } } @@ -119,8 +119,7 @@ private static void appendAmpersand(StringBuilder query) { } private static void appendParameter( - TrackingParameterMethod method, MatomoRequest request, StringBuilder query - ) { + TrackingParameterMethod method, MatomoRequest request, StringBuilder query) { try { Object parameterValue = method.getMethod().invoke(request); if (parameterValue != null) { @@ -146,15 +145,11 @@ private static void appendParameter( } @NonNull - private static String encode( - @NonNull String parameterValue - ) { + private static String encode(@NonNull String parameterValue) { try { return URLEncoder.encode(parameterValue, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new MatomoException("Could not encode parameter", e); } } - - } diff --git a/core/src/main/java/org/matomo/java/tracking/RequestValidator.java b/core/src/main/java/org/matomo/java/tracking/RequestValidator.java index f604e1c5..5df2cae8 100644 --- a/core/src/main/java/org/matomo/java/tracking/RequestValidator.java +++ b/core/src/main/java/org/matomo/java/tracking/RequestValidator.java @@ -7,7 +7,6 @@ package org.matomo.java.tracking; - import edu.umd.cs.findbugs.annotations.Nullable; import java.time.Instant; import java.time.temporal.ChronoUnit; @@ -19,26 +18,24 @@ private RequestValidator() { // utility } - static void validate( - @NonNull - MatomoRequest request, - @Nullable - CharSequence authToken - ) { + static void validate(@NonNull MatomoRequest request, @Nullable CharSequence authToken) { if (request.getSearchResultsCount() != null && request.getSearchQuery() == null) { throw new MatomoException("Search query must be set if search results count is set"); } if (authToken == null) { - if (request.getVisitorLongitude() != null || request.getVisitorLatitude() != null - || request.getVisitorRegion() != null || request.getVisitorCity() != null - || request.getVisitorCountry() != null || request.getVisitorIp() != null) { + if (request.getVisitorLongitude() != null + || request.getVisitorLatitude() != null + || request.getVisitorRegion() != null + || request.getVisitorCity() != null + || request.getVisitorCountry() != null + || request.getVisitorIp() != null) { throw new MatomoException( - "Auth token must be present if visitor longitude, latitude, region, city, country or IP are set"); + "Auth token must be present if visitor longitude, latitude, region, city, country or IP" + + " are set"); } - if (request.getRequestTimestamp() != null && request - .getRequestTimestamp() - .isBefore(Instant.now().minus(4, ChronoUnit.HOURS))) { + if (request.getRequestTimestamp() != null + && request.getRequestTimestamp().isBefore(Instant.now().minus(4, ChronoUnit.HOURS))) { throw new MatomoException( "Auth token must be present if request timestamp is more than four hours ago"); } @@ -49,4 +46,3 @@ static void validate( } } } - diff --git a/core/src/main/java/org/matomo/java/tracking/Sender.java b/core/src/main/java/org/matomo/java/tracking/Sender.java index 7b1df985..24d40564 100644 --- a/core/src/main/java/org/matomo/java/tracking/Sender.java +++ b/core/src/main/java/org/matomo/java/tracking/Sender.java @@ -7,20 +7,14 @@ interface Sender extends AutoCloseable { @NonNull - CompletableFuture sendSingleAsync( - @NonNull MatomoRequest request - ); + CompletableFuture sendSingleAsync(@NonNull MatomoRequest request); - void sendSingle( - @NonNull MatomoRequest request - ); + void sendSingle(@NonNull MatomoRequest request); void sendBulk( - @NonNull Iterable requests, @Nullable String overrideAuthToken - ); + @NonNull Iterable requests, @Nullable String overrideAuthToken); @NonNull CompletableFuture sendBulkAsync( - @NonNull Collection requests, @Nullable String overrideAuthToken - ); + @NonNull Collection requests, @Nullable String overrideAuthToken); } diff --git a/core/src/main/java/org/matomo/java/tracking/SenderFactory.java b/core/src/main/java/org/matomo/java/tracking/SenderFactory.java index c4bfa561..11c36f42 100644 --- a/core/src/main/java/org/matomo/java/tracking/SenderFactory.java +++ b/core/src/main/java/org/matomo/java/tracking/SenderFactory.java @@ -1,10 +1,7 @@ package org.matomo.java.tracking; -/** - * A factory for {@link Sender} instances. - */ +/** A factory for {@link Sender} instances. */ public interface SenderFactory { Sender createSender(TrackerConfiguration trackerConfiguration, QueryCreator queryCreator); - } diff --git a/core/src/main/java/org/matomo/java/tracking/SenderProvider.java b/core/src/main/java/org/matomo/java/tracking/SenderProvider.java index 12b80291..14f57e92 100644 --- a/core/src/main/java/org/matomo/java/tracking/SenderProvider.java +++ b/core/src/main/java/org/matomo/java/tracking/SenderProvider.java @@ -3,5 +3,4 @@ interface SenderProvider { Sender provideSender(TrackerConfiguration trackerConfiguration, QueryCreator queryCreator); - } diff --git a/core/src/main/java/org/matomo/java/tracking/ServiceLoaderSenderFactory.java b/core/src/main/java/org/matomo/java/tracking/ServiceLoaderSenderFactory.java index 7cafe302..958bcb6d 100644 --- a/core/src/main/java/org/matomo/java/tracking/ServiceLoaderSenderFactory.java +++ b/core/src/main/java/org/matomo/java/tracking/ServiceLoaderSenderFactory.java @@ -12,17 +12,19 @@ class ServiceLoaderSenderFactory implements SenderFactory { @Override public Sender createSender(TrackerConfiguration trackerConfiguration, QueryCreator queryCreator) { ServiceLoader serviceLoader = ServiceLoader.load(SenderProvider.class); - Map senderProviders = StreamSupport - .stream(serviceLoader.spliterator(), false) - .collect(toMap(senderProvider -> senderProvider.getClass().getName(), Function.identity())); - SenderProvider senderProvider = senderProviders.get("org.matomo.java.tracking.Java11SenderProvider"); + Map senderProviders = + StreamSupport.stream(serviceLoader.spliterator(), false) + .collect( + toMap(senderProvider -> senderProvider.getClass().getName(), Function.identity())); + SenderProvider senderProvider = + senderProviders.get("org.matomo.java.tracking.Java11SenderProvider"); if (senderProvider == null) { senderProvider = senderProviders.get("org.matomo.java.tracking.Java8SenderProvider"); } if (senderProvider == null) { throw new MatomoException("No SenderProvider found"); } - return senderProvider.provideSender(trackerConfiguration, new QueryCreator(trackerConfiguration)); + return senderProvider.provideSender( + trackerConfiguration, new QueryCreator(trackerConfiguration)); } - } diff --git a/core/src/main/java/org/matomo/java/tracking/TrackerConfiguration.java b/core/src/main/java/org/matomo/java/tracking/TrackerConfiguration.java index 424ce82d..39aa8df2 100644 --- a/core/src/main/java/org/matomo/java/tracking/TrackerConfiguration.java +++ b/core/src/main/java/org/matomo/java/tracking/TrackerConfiguration.java @@ -14,9 +14,7 @@ import lombok.Builder; import lombok.Value; -/** - * Defines configuration settings for the Matomo tracking. - */ +/** Defines configuration settings for the Matomo tracking. */ @Builder @Value public class TrackerConfiguration { @@ -24,78 +22,63 @@ public class TrackerConfiguration { private static final Pattern AUTH_TOKEN_PATTERN = Pattern.compile("[a-z0-9]+"); /** - * The Matomo Tracking HTTP API endpoint, for example https://your-matomo-domain.example/matomo.php + * The Matomo Tracking HTTP API endpoint. Example: https://your-matomo-domain.example/matomo.php */ URI apiEndpoint; - /** - * The default ID of the website that will be used if not specified explicitly. - */ + /** The default ID of the website that will be used if not specified explicitly. */ Integer defaultSiteId; - /** - * The authorization token (parameter token_auth) to use if not specified explicitly. - */ + /** The authorization token (parameter token_auth) to use if not specified explicitly. */ String defaultAuthToken; - /** - * Allows to stop the tracker to send requests to the Matomo endpoint. - */ - @Builder.Default - boolean enabled = true; + /** Allows to stop the tracker to send requests to the Matomo endpoint. */ + @Builder.Default boolean enabled = true; /** * The timeout until a connection is established. * - *

A timeout value of zero is interpreted as an infinite timeout. - * A `null` value is interpreted as undefined (system default if applicable).

+ *

A timeout value of zero is interpreted as an infinite timeout. A `null` value is interpreted + * as undefined (system default if applicable). * - *

Default: 5 seconds

+ *

Default: 5 seconds */ - @Builder.Default - Duration connectTimeout = Duration.ofSeconds(5L); + @Builder.Default Duration connectTimeout = Duration.ofSeconds(5L); /** - * The socket timeout ({@code SO_TIMEOUT}), which is the timeout for waiting for data or, put differently, a maximum - * period inactivity between two consecutive data packets. + * The socket timeout ({@code SO_TIMEOUT}), which is the timeout for waiting for data or, put + * differently, a maximum period inactivity between two consecutive data packets. * - *

A timeout value of zero is interpreted as an infinite timeout. - * A `null value is interpreted as undefined (system default if applicable).

+ *

A timeout value of zero is interpreted as an infinite timeout. A `null value is interpreted + * as undefined (system default if applicable). * - *

Default: 5 seconds

+ *

Default: 5 seconds */ - @Builder.Default - Duration socketTimeout = Duration.ofSeconds(5L); + @Builder.Default Duration socketTimeout = Duration.ofSeconds(5L); /** - * The hostname or IP address of an optional HTTP proxy. {@code proxyPort} must be configured as well + * The hostname or IP address of an optional HTTP proxy. {@code proxyPort} must be configured as + * well */ - @Nullable - String proxyHost; + @Nullable String proxyHost; - /** - * The port of an HTTP proxy. {@code proxyHost} must be configured as well. - */ + /** The port of an HTTP proxy. {@code proxyHost} must be configured as well. */ int proxyPort; /** - * If the HTTP proxy requires a username for basic authentication, it can be configured here. Proxy host, port and - * password must also be set. + * If the HTTP proxy requires a username for basic authentication, it can be configured here. + * Proxy host, port and password must also be set. */ - @Nullable - String proxyUsername; + @Nullable String proxyUsername; /** - * The corresponding password for the basic auth proxy user. The proxy host, port and username must be set as well. + * The corresponding password for the basic auth proxy user. The proxy host, port and username + * must be set as well. */ - @Nullable - String proxyPassword; + @Nullable String proxyPassword; - /** - * A custom user agent to be set. Defaults to "MatomoJavaClient" - */ - @Builder.Default - String userAgent = "MatomoJavaClient"; + /** A custom user agent to be set. Defaults to "MatomoJavaClient" */ + @Builder.Default String userAgent = "MatomoJavaClient"; /** * Logs if the Matomo Tracking API endpoint responds with an erroneous HTTP code. Defaults to @@ -108,7 +91,7 @@ public class TrackerConfiguration { * Do not use in production environments. Defaults to false. * *

Attention: This slows down performance - + * * @see #disableSslHostVerification */ boolean disableSslCertValidation; @@ -119,8 +102,8 @@ public class TrackerConfiguration { * *

If you use the Java 11 of the Matomo Java Tracker, this setting is ignored. Instead, you * have to set the system property {@code jdk.internal.httpclient.disableHostnameVerification} as - * described in the - * Module + * described in the Module * java.net.http. * * @see #disableSslCertValidation @@ -131,15 +114,11 @@ public class TrackerConfiguration { * The thread pool size for the async sender. Defaults to 2. * *

Attention: If you use this library in a web application, make sure that this thread pool - * does not exceed the thread pool of the web application. Otherwise, you might run into - * problems. + * does not exceed the thread pool of the web application. Otherwise, you might run into problems. */ - @Builder.Default - int threadPoolSize = 2; + @Builder.Default int threadPoolSize = 2; - /** - * Validates the auth token. The auth token must be exactly 32 characters long. - */ + /** Validates the auth token. The auth token must be exactly 32 characters long. */ public void validate() { if (apiEndpoint == null) { throw new IllegalArgumentException("API endpoint must not be null"); diff --git a/core/src/main/java/org/matomo/java/tracking/TrackingParameter.java b/core/src/main/java/org/matomo/java/tracking/TrackingParameter.java index 0b9d82bc..1e11181f 100644 --- a/core/src/main/java/org/matomo/java/tracking/TrackingParameter.java +++ b/core/src/main/java/org/matomo/java/tracking/TrackingParameter.java @@ -25,5 +25,4 @@ double max() default Double.MAX_VALUE; int maxLength() default Integer.MAX_VALUE; - } diff --git a/core/src/main/java/org/matomo/java/tracking/TrackingParameterMethod.java b/core/src/main/java/org/matomo/java/tracking/TrackingParameterMethod.java index 2540ea0c..82556dba 100644 --- a/core/src/main/java/org/matomo/java/tracking/TrackingParameterMethod.java +++ b/core/src/main/java/org/matomo/java/tracking/TrackingParameterMethod.java @@ -30,38 +30,32 @@ class TrackingParameterMethod { int maxLength; void validateParameterValue(@NonNull Object parameterValue) { - if (pattern != null && parameterValue instanceof CharSequence && !pattern - .matcher((CharSequence) parameterValue) - .matches()) { - throw new MatomoException(String.format("Invalid value for %s. Must match regex %s", - parameterName, - pattern - )); + if (pattern != null + && parameterValue instanceof CharSequence + && !pattern.matcher((CharSequence) parameterValue).matches()) { + throw new MatomoException( + String.format("Invalid value for %s. Must match regex %s", parameterName, pattern)); } if (maxLength != 0 && parameterValue.toString().length() > maxLength) { - throw new MatomoException(String.format("Invalid value for %s. Must be less or equal than %d characters", - parameterName, - maxLength - )); + throw new MatomoException( + String.format( + "Invalid value for %s. Must be less or equal than %d characters", + parameterName, maxLength)); } if (parameterValue instanceof Number) { Number number = (Number) parameterValue; if (number.doubleValue() < min) { - throw new MatomoException(String.format( - "Invalid value for %s. Must be greater or equal than %s", - parameterName, - min % 1 == 0 ? Long.toString((long) min) : min - )); - + throw new MatomoException( + String.format( + "Invalid value for %s. Must be greater or equal than %s", + parameterName, min % 1 == 0 ? Long.toString((long) min) : min)); } if (number.doubleValue() > max) { - throw new MatomoException(String.format( - "Invalid value for %s. Must be less or equal than %s", - parameterName, - max % 1 == 0 ? Long.toString((long) max) : max - )); + throw new MatomoException( + String.format( + "Invalid value for %s. Must be less or equal than %s", + parameterName, max % 1 == 0 ? Long.toString((long) max) : max)); } } } - } diff --git a/core/src/main/java/org/matomo/java/tracking/TrustingX509TrustManager.java b/core/src/main/java/org/matomo/java/tracking/TrustingX509TrustManager.java index 790db746..3e742f9f 100644 --- a/core/src/main/java/org/matomo/java/tracking/TrustingX509TrustManager.java +++ b/core/src/main/java/org/matomo/java/tracking/TrustingX509TrustManager.java @@ -13,16 +13,12 @@ public X509Certificate[] getAcceptedIssuers() { } @Override - public void checkClientTrusted( - @Nullable X509Certificate[] chain, @Nullable String authType - ) { + public void checkClientTrusted(@Nullable X509Certificate[] chain, @Nullable String authType) { // no operation } @Override - public void checkServerTrusted( - @Nullable X509Certificate[] chain, @Nullable String authType - ) { + public void checkServerTrusted(@Nullable X509Certificate[] chain, @Nullable String authType) { // no operation } } diff --git a/core/src/main/java/org/matomo/java/tracking/package-info.java b/core/src/main/java/org/matomo/java/tracking/package-info.java index 5c08c6dc..3a56acd9 100644 --- a/core/src/main/java/org/matomo/java/tracking/package-info.java +++ b/core/src/main/java/org/matomo/java/tracking/package-info.java @@ -1,13 +1,12 @@ /** - * This package contains classes that allow you to specify a {@link org.matomo.java.tracking.MatomoTracker} - * with the corresponding {@link org.matomo.java.tracking.TrackerConfiguration}. You can then send a - * {@link org.matomo.java.tracking.MatomoRequest} as a single HTTP GET request or multiple requests as a bulk HTTP POST - * request synchronously or asynchronously. If an exception occurs, {@link org.matomo.java.tracking.MatomoException} - * will be thrown. + * This package contains classes that allow you to specify a {@link + * org.matomo.java.tracking.MatomoTracker} with the corresponding {@link + * org.matomo.java.tracking.TrackerConfiguration}. You can then send a {@link + * org.matomo.java.tracking.MatomoRequest} as a single HTTP GET request or multiple requests as a + * bulk HTTP POST request synchronously or asynchronously. If an exception occurs, {@link + * org.matomo.java.tracking.MatomoException} will be thrown. * - *

For more information about the Matomo Tracking HTTP API, see the Matomo Tracking HTTP API. + *

For more information about the Matomo Tracking HTTP API, see the Matomo Tracking HTTP API. */ - package org.matomo.java.tracking; - - diff --git a/core/src/main/java/org/matomo/java/tracking/parameters/AcceptLanguage.java b/core/src/main/java/org/matomo/java/tracking/parameters/AcceptLanguage.java index 0ecee82d..cb4ea46e 100644 --- a/core/src/main/java/org/matomo/java/tracking/parameters/AcceptLanguage.java +++ b/core/src/main/java/org/matomo/java/tracking/parameters/AcceptLanguage.java @@ -18,8 +18,9 @@ import lombok.Value; /** - * Describes the content for the Accept-Language header field that can be overridden by a custom parameter. The format - * is specified in the corresponding RFC 4647 Matching of Language Tags + * Describes the content for the Accept-Language header field that can be overridden by a custom + * parameter. The format is specified in the corresponding RFC 4647 Matching of Language Tags * *

Example: "en-US,en;q=0.8,de;q=0.6" */ @@ -27,23 +28,20 @@ @Value public class AcceptLanguage { - @Singular - List languageRanges; + @Singular List languageRanges; /** * Creates the Accept-Language definition for a given header. * - *

Please see {@link LanguageRange#parse(String)} for more information. Example: "en-US,en;q=0.8,de;q=0.6" + *

Please see {@link LanguageRange#parse(String)} for more information. Example: + * "en-US,en;q=0.8,de;q=0.6" * * @param header A header that can be null * @return The parsed header (probably reformatted). null if the header is null. * @see LanguageRange#parse(String) */ @Nullable - public static AcceptLanguage fromHeader( - @Nullable - String header - ) { + public static AcceptLanguage fromHeader(@Nullable String header) { if (header == null || header.trim().isEmpty()) { return null; } @@ -57,19 +55,15 @@ public static AcceptLanguage fromHeader( */ @NonNull public String toString() { - return languageRanges - .stream() + return languageRanges.stream() .filter(Objects::nonNull) .map(AcceptLanguage::format) .collect(Collectors.joining(",")); } - private static String format( - @NonNull - LanguageRange languageRange - ) { - return languageRange.getWeight() == LanguageRange.MAX_WEIGHT ? languageRange.getRange() : - String.format("%s;q=%s", languageRange.getRange(), languageRange.getWeight()); + private static String format(@NonNull LanguageRange languageRange) { + return languageRange.getWeight() == LanguageRange.MAX_WEIGHT + ? languageRange.getRange() + : String.format("%s;q=%s", languageRange.getRange(), languageRange.getWeight()); } - } diff --git a/core/src/main/java/org/matomo/java/tracking/parameters/Country.java b/core/src/main/java/org/matomo/java/tracking/parameters/Country.java index ab51e14f..aff24465 100644 --- a/core/src/main/java/org/matomo/java/tracking/parameters/Country.java +++ b/core/src/main/java/org/matomo/java/tracking/parameters/Country.java @@ -18,24 +18,22 @@ /** * A two-letter country code representing a country. * - *

See ISO 3166-1 alpha-2 for a list of valid codes. + *

See ISO 3166-1 alpha-2 for a + * list of valid codes. */ @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public class Country { - @NonNull - private String code; + @NonNull private String code; /** - * Only for internal use to grant downwards compatibility to {@link org.matomo.java.tracking.MatomoLocale}. + * Only for internal use to grant downwards compatibility to {@link + * org.matomo.java.tracking.MatomoLocale}. * * @param locale A locale that must contain a country code */ @Deprecated - protected Country( - @edu.umd.cs.findbugs.annotations.NonNull - Locale locale - ) { + protected Country(@edu.umd.cs.findbugs.annotations.NonNull Locale locale) { setLocale(locale); } @@ -46,10 +44,7 @@ protected Country( * @return The country or null if code was null */ @Nullable - public static Country fromCode( - @Nullable - String code - ) { + public static Country fromCode(@Nullable String code) { if (code == null || code.isEmpty() || code.trim().isEmpty()) { return null; } @@ -66,10 +61,7 @@ public static Country fromCode( * @return The country or null if ranges was null */ @Nullable - public static Country fromLanguageRanges( - @Nullable - String ranges - ) { + public static Country fromLanguageRanges(@Nullable String ranges) { if (ranges == null || ranges.isEmpty() || ranges.trim().isEmpty()) { return null; } @@ -89,8 +81,8 @@ public static Country fromLanguageRanges( * * @return The locale for this country * @see Locale#forLanguageTag(String) - * @deprecated Since you instantiate this class, you can determine the language on your own - * using {@link Locale#forLanguageTag(String)} + * @deprecated Since you instantiate this class, you can determine the language on your own using + * {@link Locale#forLanguageTag(String)} */ @Deprecated public Locale getLocale() { @@ -102,8 +94,8 @@ public Locale getLocale() { * * @param locale A locale that must contain a country code * @see Locale#getCountry() - * @deprecated Since you instantiate this class, you can determine the language on your own - * using {@link Locale#getCountry()} + * @deprecated Since you instantiate this class, you can determine the language on your own using + * {@link Locale#getCountry()} */ @Deprecated public final void setLocale(Locale locale) { @@ -117,5 +109,4 @@ public final void setLocale(Locale locale) { public String toString() { return code; } - } diff --git a/core/src/main/java/org/matomo/java/tracking/parameters/CustomVariable.java b/core/src/main/java/org/matomo/java/tracking/parameters/CustomVariable.java index 0f6a3fa9..45cbf58a 100644 --- a/core/src/main/java/org/matomo/java/tracking/parameters/CustomVariable.java +++ b/core/src/main/java/org/matomo/java/tracking/parameters/CustomVariable.java @@ -15,15 +15,18 @@ import lombok.ToString; /** - * A key-value pair that represents custom information. See - * How do I use Custom Variables? + * A key-value pair that represents custom information. See How do I use + * Custom Variables? * - *

If you are not already using Custom Variables to measure your custom data, Matomo recommends to use the - * Custom Dimensions feature instead. - * There are many advantages of Custom Dimensions over Custom - * variables. Custom variables will be deprecated in the future. + *

If you are not already using Custom Variables to measure your custom data, Matomo recommends + * to use the Custom Dimensions feature + * instead. There are many advantages of Custom + * Dimensions over Custom variables. Custom variables will be deprecated in the future. * - * @deprecated Should not be used according to the Matomo FAQ: How do I use Custom Variables? + * @deprecated Should not be used according to the Matomo FAQ: How do I use + * Custom Variables? */ @Getter @Setter @@ -35,16 +38,14 @@ public class CustomVariable { private int index; - @NonNull - private String key; + @NonNull private String key; - @NonNull - private String value; + @NonNull private String value; /** * Instantiates a new custom variable. * - * @param key the key of the custom variable (required) + * @param key the key of the custom variable (required) * @param value the value of the custom variable (required) */ public CustomVariable(@NonNull String key, @NonNull String value) { @@ -52,6 +53,3 @@ public CustomVariable(@NonNull String key, @NonNull String value) { this.value = value; } } - - - diff --git a/core/src/main/java/org/matomo/java/tracking/parameters/CustomVariables.java b/core/src/main/java/org/matomo/java/tracking/parameters/CustomVariables.java index 4fee72df..acd2e041 100644 --- a/core/src/main/java/org/matomo/java/tracking/parameters/CustomVariables.java +++ b/core/src/main/java/org/matomo/java/tracking/parameters/CustomVariables.java @@ -17,9 +17,13 @@ import lombok.NonNull; /** - * A bunch of key-value pairs that represent custom information. See How do I use Custom Variables? + * A bunch of key-value pairs that represent custom information. See How do I use + * Custom Variables? * - * @deprecated Should not be used according to the Matomo FAQ: How do I use Custom Variables? + * @deprecated Should not be used according to the Matomo FAQ: How do I use + * Custom Variables? */ @EqualsAndHashCode @Deprecated @@ -60,7 +64,7 @@ public CustomVariables add(@NonNull CustomVariable variable) { /** * Adds a custom variable to the list with the given index. * - * @param cv The custom variable to add + * @param cv The custom variable to add * @param index The index to add the custom variable at * @return This object for method chaining */ @@ -89,20 +93,20 @@ public CustomVariable get(int index) { } /** - * Returns the value of the custom variable with the given key. If there are multiple custom variables with the same - * key, the first one is returned. If there is no custom variable with the given key, null is returned. + * Returns the value of the custom variable with the given key. If there are multiple custom + * variables with the same key, the first one is returned. If there is no custom variable with the + * given key, null is returned. * * @param key The key of the custom variable. Must not be null. - * @return The value of the custom variable with the given key. null if there is no variable with the given key. + * @return The value of the custom variable with the given key. null if there is no variable with + * the given key. */ @Nullable public String get(@NonNull String key) { if (key.isEmpty()) { throw new IllegalArgumentException("key must not be null or empty"); } - return variables - .values() - .stream() + return variables.values().stream() .filter(variable -> variable.getKey().equals(key)) .findFirst() .map(CustomVariable::getValue) @@ -110,7 +114,8 @@ public String get(@NonNull String key) { } /** - * Removes the custom variable at the given index. If there is no custom variable at the given index, nothing happens. + * Removes the custom variable at the given index. If there is no custom variable at the given + * index, nothing happens. * * @param index The index of the custom variable to remove. Must be greater than 0. */ @@ -120,7 +125,8 @@ public void remove(int index) { } /** - * Removes the custom variable with the given key. If there is no custom variable with the given key, nothing happens. + * Removes the custom variable with the given key. If there is no custom variable with the given + * key, nothing happens. * * @param key The key of the custom variable to remove. Must not be null. */ @@ -132,7 +138,6 @@ boolean isEmpty() { return variables.isEmpty(); } - /** * Parses a JSON representation of custom variables. * @@ -179,8 +184,8 @@ public static CustomVariables parse(@Nullable String value) { } /** - * Creates a JSON representation of the custom variables. The format is as follows: - * {@code {"1":["key1","value1"],"2":["key2","value2"]}} + * Creates a JSON representation of the custom variables. The format is as follows: {@code + * {"1":["key1","value1"],"2":["key2","value2"]}} * * @return A JSON representation of the custom variables */ @@ -205,5 +210,4 @@ public String toString() { stringBuilder.append('}'); return stringBuilder.toString(); } - } diff --git a/core/src/main/java/org/matomo/java/tracking/parameters/DeviceResolution.java b/core/src/main/java/org/matomo/java/tracking/parameters/DeviceResolution.java index 6729443c..f466dd83 100644 --- a/core/src/main/java/org/matomo/java/tracking/parameters/DeviceResolution.java +++ b/core/src/main/java/org/matomo/java/tracking/parameters/DeviceResolution.java @@ -11,9 +11,7 @@ import lombok.Builder; import lombok.RequiredArgsConstructor; -/** - * The resolution (width and height) of the user's output device (monitor / phone). - */ +/** The resolution (width and height) of the user's output device (monitor / phone). */ @Builder @RequiredArgsConstructor public class DeviceResolution { @@ -31,10 +29,7 @@ public class DeviceResolution { * @return The device resolution representation */ @Nullable - public static DeviceResolution fromString( - @Nullable - String deviceResolution - ) { + public static DeviceResolution fromString(@Nullable String deviceResolution) { if (deviceResolution == null || deviceResolution.trim().isEmpty()) { return null; } @@ -55,5 +50,4 @@ public static DeviceResolution fromString( public String toString() { return String.format("%dx%d", width, height); } - } diff --git a/core/src/main/java/org/matomo/java/tracking/parameters/EcommerceItem.java b/core/src/main/java/org/matomo/java/tracking/parameters/EcommerceItem.java index 7f5ba051..124158f8 100644 --- a/core/src/main/java/org/matomo/java/tracking/parameters/EcommerceItem.java +++ b/core/src/main/java/org/matomo/java/tracking/parameters/EcommerceItem.java @@ -12,9 +12,7 @@ import lombok.Getter; import lombok.Setter; -/** - * Represents an item in an ecommerce order. - */ +/** Represents an item in an ecommerce order. */ @Builder @AllArgsConstructor @Getter @@ -23,17 +21,13 @@ public class EcommerceItem { private String sku; - @Builder.Default - private String name = ""; + @Builder.Default private String name = ""; - @Builder.Default - private String category = ""; + @Builder.Default private String category = ""; - @Builder.Default - private Double price = 0.0; + @Builder.Default private Double price = 0.0; - @Builder.Default - private Integer quantity = 0; + @Builder.Default private Integer quantity = 0; public String toString() { return String.format("[\"%s\",\"%s\",\"%s\",%s,%d]", sku, name, category, price, quantity); diff --git a/core/src/main/java/org/matomo/java/tracking/parameters/EcommerceItems.java b/core/src/main/java/org/matomo/java/tracking/parameters/EcommerceItems.java index 7000ded7..8cf47357 100644 --- a/core/src/main/java/org/matomo/java/tracking/parameters/EcommerceItems.java +++ b/core/src/main/java/org/matomo/java/tracking/parameters/EcommerceItems.java @@ -19,9 +19,7 @@ import lombok.Singular; import lombok.experimental.Delegate; -/** - * Multiple things that you can buy online. - */ +/** Multiple things that you can buy online. */ @Builder @AllArgsConstructor @NoArgsConstructor @@ -30,12 +28,9 @@ @Setter public class EcommerceItems { - @Delegate - @Singular - private List items = new ArrayList<>(); + @Delegate @Singular private List items = new ArrayList<>(); public String toString() { return items.stream().map(String::valueOf).collect(Collectors.joining(",", "[", "]")); } - } diff --git a/core/src/main/java/org/matomo/java/tracking/parameters/Hex.java b/core/src/main/java/org/matomo/java/tracking/parameters/Hex.java index 13ab4d98..f6b12c92 100644 --- a/core/src/main/java/org/matomo/java/tracking/parameters/Hex.java +++ b/core/src/main/java/org/matomo/java/tracking/parameters/Hex.java @@ -22,5 +22,4 @@ static String fromBytes(@NonNull byte[] bytes) { } return result.toString(); } - } diff --git a/core/src/main/java/org/matomo/java/tracking/parameters/RandomValue.java b/core/src/main/java/org/matomo/java/tracking/parameters/RandomValue.java index 2b000b6e..5a066bb5 100644 --- a/core/src/main/java/org/matomo/java/tracking/parameters/RandomValue.java +++ b/core/src/main/java/org/matomo/java/tracking/parameters/RandomValue.java @@ -10,9 +10,7 @@ import java.security.SecureRandom; import java.util.Random; -/** - * A random value to avoid the tracking request being cached by the browser or a proxy. - */ +/** A random value to avoid the tracking request being cached by the browser or a proxy. */ public class RandomValue { private static final Random RANDOM = new SecureRandom(); @@ -33,7 +31,8 @@ public static RandomValue random() { } /** - * Static factory to generate a random value from a given string. The string will be used as is and not hashed. + * Static factory to generate a random value from a given string. The string will be used as is + * and not hashed. * * @param override The string to use as random value * @return A random value from the given string @@ -51,5 +50,4 @@ public String toString() { } return Hex.fromBytes(representation); } - } diff --git a/core/src/main/java/org/matomo/java/tracking/parameters/UniqueId.java b/core/src/main/java/org/matomo/java/tracking/parameters/UniqueId.java index 06a82be6..0f0f95e8 100644 --- a/core/src/main/java/org/matomo/java/tracking/parameters/UniqueId.java +++ b/core/src/main/java/org/matomo/java/tracking/parameters/UniqueId.java @@ -14,9 +14,7 @@ import lombok.AccessLevel; import lombok.RequiredArgsConstructor; -/** - * A six character unique ID consisting of the characters [0-9a-Z]. - */ +/** A six character unique ID consisting of the characters [0-9a-Z]. */ @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public final class UniqueId { @@ -48,11 +46,9 @@ public static UniqueId fromValue(long value) { @Override public String toString() { - return IntStream - .range(0, 6) + return IntStream.range(0, 6) .map(i -> (int) (value >> i * 8)) .mapToObj(codePoint -> String.valueOf(CHARS.charAt(Math.abs(codePoint % CHARS.length())))) .collect(Collectors.joining()); } - } diff --git a/core/src/main/java/org/matomo/java/tracking/parameters/VisitorId.java b/core/src/main/java/org/matomo/java/tracking/parameters/VisitorId.java index 39b54e30..70ab8087 100644 --- a/core/src/main/java/org/matomo/java/tracking/parameters/VisitorId.java +++ b/core/src/main/java/org/matomo/java/tracking/parameters/VisitorId.java @@ -15,9 +15,9 @@ import lombok.NonNull; /** - * The unique visitor ID, must be a 16 characters hexadecimal string. Every unique visitor must be assigned a different - * ID and this ID must not change after it is assigned. If this value is not set Matomo will still track visits, but the - * unique visitors metric might be less accurate. + * The unique visitor ID, must be a 16 characters hexadecimal string. Every unique visitor must be + * assigned a different ID and this ID must not change after it is assigned. If this value is not + * set Matomo will still track visits, but the unique visitors metric might be less accurate. */ public class VisitorId { @@ -29,8 +29,9 @@ public class VisitorId { /** * Static factory to generate a random visitor id. * - *

Please consider creating a fixed id for each visitor by getting a hash code from e.g. the username and - * using {@link #fromHash(long)} or {@link #fromString(String)} instead of using this method. + *

Please consider creating a fixed id for each visitor by getting a hash code from e.g. the + * username and using {@link #fromHash(long)} or {@link #fromString(String)} instead of using this + * method. * * @return A randomly generated visitor id */ @@ -44,8 +45,8 @@ public static VisitorId random() { /** * Creates always the same visitor id for the given input. * - *

You can use e.g. {@link Object#hashCode()} to generate a hash code for an object, e.g. a username - * string as input. + *

You can use e.g. {@link Object#hashCode()} to generate a hash code for an object, e.g. a + * username string as input. * * @param hash A number (a hash code) to create the visitor id from * @return Always the same visitor id for the same input @@ -77,8 +78,8 @@ public static VisitorId fromUUID(@NonNull UUID uuid) { /** * Creates a visitor id from a hexadecimal string. * - *

The input must be a valid hexadecimal string with a maximum length of 16 characters. If the input is shorter - * than 16 characters it will be padded with zeros.

+ *

The input must be a valid hexadecimal string with a maximum length of 16 characters. If the + * input is shorter than 16 characters it will be padded with zeros. * * @param inputHex A hexadecimal string to create the visitor id from * @return The visitor id for the given input @@ -95,10 +96,10 @@ public static VisitorId fromHex(@NonNull String inputHex) { throw new IllegalArgumentException("Input must be a valid hex string"); } VisitorId visitorId = new VisitorId(); - for (int charIndex = inputHex.length() - 1, representationIndex = - visitorId.representation.length - 1; - charIndex >= 0; - charIndex -= 2, representationIndex--) { + for (int charIndex = inputHex.length() - 1, + representationIndex = visitorId.representation.length - 1; + charIndex >= 0; + charIndex -= 2, representationIndex--) { String hex = inputHex.substring(Math.max(0, charIndex - 1), charIndex + 1); try { visitorId.representation[representationIndex] = (byte) Integer.parseInt(hex, 16); @@ -128,5 +129,4 @@ public static VisitorId fromString(@Nullable String str) { public String toString() { return Hex.fromBytes(representation); } - } diff --git a/core/src/main/java/org/matomo/java/tracking/parameters/package-info.java b/core/src/main/java/org/matomo/java/tracking/parameters/package-info.java index f709edce..89f96f81 100644 --- a/core/src/main/java/org/matomo/java/tracking/parameters/package-info.java +++ b/core/src/main/java/org/matomo/java/tracking/parameters/package-info.java @@ -1,9 +1,9 @@ /** - * Contains types for Matomo Tracking Parameters according to - * the Matomo Tracking HTTP API. + * Contains types for Matomo Tracking Parameters according to the Matomo Tracking HTTP API. * - *

The types help you to use the correct format for the tracking parameters. The package was introduced in Matomo - * Java Tracker version 3 to let the tracker be more self-explanatory and better maintainable. + *

The types help you to use the correct format for the tracking parameters. The package was + * introduced in Matomo Java Tracker version 3 to let the tracker be more self-explanatory and + * better maintainable. */ - package org.matomo.java.tracking.parameters; diff --git a/core/src/main/java/org/matomo/java/tracking/servlet/CookieWrapper.java b/core/src/main/java/org/matomo/java/tracking/servlet/CookieWrapper.java index 4c29ae3d..a4debe13 100644 --- a/core/src/main/java/org/matomo/java/tracking/servlet/CookieWrapper.java +++ b/core/src/main/java/org/matomo/java/tracking/servlet/CookieWrapper.java @@ -2,14 +2,11 @@ import lombok.Value; -/** - * Wrapper for the cookie name and value. - */ +/** Wrapper for the cookie name and value. */ @Value public class CookieWrapper { String name; String value; - } diff --git a/core/src/main/java/org/matomo/java/tracking/servlet/HttpServletRequestWrapper.java b/core/src/main/java/org/matomo/java/tracking/servlet/HttpServletRequestWrapper.java index b72c087b..15a7dc2f 100644 --- a/core/src/main/java/org/matomo/java/tracking/servlet/HttpServletRequestWrapper.java +++ b/core/src/main/java/org/matomo/java/tracking/servlet/HttpServletRequestWrapper.java @@ -9,27 +9,20 @@ import lombok.NonNull; import lombok.Value; -/** - * Wraps a HttpServletRequest to be compatible with both the Jakarta and the Java EE API. - */ +/** Wraps a HttpServletRequest to be compatible with both the Jakarta and the Java EE API. */ @Builder @Value public class HttpServletRequestWrapper { - @Nullable - StringBuffer requestURL; + @Nullable StringBuffer requestURL; - @Nullable - String remoteAddr; + @Nullable String remoteAddr; - @Nullable - String remoteUser; + @Nullable String remoteUser; - @Nullable - Map headers; + @Nullable Map headers; - @Nullable - CookieWrapper[] cookies; + @Nullable CookieWrapper[] cookies; /** * Returns an enumeration of all the header names this request contains. If the request has no @@ -38,8 +31,9 @@ public class HttpServletRequestWrapper { * @return an enumeration of all the header names sent with this request */ public Enumeration getHeaderNames() { - return headers == null ? Collections.emptyEnumeration() : - Collections.enumeration(headers.keySet()); + return headers == null + ? Collections.emptyEnumeration() + : Collections.enumeration(headers.keySet()); } /** @@ -50,11 +44,10 @@ public Enumeration getHeaderNames() { * * @param name a String specifying the header name (case insensitive) - must not be {@code null}. * @return a String containing the value of the requested header, or null if the request does not - * have a header of that name + * have a header of that name */ @Nullable public String getHeader(@NonNull String name) { return headers == null ? null : headers.get(name.toLowerCase(Locale.ROOT)); } - } diff --git a/core/src/main/java/org/matomo/java/tracking/servlet/ServletMatomoRequest.java b/core/src/main/java/org/matomo/java/tracking/servlet/ServletMatomoRequest.java index ef81608f..7ec30f8b 100644 --- a/core/src/main/java/org/matomo/java/tracking/servlet/ServletMatomoRequest.java +++ b/core/src/main/java/org/matomo/java/tracking/servlet/ServletMatomoRequest.java @@ -16,28 +16,20 @@ import org.matomo.java.tracking.parameters.CustomVariables; import org.matomo.java.tracking.parameters.VisitorId; - /** - * Adds the headers from a {@link HttpServletRequestWrapper} to a - * {@link MatomoRequest.MatomoRequestBuilder}. + * Adds the headers from a {@link HttpServletRequestWrapper} to a {@link + * MatomoRequest.MatomoRequestBuilder}. * - *

Use #fromServletRequest(HttpServletRequestWrapper) to create a new builder with the headers from the - * request or #addServletRequestHeaders(MatomoRequest.MatomoRequestBuilder, HttpServletRequestWrapper) to - * add the headers to an existing builder. + *

Use #fromServletRequest(HttpServletRequestWrapper) to create a new builder with the headers + * from the request or #addServletRequestHeaders(MatomoRequest.MatomoRequestBuilder, + * HttpServletRequestWrapper) to add the headers to an existing builder. */ public final class ServletMatomoRequest { - /** - * Please ensure these values are always lower case. - */ + /** Please ensure these values are always lower case. */ private static final Set RESTRICTED_HEADERS = - Collections.unmodifiableSet(new HashSet<>(asList( - "connection", - "content-length", - "expect", - "host", - "upgrade" - ))); + Collections.unmodifiableSet( + new HashSet<>(asList("connection", "content-length", "expect", "host", "upgrade"))); private ServletMatomoRequest() { // should not be instantiated @@ -46,33 +38,32 @@ private ServletMatomoRequest() { /** * Creates a new builder with the headers from the request. * - *

Use #addServletRequestHeaders(MatomoRequest.MatomoRequestBuilder, HttpServletRequestWrapper) to - * add the headers to an existing builder. + *

Use #addServletRequestHeaders(MatomoRequest.MatomoRequestBuilder, HttpServletRequestWrapper) + * to add the headers to an existing builder. * * @param request the request to get the headers from (must not be null) - * * @return a new builder with the headers from the request (never null) */ @edu.umd.cs.findbugs.annotations.NonNull - public static MatomoRequest.MatomoRequestBuilder fromServletRequest(@NonNull HttpServletRequestWrapper request) { + public static MatomoRequest.MatomoRequestBuilder fromServletRequest( + @NonNull HttpServletRequestWrapper request) { return addServletRequestHeaders(MatomoRequest.request(), request); } /** * Adds the headers from the request to an existing builder. * - *

Use #fromServletRequest(HttpServletRequestWrapper) to create a new builder with the headers from - * the request. + *

Use #fromServletRequest(HttpServletRequestWrapper) to create a new builder with the headers + * from the request. * * @param builder the builder to add the headers to (must not be null) * @param request the request to get the headers from (must not be null) - * * @return the builder with the headers added (never null) */ @edu.umd.cs.findbugs.annotations.NonNull public static MatomoRequest.MatomoRequestBuilder addServletRequestHeaders( - @NonNull MatomoRequest.MatomoRequestBuilder builder, @NonNull HttpServletRequestWrapper request - ) { + @NonNull MatomoRequest.MatomoRequestBuilder builder, + @NonNull HttpServletRequestWrapper request) { return builder .actionUrl(request.getRequestURL() == null ? null : request.getRequestURL().toString()) .headers(collectHeaders(request)) @@ -83,15 +74,14 @@ public static MatomoRequest.MatomoRequestBuilder addServletRequestHeaders( @edu.umd.cs.findbugs.annotations.NonNull private static Map collectHeaders( - @edu.umd.cs.findbugs.annotations.NonNull HttpServletRequestWrapper request - ) { + @edu.umd.cs.findbugs.annotations.NonNull HttpServletRequestWrapper request) { Map headers = new HashMap<>(10); Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); - if (headerName != null && !headerName.trim().isEmpty() && !RESTRICTED_HEADERS.contains( - headerName.toLowerCase( - Locale.ROOT))) { + if (headerName != null + && !headerName.trim().isEmpty() + && !RESTRICTED_HEADERS.contains(headerName.toLowerCase(Locale.ROOT))) { headers.put(headerName, request.getHeader(headerName)); } } @@ -100,8 +90,7 @@ private static Map collectHeaders( @Nullable private static String determineVisitorIp( - @edu.umd.cs.findbugs.annotations.NonNull HttpServletRequestWrapper request - ) { + @edu.umd.cs.findbugs.annotations.NonNull HttpServletRequestWrapper request) { String forwardedForHeader = request.getHeader("X-Forwarded-For"); if (isNotEmpty(forwardedForHeader)) { return forwardedForHeader; @@ -115,8 +104,7 @@ private static String determineVisitorIp( @edu.umd.cs.findbugs.annotations.NonNull private static Map processCookies( @edu.umd.cs.findbugs.annotations.NonNull MatomoRequest.MatomoRequestBuilder builder, - @edu.umd.cs.findbugs.annotations.NonNull HttpServletRequestWrapper request - ) { + @edu.umd.cs.findbugs.annotations.NonNull HttpServletRequestWrapper request) { Map cookies = new LinkedHashMap<>(3); if (request.getCookies() != null) { builder.supportsCookies(Boolean.TRUE); @@ -137,8 +125,7 @@ private static void processCookie( @edu.umd.cs.findbugs.annotations.NonNull MatomoRequest.MatomoRequestBuilder builder, @edu.umd.cs.findbugs.annotations.NonNull Map cookies, @edu.umd.cs.findbugs.annotations.NonNull String cookieName, - @edu.umd.cs.findbugs.annotations.NonNull String cookieValue - ) { + @edu.umd.cs.findbugs.annotations.NonNull String cookieValue) { if (cookieName.toLowerCase(Locale.ROOT).startsWith("_pk_id")) { extractVisitorId(builder, cookies, cookieValue, cookieName); } @@ -159,12 +146,11 @@ private static void extractVisitorId( @edu.umd.cs.findbugs.annotations.NonNull MatomoRequest.MatomoRequestBuilder builder, @edu.umd.cs.findbugs.annotations.NonNull Map cookies, @edu.umd.cs.findbugs.annotations.NonNull String cookieValue, - @edu.umd.cs.findbugs.annotations.NonNull String cookieName - ) { + @edu.umd.cs.findbugs.annotations.NonNull String cookieName) { String[] cookieValues = cookieValue.split("\\."); if (cookieValues.length > 0) { builder.visitorId(VisitorId.fromHex(cookieValues[0])).newVisitor(Boolean.FALSE); cookies.put(cookieName, cookieValue); } } -} \ No newline at end of file +} diff --git a/core/src/main/java/org/piwik/java/tracking/CustomVariable.java b/core/src/main/java/org/piwik/java/tracking/CustomVariable.java index 20845bed..e12cdae4 100644 --- a/core/src/main/java/org/piwik/java/tracking/CustomVariable.java +++ b/core/src/main/java/org/piwik/java/tracking/CustomVariable.java @@ -21,7 +21,7 @@ public class CustomVariable extends org.matomo.java.tracking.parameters.CustomVa /** * Instantiates a new custom variable. * - * @param key the key of the custom variable (required) + * @param key the key of the custom variable (required) * @param value the value of the custom variable (required) * @deprecated Use {@link org.matomo.java.tracking.parameters.CustomVariable} instead. */ diff --git a/core/src/main/java/org/piwik/java/tracking/EcommerceItem.java b/core/src/main/java/org/piwik/java/tracking/EcommerceItem.java index 49c3a83c..e9b4ce6c 100644 --- a/core/src/main/java/org/piwik/java/tracking/EcommerceItem.java +++ b/core/src/main/java/org/piwik/java/tracking/EcommerceItem.java @@ -19,10 +19,10 @@ public class EcommerceItem extends org.matomo.java.tracking.parameters.Ecommerce /** * Creates a new ecommerce item. * - * @param sku the sku (Stock Keeping Unit) of the item. - * @param name the name of the item. + * @param sku the sku (Stock Keeping Unit) of the item. + * @param name the name of the item. * @param category the category of the item. - * @param price the price of the item. + * @param price the price of the item. * @param quantity the quantity of the item. * @deprecated Use {@link org.matomo.java.tracking.parameters.EcommerceItem} instead. */ @@ -30,5 +30,4 @@ public class EcommerceItem extends org.matomo.java.tracking.parameters.Ecommerce public EcommerceItem(String sku, String name, String category, Double price, Integer quantity) { super(sku, name, category, price, quantity); } - } diff --git a/core/src/main/java/org/piwik/java/tracking/PiwikDate.java b/core/src/main/java/org/piwik/java/tracking/PiwikDate.java index d8029269..501ea8ac 100644 --- a/core/src/main/java/org/piwik/java/tracking/PiwikDate.java +++ b/core/src/main/java/org/piwik/java/tracking/PiwikDate.java @@ -13,7 +13,8 @@ import org.matomo.java.tracking.MatomoDate; /** - * A date object that can be used to send dates to Matomo. This class is deprecated and will be removed in a future. + * A date object that can be used to send dates to Matomo. This class is deprecated and will be + * removed in a future. * * @author brettcsorba * @deprecated Please use {@link Instant} @@ -27,11 +28,11 @@ public class PiwikDate extends MatomoDate { * @deprecated Use {@link Instant} instead. */ @Deprecated - public PiwikDate() { - } + public PiwikDate() {} /** - * Creates a new date object with the specified time. The time is specified in milliseconds since the epoch. + * Creates a new date object with the specified time. The time is specified in milliseconds since + * the epoch. * * @param epochMilli The time in milliseconds since the epoch * @deprecated Use {@link Instant} instead. @@ -42,7 +43,8 @@ public PiwikDate(long epochMilli) { } /** - * Sets the time zone for this date object. This is used to convert the date to UTC before sending it to Matomo. + * Sets the time zone for this date object. This is used to convert the date to UTC before sending + * it to Matomo. * * @param zone the time zone to use * @deprecated Use {@link ZonedDateTime#toInstant()} instead. @@ -51,5 +53,4 @@ public PiwikDate(long epochMilli) { public void setTimeZone(TimeZone zone) { setTimeZone(zone.toZoneId()); } - } diff --git a/core/src/main/java/org/piwik/java/tracking/PiwikLocale.java b/core/src/main/java/org/piwik/java/tracking/PiwikLocale.java index 34f156d6..21f31cf7 100644 --- a/core/src/main/java/org/piwik/java/tracking/PiwikLocale.java +++ b/core/src/main/java/org/piwik/java/tracking/PiwikLocale.java @@ -11,8 +11,8 @@ import org.matomo.java.tracking.parameters.Country; /** - * A locale object that can be used to send visitor country to Matomo. This class is deprecated and will be removed in - * the future. + * A locale object that can be used to send visitor country to Matomo. This class is deprecated and + * will be removed in the future. * * @author brettcsorba * @deprecated Use {@link Country} instead. diff --git a/core/src/main/java/org/piwik/java/tracking/PiwikRequest.java b/core/src/main/java/org/piwik/java/tracking/PiwikRequest.java index e4d64fe4..341cf1aa 100644 --- a/core/src/main/java/org/piwik/java/tracking/PiwikRequest.java +++ b/core/src/main/java/org/piwik/java/tracking/PiwikRequest.java @@ -13,8 +13,8 @@ import org.matomo.java.tracking.MatomoRequest; /** - * A request object that can be used to send requests to Matomo. This class is deprecated and will be removed in the - * future. + * A request object that can be used to send requests to Matomo. This class is deprecated and will + * be removed in the future. * * @author brettcsorba * @deprecated Use {@link MatomoRequest} instead. @@ -25,7 +25,7 @@ public class PiwikRequest extends MatomoRequest { /** * Creates a new request object with the specified site ID and action URL. * - * @param siteId the site ID + * @param siteId the site ID * @param actionUrl the action URL. Must not be null. * @deprecated Use {@link MatomoRequest} instead. */ diff --git a/core/src/main/java/org/piwik/java/tracking/PiwikTracker.java b/core/src/main/java/org/piwik/java/tracking/PiwikTracker.java index 02e18b13..89caf0d3 100644 --- a/core/src/main/java/org/piwik/java/tracking/PiwikTracker.java +++ b/core/src/main/java/org/piwik/java/tracking/PiwikTracker.java @@ -32,7 +32,8 @@ public PiwikTracker(@NonNull String hostUrl) { } /** - * Creates a new PiwikTracker instance with the given host URL and timeout in milliseconds. Use -1 for no timeout. + * Creates a new PiwikTracker instance with the given host URL and timeout in milliseconds. Use -1 + * for no timeout. * * @param hostUrl the host URL of the Matomo server * @param timeout the timeout in milliseconds or -1 for no timeout @@ -46,7 +47,7 @@ public PiwikTracker(@NonNull String hostUrl, int timeout) { /** * Creates a new PiwikTracker instance with the given host URL and proxy settings. * - * @param hostUrl the host URL of the Matomo server + * @param hostUrl the host URL of the Matomo server * @param proxyHost the proxy host * @param proxyPort the proxy port * @deprecated Use {@link MatomoTracker} instead. @@ -57,18 +58,18 @@ public PiwikTracker(@NonNull String hostUrl, @Nullable String proxyHost, int pro } /** - * Creates a new PiwikTracker instance with the given host URL, proxy settings and timeout in milliseconds. Use -1 for - * no timeout. + * Creates a new PiwikTracker instance with the given host URL, proxy settings and timeout in + * milliseconds. Use -1 for no timeout. * - * @param hostUrl the host URL of the Matomo server + * @param hostUrl the host URL of the Matomo server * @param proxyHost the proxy host * @param proxyPort the proxy port - * @param timeout the timeout in milliseconds or -1 for no timeout + * @param timeout the timeout in milliseconds or -1 for no timeout * @deprecated Use {@link MatomoTracker} instead. */ @Deprecated - public PiwikTracker(@NonNull String hostUrl, @Nullable String proxyHost, int proxyPort, int timeout) { + public PiwikTracker( + @NonNull String hostUrl, @Nullable String proxyHost, int proxyPort, int timeout) { super(hostUrl, proxyHost, proxyPort, timeout); } - } diff --git a/core/src/main/java/org/piwik/java/tracking/package-info.java b/core/src/main/java/org/piwik/java/tracking/package-info.java index eb647ae7..39f46a23 100644 --- a/core/src/main/java/org/piwik/java/tracking/package-info.java +++ b/core/src/main/java/org/piwik/java/tracking/package-info.java @@ -1,5 +1,2 @@ -/** - * Piwik Java Tracking API. Renamed to {@link org.matomo.java.tracking} in 3.0.0. - */ - +/** Piwik Java Tracking API. Renamed to {@link org.matomo.java.tracking} in 3.0.0. */ package org.piwik.java.tracking; diff --git a/core/src/test/java/org/matomo/java/tracking/AuthTokenTest.java b/core/src/test/java/org/matomo/java/tracking/AuthTokenTest.java index 169a83e6..cac2ba1e 100644 --- a/core/src/test/java/org/matomo/java/tracking/AuthTokenTest.java +++ b/core/src/test/java/org/matomo/java/tracking/AuthTokenTest.java @@ -12,24 +12,23 @@ class AuthTokenTest { void determineAuthTokenReturnsAuthTokenFromRequest() { MatomoRequest request = - MatomoRequests - .event("Inbox", "Open", null, null) - .authToken("bdeca231a312ab12cde124131bedfa23").build(); + MatomoRequests.event("Inbox", "Open", null, null) + .authToken("bdeca231a312ab12cde124131bedfa23") + .build(); String authToken = AuthToken.determineAuthToken(null, singleton(request), null); assertThat(authToken).isEqualTo("bdeca231a312ab12cde124131bedfa23"); - } @Test void determineAuthTokenReturnsAuthTokenFromTrackerConfiguration() { - TrackerConfiguration trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create("https://your-matomo-domain.example/matomo.")) - .defaultAuthToken("bdeca231a312ab12cde124131bedfa23") - .build(); + TrackerConfiguration trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create("https://your-matomo-domain.example/matomo.")) + .defaultAuthToken("bdeca231a312ab12cde124131bedfa23") + .build(); String authToken = AuthToken.determineAuthToken(null, null, trackerConfiguration); @@ -41,16 +40,15 @@ void determineAuthTokenFromTrackerConfigurationIfRequestTokenIsEmpty() { MatomoRequest request = MatomoRequests.ping().authToken("").build(); - TrackerConfiguration trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create("https://your-matomo-domain.example/matomo")) - .defaultAuthToken("bdeca231a312ab12cde124131bedfa23") - .build(); + TrackerConfiguration trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create("https://your-matomo-domain.example/matomo")) + .defaultAuthToken("bdeca231a312ab12cde124131bedfa23") + .build(); String authToken = AuthToken.determineAuthToken(null, singleton(request), trackerConfiguration); assertThat(authToken).isEqualTo("bdeca231a312ab12cde124131bedfa23"); - } @Test @@ -58,16 +56,14 @@ void determineAuthTokenFromTrackerConfigurationIfRequestTokenIsBlank() { MatomoRequest request = MatomoRequests.pageView("Help").authToken(" ").build(); - TrackerConfiguration trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create("https://your-matomo-domain.example/matomo")) - .defaultAuthToken("bdeca231a312ab12cde124131bedfa23") - .build(); + TrackerConfiguration trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create("https://your-matomo-domain.example/matomo")) + .defaultAuthToken("bdeca231a312ab12cde124131bedfa23") + .build(); String authToken = AuthToken.determineAuthToken(null, singleton(request), trackerConfiguration); assertThat(authToken).isEqualTo("bdeca231a312ab12cde124131bedfa23"); - } - } diff --git a/core/src/test/java/org/matomo/java/tracking/BulkRequestTest.java b/core/src/test/java/org/matomo/java/tracking/BulkRequestTest.java index 535986a0..a78aac9b 100644 --- a/core/src/test/java/org/matomo/java/tracking/BulkRequestTest.java +++ b/core/src/test/java/org/matomo/java/tracking/BulkRequestTest.java @@ -11,14 +11,17 @@ class BulkRequestTest { @Test void formatsQueriesAsJson() { - BulkRequest bulkRequest = BulkRequest.builder() - .queries(singleton("idsite=1&rec=1&action_name=TestBulkRequest")) - .authToken("token") - .build(); + BulkRequest bulkRequest = + BulkRequest.builder() + .queries(singleton("idsite=1&rec=1&action_name=TestBulkRequest")) + .authToken("token") + .build(); byte[] bytes = bulkRequest.toBytes(); - assertThat(new String(bytes)).isEqualTo("{\"requests\":[\"?idsite=1&rec=1&action_name=TestBulkRequest\"],\"token_auth\":\"token\"}"); + assertThat(new String(bytes)) + .isEqualTo( + "{\"requests\":[\"?idsite=1&rec=1&action_name=TestBulkRequest\"],\"token_auth\":\"token\"}"); } @Test @@ -29,7 +32,5 @@ void failsIfQueriesAreEmpty() { assertThatThrownBy(bulkRequest::toBytes) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Queries must not be empty"); - } - -} \ No newline at end of file +} diff --git a/core/src/test/java/org/matomo/java/tracking/CustomVariableTest.java b/core/src/test/java/org/matomo/java/tracking/CustomVariableTest.java index e58a10dd..8f1cb0bd 100644 --- a/core/src/test/java/org/matomo/java/tracking/CustomVariableTest.java +++ b/core/src/test/java/org/matomo/java/tracking/CustomVariableTest.java @@ -17,27 +17,19 @@ void createsCustomVariable() { @Test void failsOnNullKey() { - assertThatThrownBy(() -> new CustomVariable( - null, - "value" - )).isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> new CustomVariable(null, "value")) + .isInstanceOf(NullPointerException.class); } @Test void failsOnNullValue() { - assertThatThrownBy(() -> new CustomVariable( - "key", - null - )).isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> new CustomVariable("key", null)) + .isInstanceOf(NullPointerException.class); } @Test void failsOnNullKeyAndValue() { - assertThatThrownBy(() -> new CustomVariable( - null, - null - )).isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> new CustomVariable(null, null)) + .isInstanceOf(NullPointerException.class); } - - } diff --git a/core/src/test/java/org/matomo/java/tracking/DaemonThreadFactoryTest.java b/core/src/test/java/org/matomo/java/tracking/DaemonThreadFactoryTest.java index 787693db..a8c245cd 100644 --- a/core/src/test/java/org/matomo/java/tracking/DaemonThreadFactoryTest.java +++ b/core/src/test/java/org/matomo/java/tracking/DaemonThreadFactoryTest.java @@ -10,18 +10,21 @@ class DaemonThreadFactoryTest { @Test void createsNewThreadAsDaemonThread() { - Thread thread = daemonThreadFactory.newThread(() -> { - // do nothing - }); + Thread thread = + daemonThreadFactory.newThread( + () -> { + // do nothing + }); assertThat(thread.isDaemon()).isTrue(); } @Test void createsNewThreadWithMatomoJavaTrackerName() { - Thread thread = daemonThreadFactory.newThread(() -> { - // do nothing - }); + Thread thread = + daemonThreadFactory.newThread( + () -> { + // do nothing + }); assertThat(thread.getName()).startsWith("MatomoJavaTracker-"); } - -} \ No newline at end of file +} diff --git a/core/src/test/java/org/matomo/java/tracking/EcommerceItemTest.java b/core/src/test/java/org/matomo/java/tracking/EcommerceItemTest.java index 71e9fcc0..b2d5ac8e 100644 --- a/core/src/test/java/org/matomo/java/tracking/EcommerceItemTest.java +++ b/core/src/test/java/org/matomo/java/tracking/EcommerceItemTest.java @@ -8,9 +8,7 @@ class EcommerceItemTest { private EcommerceItem ecommerceItem = new EcommerceItem(null, null, null, null, null); - /** - * Test of constructor, of class EcommerceItem. - */ + /** Test of constructor, of class EcommerceItem. */ @Test void testConstructor() { EcommerceItem ecommerceItem = new EcommerceItem("sku", "name", "category", 2.0, 2); @@ -21,45 +19,35 @@ void testConstructor() { assertThat(ecommerceItem.getQuantity()).isEqualTo(2); } - /** - * Test of getSku method, of class EcommerceItem. - */ + /** Test of getSku method, of class EcommerceItem. */ @Test void testGetSku() { ecommerceItem.setSku("sku"); assertThat(ecommerceItem.getSku()).isEqualTo("sku"); } - /** - * Test of getName method, of class EcommerceItem. - */ + /** Test of getName method, of class EcommerceItem. */ @Test void testGetName() { ecommerceItem.setName("name"); assertThat(ecommerceItem.getName()).isEqualTo("name"); } - /** - * Test of getCategory method, of class EcommerceItem. - */ + /** Test of getCategory method, of class EcommerceItem. */ @Test void testGetCategory() { ecommerceItem.setCategory("category"); assertThat(ecommerceItem.getCategory()).isEqualTo("category"); } - /** - * Test of getPrice method, of class EcommerceItem. - */ + /** Test of getPrice method, of class EcommerceItem. */ @Test void testGetPrice() { ecommerceItem.setPrice(2.0); assertThat(ecommerceItem.getPrice()).isEqualTo(2.0); } - /** - * Test of getQuantity method, of class EcommerceItem. - */ + /** Test of getQuantity method, of class EcommerceItem. */ @Test void testGetQuantity() { ecommerceItem.setQuantity(2); diff --git a/core/src/test/java/org/matomo/java/tracking/ExecutorServiceCloserTest.java b/core/src/test/java/org/matomo/java/tracking/ExecutorServiceCloserTest.java index e0d167a9..7ba5f14b 100644 --- a/core/src/test/java/org/matomo/java/tracking/ExecutorServiceCloserTest.java +++ b/core/src/test/java/org/matomo/java/tracking/ExecutorServiceCloserTest.java @@ -17,30 +17,30 @@ void shutsDownExecutorService() { assertThat(executorService.isTerminated()).isTrue(); assertThat(executorService.isShutdown()).isTrue(); - } @Test void shutsDownExecutorServiceImmediately() throws Exception { ExecutorService executorService = Executors.newSingleThreadExecutor(); - executorService.submit(() -> { - try { - Thread.sleep(10000L); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - }); - - Thread thread = new Thread(() -> { - ExecutorServiceCloser.close(executorService); - }); + executorService.submit( + () -> { + try { + Thread.sleep(10000L); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + }); + + Thread thread = + new Thread( + () -> { + ExecutorServiceCloser.close(executorService); + }); thread.start(); Thread.sleep(1000L); thread.interrupt(); assertThat(executorService.isShutdown()).isTrue(); - } - -} \ No newline at end of file +} diff --git a/core/src/test/java/org/matomo/java/tracking/InvalidUrlExceptionTest.java b/core/src/test/java/org/matomo/java/tracking/InvalidUrlExceptionTest.java index 17605f04..e1feca8a 100644 --- a/core/src/test/java/org/matomo/java/tracking/InvalidUrlExceptionTest.java +++ b/core/src/test/java/org/matomo/java/tracking/InvalidUrlExceptionTest.java @@ -12,7 +12,5 @@ void createsInvalidUrlException() { assertThat(invalidUrlException).isNotNull(); assertThat(invalidUrlException.getCause()).isNotNull(); - } - } diff --git a/core/src/test/java/org/matomo/java/tracking/MatomoExceptionTest.java b/core/src/test/java/org/matomo/java/tracking/MatomoExceptionTest.java index 9c998a37..ae59041e 100644 --- a/core/src/test/java/org/matomo/java/tracking/MatomoExceptionTest.java +++ b/core/src/test/java/org/matomo/java/tracking/MatomoExceptionTest.java @@ -21,5 +21,4 @@ void createsMatomoExceptionWithMessageAndCause() { assertEquals("message", matomoException.getMessage()); assertEquals(cause, matomoException.getCause()); } - } diff --git a/core/src/test/java/org/matomo/java/tracking/MatomoLocaleTest.java b/core/src/test/java/org/matomo/java/tracking/MatomoLocaleTest.java index 7822acd3..c4d1f5ba 100644 --- a/core/src/test/java/org/matomo/java/tracking/MatomoLocaleTest.java +++ b/core/src/test/java/org/matomo/java/tracking/MatomoLocaleTest.java @@ -20,5 +20,4 @@ void failsIfLocaleIsNull() { .isInstanceOf(NullPointerException.class) .hasMessage("Locale must not be null"); } - } diff --git a/core/src/test/java/org/matomo/java/tracking/MatomoRequestBuilderTest.java b/core/src/test/java/org/matomo/java/tracking/MatomoRequestBuilderTest.java index 87dab6d5..d46403d2 100644 --- a/core/src/test/java/org/matomo/java/tracking/MatomoRequestBuilderTest.java +++ b/core/src/test/java/org/matomo/java/tracking/MatomoRequestBuilderTest.java @@ -6,7 +6,6 @@ import org.junit.jupiter.api.Test; import org.matomo.java.tracking.parameters.CustomVariables; - class MatomoRequestBuilderTest { @Test @@ -16,73 +15,70 @@ void buildsRequest() { CustomVariable visitCustomVariable = new CustomVariable("visitCustomVariableName", "visitCustomVariableValue"); - MatomoRequest matomoRequest = new MatomoRequestBuilder() - .siteId(42) - .actionName("ACTION_NAME") - .actionUrl("https://www.your-domain.tld/some/page?query=foo") - .referrerUrl("https://referrer.com") - .additionalParameters(singletonMap( - "trackingParameterName", - "trackingParameterValue" - )) - .pageCustomVariables(new CustomVariables().add(pageCustomVariable, 2)) - .visitCustomVariables(new CustomVariables().add(visitCustomVariable, 3)) - .customAction(true) - .build(); + MatomoRequest matomoRequest = + new MatomoRequestBuilder() + .siteId(42) + .actionName("ACTION_NAME") + .actionUrl("https://www.your-domain.tld/some/page?query=foo") + .referrerUrl("https://referrer.com") + .additionalParameters(singletonMap("trackingParameterName", "trackingParameterValue")) + .pageCustomVariables(new CustomVariables().add(pageCustomVariable, 2)) + .visitCustomVariables(new CustomVariables().add(visitCustomVariable, 3)) + .customAction(true) + .build(); assertThat(matomoRequest.getSiteId()).isEqualTo(42); assertThat(matomoRequest.getActionName()).isEqualTo("ACTION_NAME"); assertThat(matomoRequest.getApiVersion()).isEqualTo("1"); - assertThat(matomoRequest.getActionUrl()).isEqualTo( - "https://www.your-domain.tld/some/page?query=foo"); + assertThat(matomoRequest.getActionUrl()) + .isEqualTo("https://www.your-domain.tld/some/page?query=foo"); assertThat(matomoRequest.getVisitorId().toString()).hasSize(16).isHexadecimal(); assertThat(matomoRequest.getRandomValue().toString()).hasSize(20).isHexadecimal(); assertThat(matomoRequest.getResponseAsImage()).isFalse(); assertThat(matomoRequest.getRequired()).isTrue(); assertThat(matomoRequest.getReferrerUrl()).isEqualTo("https://referrer.com"); - assertThat(matomoRequest.getCustomTrackingParameter("trackingParameterName")).isEqualTo( - "trackingParameterValue"); - assertThat(matomoRequest.getPageCustomVariables()).hasToString( - "{\"2\":[\"pageCustomVariableName\",\"pageCustomVariableValue\"]}"); - assertThat(matomoRequest.getVisitCustomVariables()).hasToString( - "{\"3\":[\"visitCustomVariableName\",\"visitCustomVariableValue\"]}"); + assertThat(matomoRequest.getCustomTrackingParameter("trackingParameterName")) + .isEqualTo("trackingParameterValue"); + assertThat(matomoRequest.getPageCustomVariables()) + .hasToString("{\"2\":[\"pageCustomVariableName\",\"pageCustomVariableValue\"]}"); + assertThat(matomoRequest.getVisitCustomVariables()) + .hasToString("{\"3\":[\"visitCustomVariableName\",\"visitCustomVariableValue\"]}"); assertThat(matomoRequest.getCustomAction()).isTrue(); - } @Test void setCustomTrackingParameters() { - MatomoRequest matomoRequest = new MatomoRequestBuilder() - .customTrackingParameters(singletonMap("foo", "bar")) - .siteId(42) - .actionName("ACTION_NAME") - .actionUrl("https://www.your-domain.tld/some/page?query=foo") - .referrerUrl("https://referrer.com") - .build(); + MatomoRequest matomoRequest = + new MatomoRequestBuilder() + .customTrackingParameters(singletonMap("foo", "bar")) + .siteId(42) + .actionName("ACTION_NAME") + .actionUrl("https://www.your-domain.tld/some/page?query=foo") + .referrerUrl("https://referrer.com") + .build(); assertThat(matomoRequest.getCustomTrackingParameter("foo")).isEqualTo("bar"); } @Test void setCustomTrackingParametersWithCollectopm() { - MatomoRequest matomoRequest = new MatomoRequestBuilder() - .customTrackingParameters(singletonMap("foo", "bar")) - .siteId(42) - .actionName("ACTION_NAME") - .actionUrl("https://www.your-domain.tld/some/page?query=foo") - .referrerUrl("https://referrer.com") - .build(); + MatomoRequest matomoRequest = + new MatomoRequestBuilder() + .customTrackingParameters(singletonMap("foo", "bar")) + .siteId(42) + .actionName("ACTION_NAME") + .actionUrl("https://www.your-domain.tld/some/page?query=foo") + .referrerUrl("https://referrer.com") + .build(); assertThat(matomoRequest.getCustomTrackingParameter("foo")).isEqualTo("bar"); } @Test void acceptsNullAsHeaderAcceptLanguage() { - MatomoRequest matomoRequest = new MatomoRequestBuilder() - .headerAcceptLanguage((String) null) - .build(); + MatomoRequest matomoRequest = + new MatomoRequestBuilder().headerAcceptLanguage((String) null).build(); assertThat(matomoRequest.getHeaderAcceptLanguage()).isNull(); } - } diff --git a/core/src/test/java/org/matomo/java/tracking/MatomoRequestTest.java b/core/src/test/java/org/matomo/java/tracking/MatomoRequestTest.java index b4ad0e04..20d2c2f5 100644 --- a/core/src/test/java/org/matomo/java/tracking/MatomoRequestTest.java +++ b/core/src/test/java/org/matomo/java/tracking/MatomoRequestTest.java @@ -32,8 +32,8 @@ void getPageCustomVariableReturnsValueIfPageCustomVariablesIsNotNull() { @Test void setPageCustomVariableRequiresNonNullKey() { - assertThatThrownBy(() -> request.setPageCustomVariable(null, "bar")).isInstanceOf( - NullPointerException.class); + assertThatThrownBy(() -> request.setPageCustomVariable(null, "bar")) + .isInstanceOf(NullPointerException.class); } @Test @@ -62,7 +62,8 @@ void setPageCustomVariableDoesNothingIfCustomVariableParameterIsNullAndIndexIsPo } @Test - void setPageCustomVariableInitializesPageCustomVariablesIfCustomVariableParameterIsNullAndIndexIsPositive() { + void + setPageCustomVariableInitializesPageCustomVariablesIfCustomVariableParameterIsNullAndIndexIsPositive() { request.setPageCustomVariable(new CustomVariable("key", "value"), 1); assertThat(request.getPageCustomVariables()).isNotNull(); } @@ -87,7 +88,8 @@ void setVisitCustomVariableDoesNothingIfCustomVariableParameterIsNullAndIndexIsP } @Test - void setVisitCustomVariableInitializesVisitCustomVariablesIfCustomVariableParameterIsNullAndIndexIsPositive() { + void + setVisitCustomVariableInitializesVisitCustomVariablesIfCustomVariableParameterIsNullAndIndexIsPositive() { request.setVisitCustomVariable(new CustomVariable("key", "value"), 1); assertThat(request.getVisitCustomVariables()).isNotNull(); } @@ -100,10 +102,8 @@ void setsCustomParameter() { @Test void failsToSetCustomParameterIfKeyIsNull() { - assertThatThrownBy(() -> request.setParameter( - null, - 1 - )).isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> request.setParameter(null, 1)) + .isInstanceOf(NullPointerException.class); } @Test @@ -127,8 +127,7 @@ void setsDeviceResolutionString() { @Test void failsIfSetParameterParameterNameIsBlank() { - assertThatThrownBy(() -> request.setParameter(" ", "bar")).isInstanceOf( - IllegalArgumentException.class); + assertThatThrownBy(() -> request.setParameter(" ", "bar")) + .isInstanceOf(IllegalArgumentException.class); } - } diff --git a/core/src/test/java/org/matomo/java/tracking/MatomoRequestsTest.java b/core/src/test/java/org/matomo/java/tracking/MatomoRequestsTest.java index 3aa058d2..fe18ccf4 100644 --- a/core/src/test/java/org/matomo/java/tracking/MatomoRequestsTest.java +++ b/core/src/test/java/org/matomo/java/tracking/MatomoRequestsTest.java @@ -1,6 +1,5 @@ package org.matomo.java.tracking; - import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatNullPointerException; @@ -13,8 +12,7 @@ void actionRequestBuilderContainsDownloadUrl() { MatomoRequest.MatomoRequestBuilder builder = MatomoRequests.action("https://example.com", ActionType.DOWNLOAD); MatomoRequest request = builder.build(); - assertThat(request.getDownloadUrl()) - .isEqualTo("https://example.com"); + assertThat(request.getDownloadUrl()).isEqualTo("https://example.com"); } @Test @@ -22,8 +20,7 @@ void actionRequestBuilderContainsOutlinkUrl() { MatomoRequest.MatomoRequestBuilder builder = MatomoRequests.action("https://example.com", ActionType.LINK); MatomoRequest request = builder.build(); - assertThat(request.getOutlinkUrl()) - .isEqualTo("https://example.com"); + assertThat(request.getOutlinkUrl()).isEqualTo("https://example.com"); } @Test @@ -36,19 +33,15 @@ void contentImpressionRequestBuilderContainsContentInformation() { .extracting( MatomoRequest::getContentName, MatomoRequest::getContentPiece, - MatomoRequest::getContentTarget - ) + MatomoRequest::getContentTarget) .containsExactly("Product", "Smartphone", "https://example.com/product"); } @Test void contentInteractionRequestBuilderContainsInteractionAndContentInformation() { - MatomoRequest.MatomoRequestBuilder builder = MatomoRequests.contentInteraction( - "click", - "Product", - "Smartphone", - "https://example.com/product" - ); + MatomoRequest.MatomoRequestBuilder builder = + MatomoRequests.contentInteraction( + "click", "Product", "Smartphone", "https://example.com/product"); MatomoRequest request = builder.build(); assertThat(request) .isNotNull() @@ -56,22 +49,21 @@ void contentInteractionRequestBuilderContainsInteractionAndContentInformation() MatomoRequest::getContentInteraction, MatomoRequest::getContentName, MatomoRequest::getContentPiece, - MatomoRequest::getContentTarget - ) + MatomoRequest::getContentTarget) .containsExactly("click", "Product", "Smartphone", "https://example.com/product"); } @Test void crashRequestBuilderContainsCrashInformation() { - MatomoRequest.MatomoRequestBuilder builder = MatomoRequests.crash( - "Error", - "NullPointerException", - "payment failure", - "stackTrace", - "MainActivity.java", - 42, - 23 - ); + MatomoRequest.MatomoRequestBuilder builder = + MatomoRequests.crash( + "Error", + "NullPointerException", + "payment failure", + "stackTrace", + "MainActivity.java", + 42, + 23); MatomoRequest request = builder.build(); assertThat(request) .isNotNull() @@ -82,8 +74,7 @@ void crashRequestBuilderContainsCrashInformation() { MatomoRequest::getCrashStackTrace, MatomoRequest::getCrashLocation, MatomoRequest::getCrashLine, - MatomoRequest::getCrashColumn - ) + MatomoRequest::getCrashColumn) .containsExactly( "Error", "NullPointerException", @@ -91,8 +82,7 @@ void crashRequestBuilderContainsCrashInformation() { "stackTrace", "MainActivity.java", 42, - 23 - ); + 23); } @Test @@ -110,10 +100,7 @@ void crashWithThrowableRequestBuilderContainsCrashInformationFromThrowable() { void ecommerceCartUpdateRequestBuilderContainsEcommerceRevenue() { MatomoRequest.MatomoRequestBuilder builder = MatomoRequests.ecommerceCartUpdate(100.0); MatomoRequest request = builder.build(); - assertThat(request) - .isNotNull() - .extracting(MatomoRequest::getEcommerceRevenue) - .isEqualTo(100.0); + assertThat(request).isNotNull().extracting(MatomoRequest::getEcommerceRevenue).isEqualTo(100.0); } @Test @@ -129,19 +116,14 @@ void ecommerceOrderRequestBuilderContainsEcommerceOrderInformation() { MatomoRequest::getEcommerceSubtotal, MatomoRequest::getEcommerceTax, MatomoRequest::getEcommerceShippingCost, - MatomoRequest::getEcommerceDiscount - ) + MatomoRequest::getEcommerceDiscount) .containsExactly("123", 200.0, 180.0, 10.0, 5.0, 5.0); } @Test void eventRequestBuilderContainsEventInformation() { - MatomoRequest.MatomoRequestBuilder builder = MatomoRequests.event( - "Music", - "Play", - "Edvard Grieg - The Death of Ase", - 9.99 - ); + MatomoRequest.MatomoRequestBuilder builder = + MatomoRequests.event("Music", "Play", "Edvard Grieg - The Death of Ase", 9.99); MatomoRequest request = builder.build(); assertThat(request) .isNotNull() @@ -149,24 +131,17 @@ void eventRequestBuilderContainsEventInformation() { MatomoRequest::getEventCategory, MatomoRequest::getEventAction, MatomoRequest::getEventName, - MatomoRequest::getEventValue - ) + MatomoRequest::getEventValue) .containsExactly("Music", "Play", "Edvard Grieg - The Death of Ase", 9.99); } @Test void goalRequestBuilderContainsGoalInformation() { - MatomoRequest.MatomoRequestBuilder builder = MatomoRequests.goal( - 1, - 9.99 - ); + MatomoRequest.MatomoRequestBuilder builder = MatomoRequests.goal(1, 9.99); MatomoRequest request = builder.build(); assertThat(request) .isNotNull() - .extracting( - MatomoRequest::getGoalId, - MatomoRequest::getEcommerceRevenue - ) + .extracting(MatomoRequest::getGoalId, MatomoRequest::getEcommerceRevenue) .containsExactly(1, 9.99); } @@ -174,8 +149,7 @@ void goalRequestBuilderContainsGoalInformation() { void pageViewRequestBuilderContainsPageViewInformation() { MatomoRequest.MatomoRequestBuilder builder = MatomoRequests.pageView("About"); MatomoRequest request = builder.build(); - assertThat(request.getActionName()) - .isEqualTo("About"); + assertThat(request.getActionName()).isEqualTo("About"); } @Test @@ -188,8 +162,7 @@ void searchRequestBuilderContainsSearchInformation() { .extracting( MatomoRequest::getSearchQuery, MatomoRequest::getSearchCategory, - MatomoRequest::getSearchResultsCount - ) + MatomoRequest::getSearchResultsCount) .containsExactly("Matomo", "Download", 42L); } @@ -228,11 +201,9 @@ void actionNullTypeThrowsNullPointerException() { @Test void contentImpressionNullNameThrowsNullPointerException() { assertThatNullPointerException() - .isThrownBy(() -> MatomoRequests.contentImpression( - null, - "Smartphone", - "https://example.com/product" - )) + .isThrownBy( + () -> + MatomoRequests.contentImpression(null, "Smartphone", "https://example.com/product")) .withMessage("name is marked non-null but is null"); } @@ -241,15 +212,16 @@ void contentImpressionNullNameThrowsNullPointerException() { @Test void crashNullMessageThrowsNullPointerException() { assertThatNullPointerException() - .isThrownBy(() -> MatomoRequests.crash( - null, - "NullPointerException", - "payment failure", - "stackTrace", - "MainActivity.java", - 42, - 23 - )) + .isThrownBy( + () -> + MatomoRequests.crash( + null, + "NullPointerException", + "payment failure", + "stackTrace", + "MainActivity.java", + 42, + 23)) .withMessage("message is marked non-null but is null"); } @@ -277,12 +249,8 @@ void ecommerceOrderNullIdThrowsNullPointerException() { @Test void eventNullCategoryThrowsNullPointerException() { assertThatNullPointerException() - .isThrownBy(() -> MatomoRequests.event( - null, - "Play", - "Edvard Grieg - The Death of Ase", - 9.99 - )) + .isThrownBy( + () -> MatomoRequests.event(null, "Play", "Edvard Grieg - The Death of Ase", 9.99)) .withMessage("category is marked non-null but is null"); } @@ -308,11 +276,10 @@ void crashDoesNotIncludeStackTraceIfStackTraceOfThrowableIsEmpty() { assertThat(request.getCrashMessage()).isEqualTo("message"); assertThat(request.getCrashType()).isEqualTo("org.matomo.java.tracking.TestThrowable"); assertThat(request.getCrashCategory()).isEqualTo("payment failure"); - assertThat(request.getCrashStackTrace()).isEqualTo( - "org.matomo.java.tracking.TestThrowable: message"); + assertThat(request.getCrashStackTrace()) + .isEqualTo("org.matomo.java.tracking.TestThrowable: message"); assertThat(request.getCrashLocation()).isNull(); assertThat(request.getCrashLine()).isNull(); assertThat(request.getCrashColumn()).isNull(); } - -} \ No newline at end of file +} diff --git a/core/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java b/core/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java index c312c717..efbdb067 100644 --- a/core/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java +++ b/core/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java @@ -17,13 +17,13 @@ class MatomoTrackerIT { "rec=1&idsite=1&action_name=test&apiv=1&_id=00000000343efaf5&send_image=0&rand=test-random"; private MatomoTracker matomoTracker; private final TestSenderFactory senderFactory = new TestSenderFactory(); - private final MatomoRequest request = MatomoRequest - .request() - .siteId(1) - .visitorId(VisitorId.fromString("test-visitor-id")) - .randomValue(RandomValue.fromString("test-random")) - .actionName("test") - .build(); + private final MatomoRequest request = + MatomoRequest.request() + .siteId(1) + .visitorId(VisitorId.fromString("test-visitor-id")) + .randomValue(RandomValue.fromString("test-random")) + .actionName("test") + .build(); @Test void sendsRequest() { @@ -36,7 +36,6 @@ void sendsRequest() { TestSender testSender = senderFactory.getTestSender(); thenContainsRequest(testSender, QUERY); assertThat(testSender.getTrackerConfiguration().getApiEndpoint()).hasToString(HOST_URL); - } @Test @@ -51,20 +50,22 @@ void validatesRequest() { .hasMessageContaining("No default site ID and no request site ID is given"); assertThat(senderFactory.getTestSender()).isNull(); - } @Test void doesNotSendRequestIfNotEnabled() { matomoTracker = - new MatomoTracker(TrackerConfiguration.builder().apiEndpoint(URI.create(HOST_URL)).enabled(false).build()); + new MatomoTracker( + TrackerConfiguration.builder() + .apiEndpoint(URI.create(HOST_URL)) + .enabled(false) + .build()); matomoTracker.setSenderFactory(senderFactory); matomoTracker.sendRequest(request); assertThat(senderFactory.getTestSender()).isNull(); - } @Test @@ -80,7 +81,6 @@ void sendsRequestUsingProxy() { TrackerConfiguration trackerConfiguration = testSender.getTrackerConfiguration(); assertThat(trackerConfiguration.getProxyHost()).isEqualTo("localhost"); assertThat(trackerConfiguration.getProxyPort()).isEqualTo(8081); - } @Test @@ -94,7 +94,6 @@ void sendsRequestAsync() { TestSender testSender = senderFactory.getTestSender(); thenContainsRequest(testSender, QUERY); assertThat(testSender.getTrackerConfiguration().getApiEndpoint()).hasToString(HOST_URL); - } @Test @@ -103,30 +102,34 @@ void sendsRequestAsyncWithCallback() { matomoTracker = new MatomoTracker(HOST_URL, 1000); matomoTracker.setSenderFactory(senderFactory); AtomicBoolean callbackCalled = new AtomicBoolean(); - matomoTracker.sendRequestAsync(request, request -> { - assertThat(request).isEqualTo(request); - callbackCalled.set(true); - return null; - }); + matomoTracker.sendRequestAsync( + request, + request -> { + assertThat(request).isEqualTo(request); + callbackCalled.set(true); + return null; + }); TestSender testSender = senderFactory.getTestSender(); thenContainsRequest(testSender, QUERY); assertThat(testSender.getTrackerConfiguration().getApiEndpoint()).hasToString(HOST_URL); assertThat(callbackCalled).isTrue(); - } @Test void doesNotSendRequestAsyncIfNotEnabled() { matomoTracker = - new MatomoTracker(TrackerConfiguration.builder().apiEndpoint(URI.create(HOST_URL)).enabled(false).build()); + new MatomoTracker( + TrackerConfiguration.builder() + .apiEndpoint(URI.create(HOST_URL)) + .enabled(false) + .build()); matomoTracker.setSenderFactory(senderFactory); matomoTracker.sendRequestAsync(request); assertThat(senderFactory.getTestSender()).isNull(); - } @Test @@ -140,20 +143,22 @@ void sendsBulkRequests() { TestSender testSender = senderFactory.getTestSender(); thenContainsRequest(testSender, QUERY); assertThat(testSender.getTrackerConfiguration().getApiEndpoint()).hasToString(HOST_URL); - } @Test void doesNotSendBulkRequestsIfNotEnabled() { matomoTracker = - new MatomoTracker(TrackerConfiguration.builder().apiEndpoint(URI.create(HOST_URL)).enabled(false).build()); + new MatomoTracker( + TrackerConfiguration.builder() + .apiEndpoint(URI.create(HOST_URL)) + .enabled(false) + .build()); matomoTracker.setSenderFactory(senderFactory); matomoTracker.sendBulkRequest(request); assertThat(senderFactory.getTestSender()).isNull(); - } @Test @@ -167,20 +172,22 @@ void sendsBulkRequestsAsync() { TestSender testSender = senderFactory.getTestSender(); thenContainsRequest(testSender, QUERY); assertThat(testSender.getTrackerConfiguration().getApiEndpoint()).hasToString(HOST_URL); - } @Test void doesNotSendBulkRequestsAsyncIfNotEnabled() { matomoTracker = - new MatomoTracker(TrackerConfiguration.builder().apiEndpoint(URI.create(HOST_URL)).enabled(false).build()); + new MatomoTracker( + TrackerConfiguration.builder() + .apiEndpoint(URI.create(HOST_URL)) + .enabled(false) + .build()); matomoTracker.setSenderFactory(senderFactory); matomoTracker.sendBulkRequestAsync(request); assertThat(senderFactory.getTestSender()).isNull(); - } @Test @@ -195,7 +202,6 @@ void sendsBulkRequestAsyncWithCallback() { thenContainsRequest(testSender, QUERY); assertThat(testSender.getTrackerConfiguration().getApiEndpoint()).hasToString(HOST_URL); assertThat(callbackCalled).isTrue(); - } @Test @@ -206,9 +212,10 @@ void sendsBulkRequestAsyncWithAuthToken() { matomoTracker.sendBulkRequestAsync(singleton(request), "abc123def456abc123def456abc123de"); TestSender testSender = senderFactory.getTestSender(); - thenContainsRequest(testSender, "token_auth=abc123def456abc123def456abc123de&rec=1&idsite=1&action_name=test&apiv=1&_id=00000000343efaf5&send_image=0&rand=test-random"); + thenContainsRequest( + testSender, + "token_auth=abc123def456abc123def456abc123de&rec=1&idsite=1&action_name=test&apiv=1&_id=00000000343efaf5&send_image=0&rand=test-random"); assertThat(testSender.getTrackerConfiguration().getApiEndpoint()).hasToString(HOST_URL); - } @Test @@ -221,14 +228,14 @@ void appliesGoalId() { matomoTracker.sendRequest(request); TestSender testSender = senderFactory.getTestSender(); - thenContainsRequest(testSender, "rec=1&idsite=1&action_name=test&apiv=1&_id=00000000343efaf5&idgoal=0&ec_id=some-id&send_image=0&rand=test-random"); + thenContainsRequest( + testSender, + "rec=1&idsite=1&action_name=test&apiv=1&_id=00000000343efaf5&idgoal=0&ec_id=some-id&send_image=0&rand=test-random"); assertThat(testSender.getTrackerConfiguration().getApiEndpoint()).hasToString(HOST_URL); - } private void thenContainsRequest(TestSender testSender, String query) { assertThat(testSender.getRequests()).containsExactly(request); assertThat(testSender.getQueries()).containsExactly(query); } - -} \ No newline at end of file +} diff --git a/core/src/test/java/org/matomo/java/tracking/PiwikDateTest.java b/core/src/test/java/org/matomo/java/tracking/PiwikDateTest.java index 40c8bd80..c5d99795 100644 --- a/core/src/test/java/org/matomo/java/tracking/PiwikDateTest.java +++ b/core/src/test/java/org/matomo/java/tracking/PiwikDateTest.java @@ -6,12 +6,9 @@ import org.junit.jupiter.api.Test; import org.piwik.java.tracking.PiwikDate; - class PiwikDateTest { - /** - * Test of constructor, of class PiwikDate. - */ + /** Test of constructor, of class PiwikDate. */ @Test void testConstructor0() { PiwikDate date = new PiwikDate(); @@ -31,9 +28,7 @@ void testConstructor2() { assertThat(date.getTime()).isEqualTo(1467437553000L); } - /** - * Test of setTimeZone method, of class PiwikDate. - */ + /** Test of setTimeZone method, of class PiwikDate. */ @Test void testSetTimeZone() { PiwikDate date = new PiwikDate(1433186085092L); diff --git a/core/src/test/java/org/matomo/java/tracking/PiwikLocaleTest.java b/core/src/test/java/org/matomo/java/tracking/PiwikLocaleTest.java index 46e1c563..a03b97c9 100644 --- a/core/src/test/java/org/matomo/java/tracking/PiwikLocaleTest.java +++ b/core/src/test/java/org/matomo/java/tracking/PiwikLocaleTest.java @@ -10,18 +10,14 @@ class PiwikLocaleTest { private final PiwikLocale locale = new PiwikLocale(Locale.US); - /** - * Test of setLocale method, of class PiwikLocale. - */ + /** Test of setLocale method, of class PiwikLocale. */ @Test void testLocale() { locale.setLocale(Locale.GERMANY); assertThat(locale.getLocale()).isEqualTo(Locale.GERMAN); } - /** - * Test of toString method, of class PiwikLocale. - */ + /** Test of toString method, of class PiwikLocale. */ @Test void testToString() { assertThat(locale).hasToString("us"); diff --git a/core/src/test/java/org/matomo/java/tracking/PiwikRequestTest.java b/core/src/test/java/org/matomo/java/tracking/PiwikRequestTest.java index c88c7570..6f11c1e7 100644 --- a/core/src/test/java/org/matomo/java/tracking/PiwikRequestTest.java +++ b/core/src/test/java/org/matomo/java/tracking/PiwikRequestTest.java @@ -42,9 +42,7 @@ void testConstructor() throws Exception { assertThat(request.getResponseAsImage()).isFalse(); } - /** - * Test of getActionName method, of class PiwikRequest. - */ + /** Test of getActionName method, of class PiwikRequest. */ @Test void testActionName() { request.setActionName("action"); @@ -53,9 +51,7 @@ void testActionName() { assertThat(request.getActionName()).isNull(); } - /** - * Test of getActionUrl method, of class PiwikRequest. - */ + /** Test of getActionUrl method, of class PiwikRequest. */ @Test void testActionUrl() { request.setActionUrl(null); @@ -64,9 +60,7 @@ void testActionUrl() { assertThat(request.getActionUrl()).isEqualTo("https://action.com"); } - /** - * Test of getApiVersion method, of class PiwikRequest. - */ + /** Test of getApiVersion method, of class PiwikRequest. */ @Test void testApiVersion() { request.setApiVersion("2"); @@ -86,27 +80,21 @@ void testAuthTokenF() { assertThat(request.getAuthToken()).isNull(); } - /** - * Test of getCampaignKeyword method, of class PiwikRequest. - */ + /** Test of getCampaignKeyword method, of class PiwikRequest. */ @Test void testCampaignKeyword() { request.setCampaignKeyword("keyword"); assertThat(request.getCampaignKeyword()).isEqualTo("keyword"); } - /** - * Test of getCampaignName method, of class PiwikRequest. - */ + /** Test of getCampaignName method, of class PiwikRequest. */ @Test void testCampaignName() { request.setCampaignName("name"); assertThat(request.getCampaignName()).isEqualTo("name"); } - /** - * Test of getCharacterSet method, of class PiwikRequest. - */ + /** Test of getCharacterSet method, of class PiwikRequest. */ @Test void testCharacterSet() { Charset charset = Charset.defaultCharset(); @@ -114,72 +102,56 @@ void testCharacterSet() { assertThat(request.getCharacterSet()).isEqualTo(charset); } - /** - * Test of getContentInteraction method, of class PiwikRequest. - */ + /** Test of getContentInteraction method, of class PiwikRequest. */ @Test void testContentInteraction() { request.setContentInteraction("interaction"); assertThat(request.getContentInteraction()).isEqualTo("interaction"); } - /** - * Test of getContentName method, of class PiwikRequest. - */ + /** Test of getContentName method, of class PiwikRequest. */ @Test void testContentName() { request.setContentName("name"); assertThat(request.getContentName()).isEqualTo("name"); } - /** - * Test of getContentPiece method, of class PiwikRequest. - */ + /** Test of getContentPiece method, of class PiwikRequest. */ @Test void testContentPiece() { request.setContentPiece("piece"); assertThat(request.getContentPiece()).isEqualTo("piece"); } - /** - * Test of getContentTarget method, of class PiwikRequest. - */ + /** Test of getContentTarget method, of class PiwikRequest. */ @Test void testContentTarget() { request.setContentTarget("https://target.com"); assertThat(request.getContentTarget()).isEqualTo("https://target.com"); } - /** - * Test of getCurrentHour method, of class PiwikRequest. - */ + /** Test of getCurrentHour method, of class PiwikRequest. */ @Test void testCurrentHour() { request.setCurrentHour(1); assertThat(request.getCurrentHour()).isEqualTo(Integer.valueOf(1)); } - /** - * Test of getCurrentMinute method, of class PiwikRequest. - */ + /** Test of getCurrentMinute method, of class PiwikRequest. */ @Test void testCurrentMinute() { request.setCurrentMinute(2); assertThat(request.getCurrentMinute()).isEqualTo(Integer.valueOf(2)); } - /** - * Test of getCurrentSecond method, of class PiwikRequest. - */ + /** Test of getCurrentSecond method, of class PiwikRequest. */ @Test void testCurrentSecond() { request.setCurrentSecond(3); assertThat(request.getCurrentSecond()).isEqualTo(Integer.valueOf(3)); } - /** - * Test of getCustomTrackingParameter method, of class PiwikRequest. - */ + /** Test of getCustomTrackingParameter method, of class PiwikRequest. */ @Test void testGetCustomTrackingParameter_T() { try { @@ -263,18 +235,14 @@ void testClearCustomTrackingParameter() { assertThat(l).isNull(); } - /** - * Test of getDeviceResolution method, of class PiwikRequest. - */ + /** Test of getDeviceResolution method, of class PiwikRequest. */ @Test void testDeviceResolution() { request.setDeviceResolution(DeviceResolution.fromString("100x200")); assertThat(request.getDeviceResolution()).hasToString("100x200"); } - /** - * Test of getDownloadUrl method, of class PiwikRequest. - */ + /** Test of getDownloadUrl method, of class PiwikRequest. */ @Test void testDownloadUrl() { @@ -282,18 +250,14 @@ void testDownloadUrl() { assertThat(request.getDownloadUrl()).isEqualTo("https://download.com"); } - /** - * Test of enableEcommerce method, of class PiwikRequest. - */ + /** Test of enableEcommerce method, of class PiwikRequest. */ @Test void testEnableEcommerce() { request.enableEcommerce(); assertThat(request.getGoalId()).isEqualTo(Integer.valueOf(0)); } - /** - * Test of getEcommerceDiscount method, of class PiwikRequest. - */ + /** Test of getEcommerceDiscount method, of class PiwikRequest. */ @Test void testEcommerceDiscountT() { request.enableEcommerce(); @@ -303,16 +267,13 @@ void testEcommerceDiscountT() { assertThat(request.getEcommerceDiscount()).isEqualTo(Double.valueOf(1.0)); } - @Test void testEcommerceDiscountF() { request.setEcommerceDiscount(null); assertThat(request.getEcommerceDiscount()).isNull(); } - /** - * Test of getEcommerceId method, of class PiwikRequest. - */ + /** Test of getEcommerceId method, of class PiwikRequest. */ @Test void testEcommerceIdT() { request.enableEcommerce(); @@ -352,9 +313,7 @@ void testEcommerceItem() { assertThat(request.getEcommerceItem(0)).isNull(); } - /** - * Test of getEcommerceLastOrderTimestamp method, of class PiwikRequest. - */ + /** Test of getEcommerceLastOrderTimestamp method, of class PiwikRequest. */ @Test void testEcommerceLastOrderTimestampT() { request.enableEcommerce(); @@ -370,9 +329,7 @@ void testEcommerceLastOrderTimestampF() { assertThat(request.getEcommerceLastOrderTimestamp()).isNull(); } - /** - * Test of getEcommerceRevenue method, of class PiwikRequest. - */ + /** Test of getEcommerceRevenue method, of class PiwikRequest. */ @Test void testEcommerceRevenueT() { request.enableEcommerce(); @@ -381,16 +338,13 @@ void testEcommerceRevenueT() { assertThat(request.getEcommerceRevenue()).isEqualTo(Double.valueOf(20.0)); } - @Test void testEcommerceRevenueF() { request.setEcommerceRevenue(null); assertThat(request.getEcommerceRevenue()).isNull(); } - /** - * Test of getEcommerceShippingCost method, of class PiwikRequest. - */ + /** Test of getEcommerceShippingCost method, of class PiwikRequest. */ @Test void testEcommerceShippingCostT() { request.enableEcommerce(); @@ -406,9 +360,7 @@ void testEcommerceShippingCostF() { assertThat(request.getEcommerceShippingCost()).isNull(); } - /** - * Test of getEcommerceSubtotal method, of class PiwikRequest. - */ + /** Test of getEcommerceSubtotal method, of class PiwikRequest. */ @Test void testEcommerceSubtotalT() { request.enableEcommerce(); @@ -424,9 +376,7 @@ void testEcommerceSubtotalF() { assertThat(request.getEcommerceSubtotal()).isNull(); } - /** - * Test of getEcommerceTax method, of class PiwikRequest. - */ + /** Test of getEcommerceTax method, of class PiwikRequest. */ @Test void testEcommerceTaxT() { request.enableEcommerce(); @@ -442,9 +392,7 @@ void testEcommerceTaxF() { assertThat(request.getEcommerceTax()).isNull(); } - /** - * Test of getEventAction method, of class PiwikRequest. - */ + /** Test of getEventAction method, of class PiwikRequest. */ @Test void testEventAction() { request.setEventAction("action"); @@ -453,63 +401,49 @@ void testEventAction() { assertThat(request.getEventAction()).isNull(); } - /** - * Test of getEventCategory method, of class PiwikRequest. - */ + /** Test of getEventCategory method, of class PiwikRequest. */ @Test void testEventCategory() { request.setEventCategory("category"); assertThat(request.getEventCategory()).isEqualTo("category"); } - /** - * Test of getEventName method, of class PiwikRequest. - */ + /** Test of getEventName method, of class PiwikRequest. */ @Test void testEventName() { request.setEventName("name"); assertThat(request.getEventName()).isEqualTo("name"); } - /** - * Test of getEventValue method, of class PiwikRequest. - */ + /** Test of getEventValue method, of class PiwikRequest. */ @Test void testEventValue() { request.setEventValue(1.0); assertThat(request.getEventValue()).isOne(); } - /** - * Test of getGoalId method, of class PiwikRequest. - */ + /** Test of getGoalId method, of class PiwikRequest. */ @Test void testGoalId() { request.setGoalId(1); assertThat(request.getGoalId()).isEqualTo(Integer.valueOf(1)); } - /** - * Test of getHeaderAcceptLanguage method, of class PiwikRequest. - */ + /** Test of getHeaderAcceptLanguage method, of class PiwikRequest. */ @Test void testHeaderAcceptLanguage() { request.setHeaderAcceptLanguage(AcceptLanguage.fromHeader("en")); assertThat(request.getHeaderAcceptLanguage()).hasToString("en"); } - /** - * Test of getHeaderUserAgent method, of class PiwikRequest. - */ + /** Test of getHeaderUserAgent method, of class PiwikRequest. */ @Test void testHeaderUserAgent() { request.setHeaderUserAgent("agent"); assertThat(request.getHeaderUserAgent()).isEqualTo("agent"); } - /** - * Test of getNewVisit method, of class PiwikRequest. - */ + /** Test of getNewVisit method, of class PiwikRequest. */ @Test void testNewVisit() { request.setNewVisit(true); @@ -518,18 +452,14 @@ void testNewVisit() { assertThat(request.getNewVisit()).isNull(); } - /** - * Test of getOutlinkUrl method, of class PiwikRequest. - */ + /** Test of getOutlinkUrl method, of class PiwikRequest. */ @Test void testOutlinkUrl() { request.setOutlinkUrl("https://outlink.com"); assertThat(request.getOutlinkUrl()).isEqualTo("https://outlink.com"); } - /** - * Test of getPageCustomVariable method, of class PiwikRequest. - */ + /** Test of getPageCustomVariable method, of class PiwikRequest. */ @Test void testPageCustomVariableStringStringE() { assertThatThrownBy(() -> request.setPageCustomVariable(null, null)); @@ -552,108 +482,84 @@ void testPageCustomVariableCustomVariable() { assertThat(request.getPageCustomVariable(2)).isEqualTo(cv); } - /** - * Test of getPluginDirector method, of class PiwikRequest. - */ + /** Test of getPluginDirector method, of class PiwikRequest. */ @Test void testPluginDirector() { request.setPluginDirector(true); assertThat(request.getPluginDirector()).isTrue(); } - /** - * Test of getPluginFlash method, of class PiwikRequest. - */ + /** Test of getPluginFlash method, of class PiwikRequest. */ @Test void testPluginFlash() { request.setPluginFlash(true); assertThat(request.getPluginFlash()).isTrue(); } - /** - * Test of getPluginGears method, of class PiwikRequest. - */ + /** Test of getPluginGears method, of class PiwikRequest. */ @Test void testPluginGears() { request.setPluginGears(true); assertThat(request.getPluginGears()).isTrue(); } - /** - * Test of getPluginJava method, of class PiwikRequest. - */ + /** Test of getPluginJava method, of class PiwikRequest. */ @Test void testPluginJava() { request.setPluginJava(true); assertThat(request.getPluginJava()).isTrue(); } - /** - * Test of getPluginPDF method, of class PiwikRequest. - */ + /** Test of getPluginPDF method, of class PiwikRequest. */ @Test void testPluginPDF() { request.setPluginPDF(true); assertThat(request.getPluginPDF()).isTrue(); } - /** - * Test of getPluginQuicktime method, of class PiwikRequest. - */ + /** Test of getPluginQuicktime method, of class PiwikRequest. */ @Test void testPluginQuicktime() { request.setPluginQuicktime(true); assertThat(request.getPluginQuicktime()).isTrue(); } - /** - * Test of getPluginRealPlayer method, of class PiwikRequest. - */ + /** Test of getPluginRealPlayer method, of class PiwikRequest. */ @Test void testPluginRealPlayer() { request.setPluginRealPlayer(true); assertThat(request.getPluginRealPlayer()).isTrue(); } - /** - * Test of getPluginSilverlight method, of class PiwikRequest. - */ + /** Test of getPluginSilverlight method, of class PiwikRequest. */ @Test void testPluginSilverlight() { request.setPluginSilverlight(true); assertThat(request.getPluginSilverlight()).isTrue(); } - /** - * Test of getPluginWindowsMedia method, of class PiwikRequest. - */ + /** Test of getPluginWindowsMedia method, of class PiwikRequest. */ @Test void testPluginWindowsMedia() { request.setPluginWindowsMedia(true); assertThat(request.getPluginWindowsMedia()).isTrue(); } - /** - * Test of getRandomValue method, of class PiwikRequest. - */ + /** Test of getRandomValue method, of class PiwikRequest. */ @Test void testRandomValue() { request.setRandomValue(RandomValue.fromString("value")); assertThat(request.getRandomValue()).hasToString("value"); } - /** - * Test of setReferrerUrl method, of class PiwikRequest. - */ + /** Test of setReferrerUrl method, of class PiwikRequest. */ @Test void testReferrerUrl() { request.setReferrerUrl("https://referrer.com"); assertThat(request.getReferrerUrl()).isEqualTo("https://referrer.com"); } - /** - * Test of getRequestDatetime method, of class PiwikRequest. - */ + /** Test of getRequestDatetime method, of class PiwikRequest. */ @Test void testRequestDatetimeTTT() { request.setAuthToken("12345678901234567890123456789012"); @@ -662,14 +568,11 @@ void testRequestDatetimeTTT() { assertThat(request.getRequestDatetime().getTime()).isEqualTo(1000L); } - @Test void testRequestDatetimeTF() { request.setRequestDatetime(new PiwikDate()); - assertThat(request.getRequestDatetime().getZonedDateTime()).isCloseTo( - ZonedDateTime.now(), - within(2, MINUTES) - ); + assertThat(request.getRequestDatetime().getZonedDateTime()) + .isCloseTo(ZonedDateTime.now(), within(2, MINUTES)); } @Test @@ -680,18 +583,14 @@ void testRequestDatetimeF() { assertThat(request.getRequestDatetime()).isNull(); } - /** - * Test of getRequired method, of class PiwikRequest. - */ + /** Test of getRequired method, of class PiwikRequest. */ @Test void testRequired() { request.setRequired(false); assertThat(request.getRequired()).isFalse(); } - /** - * Test of getResponseAsImage method, of class PiwikRequest. - */ + /** Test of getResponseAsImage method, of class PiwikRequest. */ @Test void testResponseAsImage() { request.setResponseAsImage(true); @@ -711,9 +610,7 @@ void testSearchCategoryF() { assertThat(request.getSearchCategory()).isNull(); } - /** - * Test of getSearchQuery method, of class PiwikRequest. - */ + /** Test of getSearchQuery method, of class PiwikRequest. */ @Test void testSearchQuery() { request.setSearchQuery("query"); @@ -733,46 +630,35 @@ void testSearchResultsCountF() { assertThat(request.getSearchResultsCount()).isNull(); } - /** - * Test of getSiteId method, of class PiwikRequest. - */ + /** Test of getSiteId method, of class PiwikRequest. */ @Test void testSiteId() { request.setSiteId(2); assertThat(request.getSiteId()).isEqualTo(Integer.valueOf(2)); } - /** - * Test of setTrackBotRequest method, of class PiwikRequest. - */ + /** Test of setTrackBotRequest method, of class PiwikRequest. */ @Test void testTrackBotRequests() { request.setTrackBotRequests(true); assertThat(request.getTrackBotRequests()).isTrue(); } - /** - * Test of getUserCustomVariable method, of class PiwikRequest. - */ + /** Test of getUserCustomVariable method, of class PiwikRequest. */ @Test void testUserCustomVariableStringString() { request.setUserCustomVariable("userKey", "userValue"); assertThat(request.getUserCustomVariable("userKey")).isEqualTo("userValue"); } - - /** - * Test of getUserId method, of class PiwikRequest. - */ + /** Test of getUserId method, of class PiwikRequest. */ @Test void testUserId() { request.setUserId("id"); assertThat(request.getUserId()).isEqualTo("id"); } - /** - * Test of getVisitorCity method, of class PiwikRequest. - */ + /** Test of getVisitorCity method, of class PiwikRequest. */ @Test void testVisitorCityT() { request.setAuthToken("12345678901234567890123456789012"); @@ -786,9 +672,7 @@ void testVisitorCityF() { assertThat(request.getVisitorCity()).isNull(); } - /** - * Test of getVisitorCountry method, of class PiwikRequest. - */ + /** Test of getVisitorCountry method, of class PiwikRequest. */ @Test void testVisitorCountryT() { PiwikLocale country = new PiwikLocale(Locale.US); @@ -816,9 +700,7 @@ void testVisitorCustomIdF() { assertThat(request.getVisitorCustomId()).isNull(); } - /** - * Test of getVisitorFirstVisitTimestamp method, of class PiwikRequest. - */ + /** Test of getVisitorFirstVisitTimestamp method, of class PiwikRequest. */ @Test void testVisitorFirstVisitTimestamp() { request.setVisitorFirstVisitTimestamp(Instant.parse("2021-03-10T10:22:22.123Z")); @@ -848,9 +730,7 @@ void testVisitorIdF() { assertThat(request.getVisitorId()).isNull(); } - /** - * Test of getVisitorIp method, of class PiwikRequest. - */ + /** Test of getVisitorIp method, of class PiwikRequest. */ @Test void testVisitorIpT() { request.setAuthToken("12345678901234567890123456789012"); @@ -864,9 +744,7 @@ void testVisitorIpF() { assertThat(request.getVisitorIp()).isNull(); } - /** - * Test of getVisitorLatitude method, of class PiwikRequest. - */ + /** Test of getVisitorLatitude method, of class PiwikRequest. */ @Test void testVisitorLatitudeT() { request.setAuthToken("12345678901234567890123456789012"); @@ -880,9 +758,7 @@ void testVisitorLatitudeF() { assertThat(request.getVisitorLatitude()).isNull(); } - /** - * Test of getVisitorLongitude method, of class PiwikRequest. - */ + /** Test of getVisitorLongitude method, of class PiwikRequest. */ @Test void testVisitorLongitudeT() { request.setAuthToken("12345678901234567890123456789012"); @@ -896,18 +772,14 @@ void testVisitorLongitudeF() { assertThat(request.getVisitorLongitude()).isNull(); } - /** - * Test of getVisitorPreviousVisitTimestamp method, of class PiwikRequest. - */ + /** Test of getVisitorPreviousVisitTimestamp method, of class PiwikRequest. */ @Test void testVisitorPreviousVisitTimestamp() { request.setVisitorPreviousVisitTimestamp(Instant.ofEpochSecond(1000L)); assertThat(request.getVisitorPreviousVisitTimestamp()).isEqualTo("1970-01-01T00:16:40Z"); } - /** - * Test of getVisitorRegion method, of class PiwikRequest. - */ + /** Test of getVisitorRegion method, of class PiwikRequest. */ @Test void testVisitorRegionT() { request.setAuthToken("12345678901234567890123456789012"); @@ -921,9 +793,7 @@ void testVisitorRegionF() { assertThat(request.getVisitorRegion()).isNull(); } - /** - * Test of getVisitorVisitCount method, of class PiwikRequest. - */ + /** Test of getVisitorVisitCount method, of class PiwikRequest. */ @Test void testVisitorVisitCount() { request.setVisitorVisitCount(100); @@ -936,5 +806,4 @@ void failsIfActionUrlIsNull() { .isInstanceOf(NullPointerException.class) .hasMessage("Action URL must not be null"); } - } diff --git a/core/src/test/java/org/matomo/java/tracking/ProxyAuthenticatorTest.java b/core/src/test/java/org/matomo/java/tracking/ProxyAuthenticatorTest.java index 08893677..9107828d 100644 --- a/core/src/test/java/org/matomo/java/tracking/ProxyAuthenticatorTest.java +++ b/core/src/test/java/org/matomo/java/tracking/ProxyAuthenticatorTest.java @@ -21,29 +21,21 @@ void createsPasswordAuthentication() throws Exception { givenPasswordAuthentication(RequestorType.PROXY); assertThat(passwordAuthentication.getUserName()).isEqualTo("user"); - assertThat(passwordAuthentication.getPassword()).contains( - 'p', - 'a', - 's', - 's', - 'w', - 'o', - 'r', - 'd' - ); - + assertThat(passwordAuthentication.getPassword()) + .contains('p', 'a', 's', 's', 'w', 'o', 'r', 'd'); } private void givenPasswordAuthentication(RequestorType proxy) throws Exception { - passwordAuthentication = Authenticator.requestPasswordAuthentication("host", - InetAddress.getLocalHost(), - 8080, - "http", - "prompt", - "https", - new URL("https://www.daniel-heid.de"), - proxy - ); + passwordAuthentication = + Authenticator.requestPasswordAuthentication( + "host", + InetAddress.getLocalHost(), + 8080, + "http", + "prompt", + "https", + new URL("https://www.daniel-heid.de"), + proxy); } @Test @@ -54,8 +46,5 @@ void returnsNullIfNoPasswordAuthentication() throws Exception { givenPasswordAuthentication(RequestorType.SERVER); assertThat(passwordAuthentication).isNull(); - } - - } diff --git a/core/src/test/java/org/matomo/java/tracking/QueryCreatorTest.java b/core/src/test/java/org/matomo/java/tracking/QueryCreatorTest.java index a4e87e5b..6201562c 100644 --- a/core/src/test/java/org/matomo/java/tracking/QueryCreatorTest.java +++ b/core/src/test/java/org/matomo/java/tracking/QueryCreatorTest.java @@ -27,10 +27,10 @@ class QueryCreatorTest { - private final MatomoRequest.MatomoRequestBuilder matomoRequestBuilder = MatomoRequest - .request() - .visitorId(VisitorId.fromHash(1234567890123456789L)) - .randomValue(RandomValue.fromString("random-value")); + private final MatomoRequest.MatomoRequestBuilder matomoRequestBuilder = + MatomoRequest.request() + .visitorId(VisitorId.fromHash(1234567890123456789L)) + .randomValue(RandomValue.fromString("random-value")); private String defaultAuthToken = "876de1876fb2cda2816c362a61bfc712"; @@ -43,19 +43,19 @@ void usesDefaultSiteId() { whenCreatesQuery(); - assertThat(query).isEqualTo( - "idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&apiv=1&_id=112210f47de98115&send_image=0&rand=random-value"); - + assertThat(query) + .isEqualTo( + "idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&apiv=1&_id=112210f47de98115&send_image=0&rand=random-value"); } private void whenCreatesQuery() { request = matomoRequestBuilder.build(); - TrackerConfiguration trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create("http://localhost")) - .defaultSiteId(42) - .defaultAuthToken(defaultAuthToken) - .build(); + TrackerConfiguration trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create("http://localhost")) + .defaultSiteId(42) + .defaultAuthToken(defaultAuthToken) + .build(); String authToken = AuthToken.determineAuthToken(null, singleton(request), trackerConfiguration); query = new QueryCreator(trackerConfiguration).createQuery(request, authToken); } @@ -67,9 +67,9 @@ void overridesDefaultSiteId() { whenCreatesQuery(); - assertThat(query).isEqualTo( - "token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&idsite=123&apiv=1&_id=112210f47de98115&send_image=0&rand=random-value"); - + assertThat(query) + .isEqualTo( + "token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&idsite=123&apiv=1&_id=112210f47de98115&send_image=0&rand=random-value"); } @Test @@ -79,9 +79,9 @@ void usesDefaultTokenAuth() { whenCreatesQuery(); - assertThat(query).isEqualTo( - "idsite=42&token_auth=f123bfc9a46de0bb5453afdab6f93200&rec=1&apiv=1&_id=112210f47de98115&send_image=0&rand=random-value"); - + assertThat(query) + .isEqualTo( + "idsite=42&token_auth=f123bfc9a46de0bb5453afdab6f93200&rec=1&apiv=1&_id=112210f47de98115&send_image=0&rand=random-value"); } @Test @@ -92,9 +92,9 @@ void overridesDefaultTokenAuth() { whenCreatesQuery(); - assertThat(query).isEqualTo( - "idsite=42&token_auth=e456bfc9a46de0bb5453afdab6f93200&rec=1&apiv=1&_id=112210f47de98115&token_auth=e456bfc9a46de0bb5453afdab6f93200&send_image=0&rand=random-value"); - + assertThat(query) + .isEqualTo( + "idsite=42&token_auth=e456bfc9a46de0bb5453afdab6f93200&rec=1&apiv=1&_id=112210f47de98115&token_auth=e456bfc9a46de0bb5453afdab6f93200&send_image=0&rand=random-value"); } @Test @@ -105,7 +105,6 @@ void validatesTokenAuth() { assertThatThrownBy(this::whenCreatesQuery) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Auth token must be exactly 32 characters long"); - } @Test @@ -115,9 +114,9 @@ void convertsTrueBooleanTo1() { whenCreatesQuery(); - assertThat(query).isEqualTo( - "idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&apiv=1&_id=112210f47de98115&fla=1&send_image=0&rand=random-value"); - + assertThat(query) + .isEqualTo( + "idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&apiv=1&_id=112210f47de98115&fla=1&send_image=0&rand=random-value"); } @Test @@ -127,9 +126,9 @@ void convertsFalseBooleanTo0() { whenCreatesQuery(); - assertThat(query).isEqualTo( - "idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&apiv=1&_id=112210f47de98115&java=0&send_image=0&rand=random-value"); - + assertThat(query) + .isEqualTo( + "idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&apiv=1&_id=112210f47de98115&java=0&send_image=0&rand=random-value"); } @Test @@ -139,9 +138,9 @@ void encodesUrl() { whenCreatesQuery(); - assertThat(query).isEqualTo( - "idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&url=https%3A%2F%2Fwww.daniel-heid.de%2Fsome%2Fpage%3Ffoo%3Dbar&apiv=1&_id=112210f47de98115&send_image=0&rand=random-value"); - + assertThat(query) + .isEqualTo( + "idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&url=https%3A%2F%2Fwww.daniel-heid.de%2Fsome%2Fpage%3Ffoo%3Dbar&apiv=1&_id=112210f47de98115&send_image=0&rand=random-value"); } @Test @@ -151,9 +150,9 @@ void encodesReferrerUrl() { whenCreatesQuery(); - assertThat(query).isEqualTo( - "idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&apiv=1&_id=112210f47de98115&urlref=https%3A%2F%2Fwww.daniel-heid.de%2Fsome%2Freferrer%3Ffoo2%3Dbar2&send_image=0&rand=random-value"); - + assertThat(query) + .isEqualTo( + "idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&apiv=1&_id=112210f47de98115&urlref=https%3A%2F%2Fwww.daniel-heid.de%2Fsome%2Freferrer%3Ffoo2%3Dbar2&send_image=0&rand=random-value"); } @Test @@ -163,9 +162,9 @@ void encodesLink() { whenCreatesQuery(); - assertThat(query).isEqualTo( - "idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&apiv=1&_id=112210f47de98115&link=https%3A%2F%2Fwww.daniel-heid.de%2Fsome%2Fexternal%2Flink%23&send_image=0&rand=random-value"); - + assertThat(query) + .isEqualTo( + "idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&apiv=1&_id=112210f47de98115&link=https%3A%2F%2Fwww.daniel-heid.de%2Fsome%2Fexternal%2Flink%23&send_image=0&rand=random-value"); } @Test @@ -175,9 +174,9 @@ void encodesDownloadUrl() { whenCreatesQuery(); - assertThat(query).isEqualTo( - "idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&apiv=1&_id=112210f47de98115&download=https%3A%2F%2Fwww.daniel-heid.de%2Fsome%2Fdownload.pdf&send_image=0&rand=random-value"); - + assertThat(query) + .isEqualTo( + "idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&apiv=1&_id=112210f47de98115&download=https%3A%2F%2Fwww.daniel-heid.de%2Fsome%2Fdownload.pdf&send_image=0&rand=random-value"); } @Test @@ -188,40 +187,42 @@ void tracksMinimalRequest() { .actionUrl("https://www.daniel-heid.de/portfolio") .visitorId(VisitorId.fromHash(3434343434343434343L)) .referrerUrl("https://www.daniel-heid.de/referrer") - .visitCustomVariables(new CustomVariables() - .add(new CustomVariable("customVariable1Key", "customVariable1Value"), 5) - .add(new CustomVariable("customVariable2Key", "customVariable2Value"), 6)) + .visitCustomVariables( + new CustomVariables() + .add(new CustomVariable("customVariable1Key", "customVariable1Value"), 5) + .add(new CustomVariable("customVariable2Key", "customVariable2Value"), 6)) .visitorVisitCount(2) .visitorPreviousVisitTimestamp(Instant.parse("2022-08-09T18:34:12Z")) .deviceResolution(DeviceResolution.builder().width(1024).height(768).build()) - .headerAcceptLanguage(AcceptLanguage - .builder() - .languageRange(new LanguageRange("de")) - .languageRange(new LanguageRange("de-DE", 0.9)) - .languageRange(new LanguageRange("en", 0.8)) - .build()) + .headerAcceptLanguage( + AcceptLanguage.builder() + .languageRange(new LanguageRange("de")) + .languageRange(new LanguageRange("de-DE", 0.9)) + .languageRange(new LanguageRange("en", 0.8)) + .build()) .pageViewId(UniqueId.fromValue(999999999999999999L)) .goalId(0) .ecommerceRevenue(12.34) - .ecommerceItems(EcommerceItems - .builder() - .item(EcommerceItem.builder().sku("SKU").build()) - .item(EcommerceItem - .builder() - .sku("SKU") - .name("NAME") - .category("CATEGORY") - .price(123.4) + .ecommerceItems( + EcommerceItems.builder() + .item(EcommerceItem.builder().sku("SKU").build()) + .item( + EcommerceItem.builder() + .sku("SKU") + .name("NAME") + .category("CATEGORY") + .price(123.4) + .build()) .build()) - .build()) .authToken("fdf6e8461ea9de33176b222519627f78") - .visitorCountry(Country.fromLanguageRanges("en-GB;q=0.7,de,de-DE;q=0.9,en;q=0.8,en-US;q=0.6")); + .visitorCountry( + Country.fromLanguageRanges("en-GB;q=0.7,de,de-DE;q=0.9,en;q=0.8,en-US;q=0.6")); whenCreatesQuery(); - assertThat(query).isEqualTo( - "idsite=42&token_auth=fdf6e8461ea9de33176b222519627f78&rec=1&action_name=Help+%2F+Feedback&url=https%3A%2F%2Fwww.daniel-heid.de%2Fportfolio&apiv=1&_id=2fa93d2858bc4867&urlref=https%3A%2F%2Fwww.daniel-heid.de%2Freferrer&_cvar=%7B%225%22%3A%5B%22customVariable1Key%22%2C%22customVariable1Value%22%5D%2C%226%22%3A%5B%22customVariable2Key%22%2C%22customVariable2Value%22%5D%7D&_idvc=2&_viewts=1660070052&res=1024x768&lang=de%2Cde-de%3Bq%3D0.9%2Cen%3Bq%3D0.8&pv_id=lbBbxG&idgoal=0&revenue=12.34&ec_items=%5B%5B%22SKU%22%2C%22%22%2C%22%22%2C0.0%2C0%5D%2C%5B%22SKU%22%2C%22NAME%22%2C%22CATEGORY%22%2C123.4%2C0%5D%5D&token_auth=fdf6e8461ea9de33176b222519627f78&country=de&send_image=0&rand=random-value"); - + assertThat(query) + .isEqualTo( + "idsite=42&token_auth=fdf6e8461ea9de33176b222519627f78&rec=1&action_name=Help+%2F+Feedback&url=https%3A%2F%2Fwww.daniel-heid.de%2Fportfolio&apiv=1&_id=2fa93d2858bc4867&urlref=https%3A%2F%2Fwww.daniel-heid.de%2Freferrer&_cvar=%7B%225%22%3A%5B%22customVariable1Key%22%2C%22customVariable1Value%22%5D%2C%226%22%3A%5B%22customVariable2Key%22%2C%22customVariable2Value%22%5D%7D&_idvc=2&_viewts=1660070052&res=1024x768&lang=de%2Cde-de%3Bq%3D0.9%2Cen%3Bq%3D0.8&pv_id=lbBbxG&idgoal=0&revenue=12.34&ec_items=%5B%5B%22SKU%22%2C%22%22%2C%22%22%2C0.0%2C0%5D%2C%5B%22SKU%22%2C%22NAME%22%2C%22CATEGORY%22%2C123.4%2C0%5D%5D&token_auth=fdf6e8461ea9de33176b222519627f78&country=de&send_image=0&rand=random-value"); } @Test @@ -233,34 +234,38 @@ void testGetQueryString() { .visitorId(VisitorId.fromHex("1234567890123456")); defaultAuthToken = null; whenCreatesQuery(); - assertThat(query).isEqualTo( - "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&send_image=0&rand=random"); - matomoRequestBuilder.pageCustomVariables(new CustomVariables().add(new CustomVariable( - "key", - "val" - ), 7)); + assertThat(query) + .isEqualTo( + "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&send_image=0&rand=random"); + matomoRequestBuilder.pageCustomVariables( + new CustomVariables().add(new CustomVariable("key", "val"), 7)); whenCreatesQuery(); - assertThat(query).isEqualTo( - "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&cvar=%7B%227%22%3A%5B%22key%22%2C%22val%22%5D%7D&send_image=0&rand=random"); + assertThat(query) + .isEqualTo( + "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&cvar=%7B%227%22%3A%5B%22key%22%2C%22val%22%5D%7D&send_image=0&rand=random"); matomoRequestBuilder.additionalParameters(singletonMap("key", singleton("test"))); whenCreatesQuery(); - assertThat(query).isEqualTo( - "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&cvar=%7B%227%22%3A%5B%22key%22%2C%22val%22%5D%7D&send_image=0&rand=random&key=%5Btest%5D"); + assertThat(query) + .isEqualTo( + "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&cvar=%7B%227%22%3A%5B%22key%22%2C%22val%22%5D%7D&send_image=0&rand=random&key=%5Btest%5D"); matomoRequestBuilder.additionalParameters(singletonMap("key", asList("test", "test2"))); whenCreatesQuery(); - assertThat(query).isEqualTo( - "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&cvar=%7B%227%22%3A%5B%22key%22%2C%22val%22%5D%7D&send_image=0&rand=random&key=%5Btest%2C+test2%5D"); + assertThat(query) + .isEqualTo( + "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&cvar=%7B%227%22%3A%5B%22key%22%2C%22val%22%5D%7D&send_image=0&rand=random&key=%5Btest%2C+test2%5D"); Map customTrackingParameters = new HashMap<>(); customTrackingParameters.put("key", "test2"); customTrackingParameters.put("key2", "test3"); matomoRequestBuilder.additionalParameters(customTrackingParameters); whenCreatesQuery(); - assertThat(query).isEqualTo( - "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&cvar=%7B%227%22%3A%5B%22key%22%2C%22val%22%5D%7D&send_image=0&rand=random&key2=test3&key=test2"); + assertThat(query) + .isEqualTo( + "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&cvar=%7B%227%22%3A%5B%22key%22%2C%22val%22%5D%7D&send_image=0&rand=random&key2=test3&key=test2"); customTrackingParameters.put("key", "test4"); whenCreatesQuery(); - assertThat(query).isEqualTo( - "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&cvar=%7B%227%22%3A%5B%22key%22%2C%22val%22%5D%7D&send_image=0&rand=random&key2=test3&key=test4"); + assertThat(query) + .isEqualTo( + "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&cvar=%7B%227%22%3A%5B%22key%22%2C%22val%22%5D%7D&send_image=0&rand=random&key2=test3&key=test4"); matomoRequestBuilder.randomValue(null); matomoRequestBuilder.siteId(null); matomoRequestBuilder.required(null); @@ -269,8 +274,9 @@ void testGetQueryString() { matomoRequestBuilder.visitorId(null); matomoRequestBuilder.actionUrl(null); whenCreatesQuery(); - assertThat(query).isEqualTo( - "idsite=42&cvar=%7B%227%22%3A%5B%22key%22%2C%22val%22%5D%7D&key2=test3&key=test4"); + assertThat(query) + .isEqualTo( + "idsite=42&cvar=%7B%227%22%3A%5B%22key%22%2C%22val%22%5D%7D&key2=test3&key=test4"); } @Test @@ -284,8 +290,9 @@ void testGetQueryString2() { whenCreatesQuery(); - assertThat(query).isEqualTo( - "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&send_image=0&rand=random"); + assertThat(query) + .isEqualTo( + "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&send_image=0&rand=random"); } @Test @@ -297,26 +304,31 @@ void testGetUrlEncodedQueryString() { .visitorId(VisitorId.fromHex("1234567890123456")) .siteId(3); whenCreatesQuery(); - assertThat(query).isEqualTo( - "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&send_image=0&rand=random"); + assertThat(query) + .isEqualTo( + "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&send_image=0&rand=random"); Map customTrackingParameters = new HashMap<>(); customTrackingParameters.put("ke/y", "te:st"); matomoRequestBuilder.additionalParameters(customTrackingParameters); whenCreatesQuery(); - assertThat(query).isEqualTo( - "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&send_image=0&rand=random&ke%2Fy=te%3Ast"); + assertThat(query) + .isEqualTo( + "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&send_image=0&rand=random&ke%2Fy=te%3Ast"); customTrackingParameters.put("ke/y", "te:st2"); whenCreatesQuery(); - assertThat(query).isEqualTo( - "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&send_image=0&rand=random&ke%2Fy=te%3Ast2"); + assertThat(query) + .isEqualTo( + "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&send_image=0&rand=random&ke%2Fy=te%3Ast2"); customTrackingParameters.put("ke/y2", "te:st3"); whenCreatesQuery(); - assertThat(query).isEqualTo( - "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&send_image=0&rand=random&ke%2Fy=te%3Ast2&ke%2Fy2=te%3Ast3"); + assertThat(query) + .isEqualTo( + "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&send_image=0&rand=random&ke%2Fy=te%3Ast2&ke%2Fy2=te%3Ast3"); customTrackingParameters.put("ke/y", "te:st3"); whenCreatesQuery(); - assertThat(query).isEqualTo( - "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&send_image=0&rand=random&ke%2Fy=te%3Ast3&ke%2Fy2=te%3Ast3"); + assertThat(query) + .isEqualTo( + "rec=1&idsite=3&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&send_image=0&rand=random&ke%2Fy=te%3Ast3&ke%2Fy2=te%3Ast3"); matomoRequestBuilder .randomValue(null) .siteId(null) @@ -327,7 +339,6 @@ void testGetUrlEncodedQueryString() { .actionUrl(null); whenCreatesQuery(); assertThat(query).isEqualTo("idsite=42&ke%2Fy=te%3Ast3&ke%2Fy2=te%3Ast3"); - } @Test @@ -340,9 +351,9 @@ void testGetUrlEncodedQueryString2() { whenCreatesQuery(); - assertThat(query).isEqualTo( - "idsite=42&rec=1&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&send_image=0&rand=random"); - + assertThat(query) + .isEqualTo( + "idsite=42&rec=1&url=http%3A%2F%2Ftest.com&apiv=1&_id=1234567890123456&send_image=0&rand=random"); } @Test @@ -359,8 +370,9 @@ void testVisitCustomVariableCustomVariable() { whenCreatesQuery(); assertThat(request.getVisitCustomVariable(1)).isNull(); - assertThat(query).isEqualTo( - "rec=1&idsite=3&apiv=1&_id=1234567890123456&_cvar=%7B%228%22%3A%5B%22visitKey%22%2C%22visitVal%22%5D%7D&send_image=0&rand=random"); + assertThat(query) + .isEqualTo( + "rec=1&idsite=3&apiv=1&_id=1234567890123456&_cvar=%7B%228%22%3A%5B%22visitKey%22%2C%22visitVal%22%5D%7D&send_image=0&rand=random"); } @Test @@ -370,9 +382,9 @@ void doesNotAppendEmptyString() { whenCreatesQuery(); - assertThat(query).isEqualTo( - "idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&apiv=1&_id=112210f47de98115&e_a=&send_image=0&rand=random-value"); - + assertThat(query) + .isEqualTo( + "idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&apiv=1&_id=112210f47de98115&e_a=&send_image=0&rand=random-value"); } @Test @@ -394,8 +406,9 @@ void createsQueryWithDimensions() { whenCreatesQuery(); - assertThat(query).isEqualTo( - "idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&apiv=1&_id=112210f47de98115&send_image=0&rand=random-value&dimension1=firstDimension&dimension3=thirdDimension"); + assertThat(query) + .isEqualTo( + "idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&apiv=1&_id=112210f47de98115&send_image=0&rand=random-value&dimension1=firstDimension&dimension3=thirdDimension"); } @Test @@ -404,8 +417,9 @@ void appendsCharsetParameters() { whenCreatesQuery(); - assertThat(query).isEqualTo( - "idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&apiv=1&_id=112210f47de98115&cs=ISO-8859-1&send_image=0&rand=random-value"); + assertThat(query) + .isEqualTo( + "idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&apiv=1&_id=112210f47de98115&cs=ISO-8859-1&send_image=0&rand=random-value"); } @Test @@ -540,38 +554,42 @@ void failsIfLongitudeIsGreaterThan180() { @Test void tracksEvent() { - matomoRequestBuilder.eventName("Event Name") - .eventValue(23.456) - .eventAction("Event Action") - .eventCategory("Event Category"); + matomoRequestBuilder + .eventName("Event Name") + .eventValue(23.456) + .eventAction("Event Action") + .eventCategory("Event Category"); whenCreatesQuery(); - assertThat(query).isEqualTo("idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&apiv=1&_id=112210f47de98115&e_c=Event+Category&e_a=Event+Action&e_n=Event+Name&e_v=23.456&send_image=0&rand=random-value"); + assertThat(query) + .isEqualTo( + "idsite=42&token_auth=876de1876fb2cda2816c362a61bfc712&rec=1&apiv=1&_id=112210f47de98115&e_c=Event+Category&e_a=Event+Action&e_n=Event+Name&e_v=23.456&send_image=0&rand=random-value"); } @Test void allowsZeroForEventValue() { - matomoRequestBuilder.eventName("Event Name") - .eventValue(0.0) - .eventAction("Event Action") - .eventCategory("Event Category"); + matomoRequestBuilder + .eventName("Event Name") + .eventValue(0.0) + .eventAction("Event Action") + .eventCategory("Event Category"); whenCreatesQuery(); assertThat(query) - .isEqualTo("idsite=42&" + - "token_auth=876de1876fb2cda2816c362a61bfc712&" + - "rec=1&" + - "apiv=1&" + - "_id=112210f47de98115&" + - "e_c=Event+Category&" + - "e_a=Event+Action&" + - "e_n=Event+Name&" + - "e_v=0.0&" + - "send_image=0&" + - "rand=random-value" - ); + .isEqualTo( + "idsite=42&" + + "token_auth=876de1876fb2cda2816c362a61bfc712&" + + "rec=1&" + + "apiv=1&" + + "_id=112210f47de98115&" + + "e_c=Event+Category&" + + "e_a=Event+Action&" + + "e_n=Event+Name&" + + "e_v=0.0&" + + "send_image=0&" + + "rand=random-value"); } @Test @@ -586,19 +604,18 @@ void allowsZeroForEcommerceValues() { whenCreatesQuery(); assertThat(query) - .isEqualTo("idsite=42&" + - "token_auth=876de1876fb2cda2816c362a61bfc712&" + - "rec=1&" + - "apiv=1&" + - "_id=112210f47de98115&" + - "revenue=0.0&" + - "ec_st=0.0&" + - "ec_tx=0.0&" + - "ec_sh=0.0&" + - "ec_dt=0.0&" + - "send_image=0&" + - "rand=random-value" - ); - } - -} \ No newline at end of file + .isEqualTo( + "idsite=42&" + + "token_auth=876de1876fb2cda2816c362a61bfc712&" + + "rec=1&" + + "apiv=1&" + + "_id=112210f47de98115&" + + "revenue=0.0&" + + "ec_st=0.0&" + + "ec_tx=0.0&" + + "ec_sh=0.0&" + + "ec_dt=0.0&" + + "send_image=0&" + + "rand=random-value"); + } +} diff --git a/core/src/test/java/org/matomo/java/tracking/RequestValidatorTest.java b/core/src/test/java/org/matomo/java/tracking/RequestValidatorTest.java index 6d1ab348..d223f688 100644 --- a/core/src/test/java/org/matomo/java/tracking/RequestValidatorTest.java +++ b/core/src/test/java/org/matomo/java/tracking/RequestValidatorTest.java @@ -11,7 +11,6 @@ class RequestValidatorTest { private final MatomoRequest request = new MatomoRequest(); - @Test void testSearchResultsCount() { @@ -20,7 +19,6 @@ void testSearchResultsCount() { assertThatThrownBy(() -> RequestValidator.validate(request, null)) .isInstanceOf(MatomoException.class) .hasMessage("Search query must be set if search results count is set"); - } @Test @@ -30,7 +28,8 @@ void testVisitorLongitude() { assertThatThrownBy(() -> RequestValidator.validate(request, null)) .isInstanceOf(MatomoException.class) .hasMessage( - "Auth token must be present if visitor longitude, latitude, region, city, country or IP are set"); + "Auth token must be present if visitor longitude, latitude, region, city, country or IP" + + " are set"); } @Test @@ -40,7 +39,8 @@ void testVisitorLatitude() { assertThatThrownBy(() -> RequestValidator.validate(request, null)) .isInstanceOf(MatomoException.class) .hasMessage( - "Auth token must be present if visitor longitude, latitude, region, city, country or IP are set"); + "Auth token must be present if visitor longitude, latitude, region, city, country or IP" + + " are set"); } @Test @@ -50,7 +50,8 @@ void testVisitorCity() { assertThatThrownBy(() -> RequestValidator.validate(request, null)) .isInstanceOf(MatomoException.class) .hasMessage( - "Auth token must be present if visitor longitude, latitude, region, city, country or IP are set"); + "Auth token must be present if visitor longitude, latitude, region, city, country or IP" + + " are set"); } @Test @@ -60,7 +61,8 @@ void testVisitorRegion() { assertThatThrownBy(() -> RequestValidator.validate(request, null)) .isInstanceOf(MatomoException.class) .hasMessage( - "Auth token must be present if visitor longitude, latitude, region, city, country or IP are set"); + "Auth token must be present if visitor longitude, latitude, region, city, country or IP" + + " are set"); } @Test @@ -68,11 +70,11 @@ void testVisitorCountryTE() { PiwikLocale country = new PiwikLocale(Locale.US); request.setVisitorCountry(country); - assertThatThrownBy(() -> RequestValidator.validate(request, null)) .isInstanceOf(MatomoException.class) .hasMessage( - "Auth token must be present if visitor longitude, latitude, region, city, country or IP are set"); + "Auth token must be present if visitor longitude, latitude, region, city, country or IP" + + " are set"); } @Test @@ -84,7 +86,6 @@ void testRequestDatetime() { assertThatThrownBy(() -> RequestValidator.validate(request, null)) .isInstanceOf(MatomoException.class) .hasMessage("Auth token must be present if request timestamp is more than four hours ago"); - } @Test @@ -93,5 +94,4 @@ void failsIfAuthTokenIsNot32CharactersLong() { .isInstanceOf(IllegalArgumentException.class) .hasMessage("Auth token must be exactly 32 characters long"); } - } diff --git a/core/src/test/java/org/matomo/java/tracking/ServiceLoaderSenderFactoryTest.java b/core/src/test/java/org/matomo/java/tracking/ServiceLoaderSenderFactoryTest.java index 0a5d2253..50d24def 100644 --- a/core/src/test/java/org/matomo/java/tracking/ServiceLoaderSenderFactoryTest.java +++ b/core/src/test/java/org/matomo/java/tracking/ServiceLoaderSenderFactoryTest.java @@ -12,13 +12,15 @@ void failsIfNoImplementationFound() { ServiceLoaderSenderFactory serviceLoaderSenderFactory = new ServiceLoaderSenderFactory(); TrackerConfiguration trackerConfiguration = - TrackerConfiguration.builder().apiEndpoint(URI.create("http://localhost/matomo.php")).build(); + TrackerConfiguration.builder() + .apiEndpoint(URI.create("http://localhost/matomo.php")) + .build(); - assertThatThrownBy(() -> serviceLoaderSenderFactory.createSender(trackerConfiguration, - new QueryCreator(trackerConfiguration) - )) + assertThatThrownBy( + () -> + serviceLoaderSenderFactory.createSender( + trackerConfiguration, new QueryCreator(trackerConfiguration))) .isInstanceOf(MatomoException.class) .hasMessage("No SenderProvider found"); } - -} \ No newline at end of file +} diff --git a/core/src/test/java/org/matomo/java/tracking/TestSender.java b/core/src/test/java/org/matomo/java/tracking/TestSender.java index f000bc8d..30f0395c 100644 --- a/core/src/test/java/org/matomo/java/tracking/TestSender.java +++ b/core/src/test/java/org/matomo/java/tracking/TestSender.java @@ -13,9 +13,9 @@ /** * A {@link Sender} implementation that does not send anything but stores the requests and queries. * - *

This class is intended for testing purposes only. It does not send anything to the Matomo server. Instead, it - * stores the requests and queries in collections that can be accessed via {@link #getRequests()} and {@link - * #getQueries()}. + *

This class is intended for testing purposes only. It does not send anything to the Matomo + * server. Instead, it stores the requests and queries in collections that can be accessed via + * {@link #getRequests()} and {@link #getQueries()}. */ @RequiredArgsConstructor @Getter @@ -43,8 +43,7 @@ public void sendSingle(@NonNull MatomoRequest request) { @Override public void sendBulk( - @NonNull Iterable requests, @Nullable String overrideAuthToken - ) { + @NonNull Iterable requests, @Nullable String overrideAuthToken) { for (MatomoRequest request : requests) { createQueryAndAddRequest(request, overrideAuthToken); } @@ -53,18 +52,17 @@ public void sendBulk( @NonNull @Override public CompletableFuture sendBulkAsync( - @NonNull Collection requests, @Nullable String overrideAuthToken - ) { + @NonNull Collection requests, @Nullable String overrideAuthToken) { for (MatomoRequest request : requests) { createQueryAndAddRequest(request, overrideAuthToken); } return CompletableFuture.completedFuture(null); } - - - private void createQueryAndAddRequest(@lombok.NonNull MatomoRequest request, @Nullable String overrideAuthToken) { - String authToken = AuthToken.determineAuthToken(overrideAuthToken, singleton(request), trackerConfiguration); + private void createQueryAndAddRequest( + @lombok.NonNull MatomoRequest request, @Nullable String overrideAuthToken) { + String authToken = + AuthToken.determineAuthToken(overrideAuthToken, singleton(request), trackerConfiguration); queries.add(queryCreator.createQuery(request, authToken)); requests.add(request); } diff --git a/core/src/test/java/org/matomo/java/tracking/TestSenderFactory.java b/core/src/test/java/org/matomo/java/tracking/TestSenderFactory.java index fafafa90..4ddb321f 100644 --- a/core/src/test/java/org/matomo/java/tracking/TestSenderFactory.java +++ b/core/src/test/java/org/matomo/java/tracking/TestSenderFactory.java @@ -4,8 +4,7 @@ class TestSenderFactory implements SenderFactory { - @Getter - private TestSender testSender; + @Getter private TestSender testSender; @Override public Sender createSender(TrackerConfiguration trackerConfiguration, QueryCreator queryCreator) { diff --git a/core/src/test/java/org/matomo/java/tracking/TestThrowable.java b/core/src/test/java/org/matomo/java/tracking/TestThrowable.java index daf4a69a..48b37ca4 100644 --- a/core/src/test/java/org/matomo/java/tracking/TestThrowable.java +++ b/core/src/test/java/org/matomo/java/tracking/TestThrowable.java @@ -5,5 +5,4 @@ class TestThrowable extends Throwable { TestThrowable() { super("message", null, false, false); } - } diff --git a/core/src/test/java/org/matomo/java/tracking/TrackerConfigurationTest.java b/core/src/test/java/org/matomo/java/tracking/TrackerConfigurationTest.java index 593aa7b7..3cfc17b4 100644 --- a/core/src/test/java/org/matomo/java/tracking/TrackerConfigurationTest.java +++ b/core/src/test/java/org/matomo/java/tracking/TrackerConfigurationTest.java @@ -7,8 +7,8 @@ class TrackerConfigurationTest { - private final TrackerConfiguration.TrackerConfigurationBuilder trackerConfigurationBuilder - = TrackerConfiguration.builder(); + private final TrackerConfiguration.TrackerConfigurationBuilder trackerConfigurationBuilder = + TrackerConfiguration.builder(); @Test void validateDoesNotFailIfDefaultAuthTokenIsNull() { @@ -74,7 +74,6 @@ void validateDoesNotFailIfDefaultSiteIdIsNull() { whenValidates(); } - @Test void validateDoesNotFailIfDefaultSiteIdIsPositive() { trackerConfigurationBuilder @@ -268,7 +267,8 @@ void validateDoesNotFailIfProxyUsernameIsNotSetAndProxyPasswordIsNotSet() { } @Test - void validateFailsIfProxyUsernameIsSetAndProxyPasswordIsNotSetAndProxyHostIsNotSetAndProxyPortIsNotSet() { + void + validateFailsIfProxyUsernameIsSetAndProxyPasswordIsNotSetAndProxyHostIsNotSetAndProxyPortIsNotSet() { trackerConfigurationBuilder .apiEndpoint(URI.create("https://matomo.example/matomo.php")) .proxyUsername("user") @@ -279,7 +279,8 @@ void validateFailsIfProxyUsernameIsSetAndProxyPasswordIsNotSetAndProxyHostIsNotS } @Test - void validateDoesNotFailIfProxyUsernameIsNotSetAndProxyPasswordIsNotSetAndProxyHostIsNotSetAndProxyPortIsNotSet() { + void + validateDoesNotFailIfProxyUsernameIsNotSetAndProxyPasswordIsNotSetAndProxyHostIsNotSetAndProxyPortIsNotSet() { trackerConfigurationBuilder .apiEndpoint(URI.create("https://matomo.example/matomo.php")) .defaultSiteId(1) @@ -289,7 +290,8 @@ void validateDoesNotFailIfProxyUsernameIsNotSetAndProxyPasswordIsNotSetAndProxyH } @Test - void validateFailsIfProxyUsernameIsSetAndProxyPasswordIsSetAndProxyHostIsNotSetAndProxyPortIsNotSet() { + void + validateFailsIfProxyUsernameIsSetAndProxyPasswordIsSetAndProxyHostIsNotSetAndProxyPortIsNotSet() { trackerConfigurationBuilder .apiEndpoint(URI.create("https://matomo.example/matomo.php")) .proxyUsername("user") @@ -406,7 +408,8 @@ void whenValidates() { } private void thenFailsOnValidation(String message) { - assertThatThrownBy(this::whenValidates).isInstanceOf(IllegalArgumentException.class).hasMessage(message); + assertThatThrownBy(this::whenValidates) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(message); } - -} \ No newline at end of file +} diff --git a/core/src/test/java/org/matomo/java/tracking/TrackingParameterMethodTest.java b/core/src/test/java/org/matomo/java/tracking/TrackingParameterMethodTest.java index 8b68c950..db135c8d 100644 --- a/core/src/test/java/org/matomo/java/tracking/TrackingParameterMethodTest.java +++ b/core/src/test/java/org/matomo/java/tracking/TrackingParameterMethodTest.java @@ -9,11 +9,11 @@ class TrackingParameterMethodTest { @Test void validateParameterValueFailsIfPatternDoesNotMatch() { - TrackingParameterMethod trackingParameterMethod = TrackingParameterMethod - .builder() - .parameterName("foo") - .pattern(Pattern.compile("bar")) - .build(); + TrackingParameterMethod trackingParameterMethod = + TrackingParameterMethod.builder() + .parameterName("foo") + .pattern(Pattern.compile("bar")) + .build(); assertThatThrownBy(() -> trackingParameterMethod.validateParameterValue("baz")) .isInstanceOf(MatomoException.class) @@ -30,26 +30,26 @@ void doNothingIfPatternIsNull() { @Test void doNothingIfParameterValueIsNotCharSequence() { - TrackingParameterMethod trackingParameterMethod = TrackingParameterMethod - .builder() - .parameterName("foo") - .pattern(Pattern.compile("bar")) - .maxLength(255) - .min(1) - .max(1) - .build(); + TrackingParameterMethod trackingParameterMethod = + TrackingParameterMethod.builder() + .parameterName("foo") + .pattern(Pattern.compile("bar")) + .maxLength(255) + .min(1) + .max(1) + .build(); trackingParameterMethod.validateParameterValue(1); } @Test void failIfParameterValueIsNull() { - TrackingParameterMethod trackingParameterMethod = TrackingParameterMethod - .builder() - .parameterName("foo") - .pattern(Pattern.compile("bar")) - .maxLength(255) - .build(); + TrackingParameterMethod trackingParameterMethod = + TrackingParameterMethod.builder() + .parameterName("foo") + .pattern(Pattern.compile("bar")) + .maxLength(255) + .build(); assertThatThrownBy(() -> trackingParameterMethod.validateParameterValue(null)) .isInstanceOf(NullPointerException.class) @@ -85,5 +85,4 @@ void failIfParameterValueIsGreaterThanMax() { .isInstanceOf(MatomoException.class) .hasMessage("Invalid value for foo. Must be less or equal than 3"); } - } diff --git a/core/src/test/java/org/matomo/java/tracking/TrustingX509TrustManagerTest.java b/core/src/test/java/org/matomo/java/tracking/TrustingX509TrustManagerTest.java index 895017de..f8cd51e8 100644 --- a/core/src/test/java/org/matomo/java/tracking/TrustingX509TrustManagerTest.java +++ b/core/src/test/java/org/matomo/java/tracking/TrustingX509TrustManagerTest.java @@ -24,5 +24,4 @@ void checkClientTrustedDoesNothing() { void checkServerTrustedDoesNothing() { trustingX509TrustManager.checkServerTrusted(null, null); } - -} \ No newline at end of file +} diff --git a/core/src/test/java/org/matomo/java/tracking/parameters/AcceptLanguageTest.java b/core/src/test/java/org/matomo/java/tracking/parameters/AcceptLanguageTest.java index 6235949d..3772f670 100644 --- a/core/src/test/java/org/matomo/java/tracking/parameters/AcceptLanguageTest.java +++ b/core/src/test/java/org/matomo/java/tracking/parameters/AcceptLanguageTest.java @@ -22,9 +22,8 @@ void fromHeader() { AcceptLanguage acceptLanguage = AcceptLanguage.fromHeader("de,de-DE;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"); - assertThat(acceptLanguage).hasToString( - "de,de-de;q=0.9,de-dd;q=0.9,en;q=0.8,en-gb;q=0.7,en-us;q=0.6"); - + assertThat(acceptLanguage) + .hasToString("de,de-de;q=0.9,de-dd;q=0.9,en;q=0.8,en-gb;q=0.7,en-us;q=0.6"); } @ParameterizedTest @@ -34,15 +33,11 @@ void fromHeaderToleratesNull(String header) { AcceptLanguage acceptLanguage = AcceptLanguage.fromHeader(header); assertThat(acceptLanguage).isNull(); - } @Test void failsOnNullLanguageRange() { - assertThat(AcceptLanguage - .builder() - .languageRanges(singletonList(null)) - .build()).hasToString(""); + assertThat(AcceptLanguage.builder().languageRanges(singletonList(null)).build()) + .hasToString(""); } - } diff --git a/core/src/test/java/org/matomo/java/tracking/parameters/CountryTest.java b/core/src/test/java/org/matomo/java/tracking/parameters/CountryTest.java index 097357c1..03c6f1d4 100644 --- a/core/src/test/java/org/matomo/java/tracking/parameters/CountryTest.java +++ b/core/src/test/java/org/matomo/java/tracking/parameters/CountryTest.java @@ -23,7 +23,6 @@ void createsCountryFromCode() { Country country = Country.fromCode("DE"); assertThat(country).hasToString("de"); - } @Test @@ -32,7 +31,6 @@ void createsCountryFromAcceptLanguageHeader() { Country country = Country.fromLanguageRanges("en-GB;q=0.7,de,de-DE;q=0.9,en;q=0.8,en-US;q=0.6"); assertThat(country).hasToString("de"); - } @ParameterizedTest @@ -42,7 +40,6 @@ void returnsNullOnEmptyRanges(String ranges) { Country country = Country.fromLanguageRanges(ranges); assertThat(country).isNull(); - } @Test @@ -51,7 +48,6 @@ void failsOnInvalidCountryCode() { assertThatThrownBy(() -> Country.fromCode("invalid")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Invalid country code"); - } @Test @@ -60,7 +56,6 @@ void failsOnInvalidCountryCodeLength() { assertThatThrownBy(() -> Country.fromCode("invalid")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Invalid country code"); - } @Test @@ -69,7 +64,6 @@ void returnsNullOnNullCode() { Country country = Country.fromCode(null); assertThat(country).isNull(); - } @Test @@ -78,7 +72,6 @@ void returnsNullOnEmptyCode() { Country country = Country.fromCode(""); assertThat(country).isNull(); - } @Test @@ -87,7 +80,6 @@ void returnsNullOnBlankCode() { Country country = Country.fromCode(" "); assertThat(country).isNull(); - } @Test @@ -96,7 +88,6 @@ void returnsNullOnNullRanges() { Country country = Country.fromLanguageRanges(null); assertThat(country).isNull(); - } @Test @@ -105,7 +96,6 @@ void returnsNullOnBlankRanges() { Country country = Country.fromLanguageRanges(" "); assertThat(country).isNull(); - } @Test @@ -114,7 +104,6 @@ void failsOnInvalidRanges() { assertThatThrownBy(() -> Country.fromLanguageRanges("invalid")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Invalid country code"); - } @Test @@ -123,7 +112,6 @@ void failsOnLocaleWithoutCountryCode() { assertThatThrownBy(() -> new Country(Locale.forLanguageTag("de"))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Invalid locale"); - } @Test @@ -132,23 +120,23 @@ void setLocaleFailsOnNullLocale() { assertThatThrownBy(() -> new Country(Locale.forLanguageTag("de")).setLocale(null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Invalid locale"); - } @Test void setLocaleFailsOnNullCountryCode() { - assertThatThrownBy(() -> new Country(Locale.forLanguageTag("de")).setLocale(Locale.forLanguageTag( - "de"))).isInstanceOf(IllegalArgumentException.class).hasMessage("Invalid locale"); - + assertThatThrownBy( + () -> new Country(Locale.forLanguageTag("de")).setLocale(Locale.forLanguageTag("de"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid locale"); } @Test void setLocaleFailsOnEmptyCountryCode() { - assertThatThrownBy(() -> new Country(Locale.forLanguageTag("de")).setLocale(Locale.forLanguageTag( - "de"))).isInstanceOf(IllegalArgumentException.class).hasMessage("Invalid locale"); - + assertThatThrownBy( + () -> new Country(Locale.forLanguageTag("de")).setLocale(Locale.forLanguageTag("de"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid locale"); } - } diff --git a/core/src/test/java/org/matomo/java/tracking/parameters/CustomVariableTest.java b/core/src/test/java/org/matomo/java/tracking/parameters/CustomVariableTest.java index f072d09e..26af6402 100644 --- a/core/src/test/java/org/matomo/java/tracking/parameters/CustomVariableTest.java +++ b/core/src/test/java/org/matomo/java/tracking/parameters/CustomVariableTest.java @@ -65,5 +65,4 @@ void equalsCustomVariable() { assertThat(variableA).isNotEqualTo(d); assertThat(variableA.hashCode()).isNotEqualTo(d.hashCode()); } - } diff --git a/core/src/test/java/org/matomo/java/tracking/parameters/CustomVariablesTest.java b/core/src/test/java/org/matomo/java/tracking/parameters/CustomVariablesTest.java index 0cf25d80..da1d523d 100644 --- a/core/src/test/java/org/matomo/java/tracking/parameters/CustomVariablesTest.java +++ b/core/src/test/java/org/matomo/java/tracking/parameters/CustomVariablesTest.java @@ -36,13 +36,15 @@ void testAdd_CustomVariable() { assertThat(customVariables.get("a")).isEqualTo("b"); assertThat(customVariables.get(5)).isEqualTo(c); assertThat(customVariables.get(3)).isNull(); - assertThat(customVariables).hasToString("{\"1\":[\"a\",\"b\"],\"2\":[\"c\",\"d\"],\"5\":[\"a\",\"e\"]}"); + assertThat(customVariables) + .hasToString("{\"1\":[\"a\",\"b\"],\"2\":[\"c\",\"d\"],\"5\":[\"a\",\"e\"]}"); CustomVariable d = new CustomVariable("a", "f"); customVariables.add(d); assertThat(customVariables.get("a")).isEqualTo("f"); assertThat(customVariables.get(1)).isEqualTo(d); assertThat(customVariables.get(5)).isEqualTo(d); - assertThat(customVariables).hasToString("{\"1\":[\"a\",\"f\"],\"2\":[\"c\",\"d\"],\"5\":[\"a\",\"f\"]}"); + assertThat(customVariables) + .hasToString("{\"1\":[\"a\",\"f\"],\"2\":[\"c\",\"d\"],\"5\":[\"a\",\"f\"]}"); customVariables.remove("a"); assertThat(customVariables.get("a")).isNull(); assertThat(customVariables.get(1)).isNull(); @@ -123,7 +125,6 @@ void testAddCustomVariableNullIndex() { .hasNoCause(); } - @Test void testAddNullCustomVariableIndex() { assertThatThrownBy(() -> customVariables.add(null, 1)) @@ -174,5 +175,4 @@ void parseCustomVariables() { assertThat(customVariables.get(3).getKey()).isEqualTo("var 3 set"); assertThat(customVariables.get(3).getValue()).isEqualTo("yes!!!!"); } - } diff --git a/core/src/test/java/org/matomo/java/tracking/parameters/DeviceResolutionTest.java b/core/src/test/java/org/matomo/java/tracking/parameters/DeviceResolutionTest.java index 829c915f..84254126 100644 --- a/core/src/test/java/org/matomo/java/tracking/parameters/DeviceResolutionTest.java +++ b/core/src/test/java/org/matomo/java/tracking/parameters/DeviceResolutionTest.java @@ -20,7 +20,6 @@ void formatsDeviceResolution() { DeviceResolution deviceResolution = DeviceResolution.builder().width(1280).height(1080).build(); assertThat(deviceResolution).hasToString("1280x1080"); - } @Test @@ -29,7 +28,6 @@ void returnsNullOnNull() { DeviceResolution deviceResolution = DeviceResolution.fromString(null); assertThat(deviceResolution).isNull(); - } @Test @@ -50,5 +48,4 @@ void failsIfDeviceResolutionIsTooShort() { void returnsNullIfDeviceResolutionIsEmpty() { assertThat(DeviceResolution.fromString("")).isNull(); } - } diff --git a/core/src/test/java/org/matomo/java/tracking/parameters/EcommerceItemsTest.java b/core/src/test/java/org/matomo/java/tracking/parameters/EcommerceItemsTest.java index 9d13a5d8..85bf8343 100644 --- a/core/src/test/java/org/matomo/java/tracking/parameters/EcommerceItemsTest.java +++ b/core/src/test/java/org/matomo/java/tracking/parameters/EcommerceItemsTest.java @@ -4,32 +4,33 @@ import org.junit.jupiter.api.Test; - class EcommerceItemsTest { @Test void formatsJson() { - EcommerceItems ecommerceItems = EcommerceItems - .builder() - .item(EcommerceItem - .builder() - .sku("XYZ12345") - .name("Matomo - The big book about web analytics") - .category("Education & Teaching") - .price(23.1) - .quantity(2) - .build()) - .item(EcommerceItem - .builder() - .sku("B0C2WV3MRJ") - .name("Matomo for data visualization") - .category("Education & Teaching") - .price(15.1) - .quantity(1) - .build()) - .build(); - assertThat(ecommerceItems).hasToString("[[\"XYZ12345\",\"Matomo - The big book about web analytics\",\"Education & Teaching\",23.1,2],[\"B0C2WV3MRJ\",\"Matomo for data visualization\",\"Education & Teaching\",15.1,1]]"); + EcommerceItems ecommerceItems = + EcommerceItems.builder() + .item( + EcommerceItem.builder() + .sku("XYZ12345") + .name("Matomo - The big book about web analytics") + .category("Education & Teaching") + .price(23.1) + .quantity(2) + .build()) + .item( + EcommerceItem.builder() + .sku("B0C2WV3MRJ") + .name("Matomo for data visualization") + .category("Education & Teaching") + .price(15.1) + .quantity(1) + .build()) + .build(); + assertThat(ecommerceItems) + .hasToString( + "[[\"XYZ12345\",\"Matomo - The big book about web analytics\",\"Education &" + + " Teaching\",23.1,2],[\"B0C2WV3MRJ\",\"Matomo for data" + + " visualization\",\"Education & Teaching\",15.1,1]]"); } - - } diff --git a/core/src/test/java/org/matomo/java/tracking/parameters/HexTest.java b/core/src/test/java/org/matomo/java/tracking/parameters/HexTest.java index 5f07f27d..7b9a9b8c 100644 --- a/core/src/test/java/org/matomo/java/tracking/parameters/HexTest.java +++ b/core/src/test/java/org/matomo/java/tracking/parameters/HexTest.java @@ -11,8 +11,6 @@ class HexTest { - - @Test void failsIfBytesAreNull() { assertThatThrownBy(() -> Hex.fromBytes(null)) @@ -24,8 +22,7 @@ private static Stream testBytes() { return Stream.of( Arguments.of(new byte[] {0x00, 0x01, 0x02, 0x03}, "00010203"), Arguments.of(new byte[] {(byte) 0xFF, (byte) 0xFE, (byte) 0xFD, (byte) 0xFC}, "fffefdfc"), - Arguments.of(new byte[0], "") - ); + Arguments.of(new byte[0], "")); } @ParameterizedTest @@ -33,5 +30,4 @@ private static Stream testBytes() { void convertsBytesIntoHex(byte[] bytes, String expected) { assertThat(Hex.fromBytes(bytes)).isEqualTo(expected); } - -} \ No newline at end of file +} diff --git a/core/src/test/java/org/matomo/java/tracking/parameters/UniqueIdTest.java b/core/src/test/java/org/matomo/java/tracking/parameters/UniqueIdTest.java index 00d1bca9..93ab9fe3 100644 --- a/core/src/test/java/org/matomo/java/tracking/parameters/UniqueIdTest.java +++ b/core/src/test/java/org/matomo/java/tracking/parameters/UniqueIdTest.java @@ -12,7 +12,6 @@ void createsRandomUniqueId() { UniqueId uniqueId = UniqueId.random(); assertThat(uniqueId.toString()).matches("[0-9a-zA-Z]{6}"); - } @Test @@ -22,7 +21,5 @@ void createsSameUniqueIds() { UniqueId uniqueId2 = UniqueId.fromValue(868686868); assertThat(uniqueId1).hasToString(uniqueId2.toString()); - } - } diff --git a/core/src/test/java/org/matomo/java/tracking/parameters/VisitorIdTest.java b/core/src/test/java/org/matomo/java/tracking/parameters/VisitorIdTest.java index 45aa34de..36a6c16a 100644 --- a/core/src/test/java/org/matomo/java/tracking/parameters/VisitorIdTest.java +++ b/core/src/test/java/org/matomo/java/tracking/parameters/VisitorIdTest.java @@ -26,8 +26,7 @@ private static Stream validHexStrings() { Arguments.of("1a2b3c4d5e", "0000001a2b3c4d5e"), Arguments.of("1A2B3C4D5E", "0000001a2b3c4d5e"), Arguments.of("1a2b3c4d5e6f", "00001a2b3c4d5e6f"), - Arguments.of("1a2b3c4d5e6f7a", "001a2b3c4d5e6f7a") - ); + Arguments.of("1a2b3c4d5e6f7a", "001a2b3c4d5e6f7a")); } @Test @@ -36,7 +35,6 @@ void hasCorrectFormat() { VisitorId visitorId = VisitorId.random(); assertThat(visitorId.toString()).matches("^[a-z0-9]{16}$"); - } @Test @@ -46,7 +44,6 @@ void createsRandomVisitorId() { VisitorId second = VisitorId.random(); assertThat(first).doesNotHaveToString(second.toString()); - } @Test @@ -55,7 +52,6 @@ void fixedVisitorIdForLongHash() { VisitorId visitorId = VisitorId.fromHash(987654321098765432L); assertThat(visitorId).hasToString("0db4da5f49f8b478"); - } @Test @@ -64,7 +60,6 @@ void fixedVisitorIdForIntHash() { VisitorId visitorId = VisitorId.fromHash(777777777); assertThat(visitorId).hasToString("000000002e5bf271"); - } @Test @@ -74,7 +69,6 @@ void sameVisitorIdForSameHash() { VisitorId second = VisitorId.fromHash(1234567890); assertThat(first).hasToString(second.toString()); - } @Test @@ -83,7 +77,6 @@ void alwaysTheSameToString() { VisitorId visitorId = VisitorId.random(); assertThat(visitorId).hasToString(visitorId.toString()); - } @Test @@ -92,7 +85,6 @@ void createsVisitorIdFrom16CharacterHex() { VisitorId visitorId = VisitorId.fromHex("1234567890abcdef"); assertThat(visitorId).hasToString("1234567890abcdef"); - } @Test @@ -101,7 +93,6 @@ void createsVisitorIdFrom1CharacterHex() { VisitorId visitorId = VisitorId.fromHex("a"); assertThat(visitorId).hasToString("000000000000000a"); - } @Test @@ -110,7 +101,6 @@ void createsVisitorIdFrom2CharacterHex() { VisitorId visitorId = VisitorId.fromHex("12"); assertThat(visitorId).hasToString("0000000000000012"); - } @Test @@ -119,12 +109,22 @@ void failsOnInvalidHexString() { assertThatThrownBy(() -> VisitorId.fromHex("invalid123456789")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Input must be a valid hex string"); - } @ParameterizedTest - @ValueSource(strings = - {"g", "gh", "ghi", "ghij", "ghijk", "ghijkl", "ghijklm", "ghijklmn", "ghijklmn", "-1"}) + @ValueSource( + strings = { + "g", + "gh", + "ghi", + "ghij", + "ghijk", + "ghijkl", + "ghijklm", + "ghijklmn", + "ghijklmn", + "-1" + }) void failsOnInvalidHexString(String hex) { assertThatThrownBy(() -> VisitorId.fromHex(hex)) .isInstanceOf(IllegalArgumentException.class) @@ -133,14 +133,11 @@ void failsOnInvalidHexString(String hex) { @ParameterizedTest @MethodSource("validHexStrings") - void createsVisitorIdFromHex( - String hex, String expected - ) { + void createsVisitorIdFromHex(String hex, String expected) { VisitorId visitorId = VisitorId.fromHex(hex); assertThat(visitorId).hasToString(expected); - } @ParameterizedTest @@ -162,12 +159,10 @@ void failsOnInvalidHexStringLength(String hex) { @Test void createsVisitorIdFromUUID() { - VisitorId visitorId = VisitorId.fromUUID( - java.util.UUID.fromString("12345678-90ab-cdef-1234-567890abcdef") - ); + VisitorId visitorId = + VisitorId.fromUUID(java.util.UUID.fromString("12345678-90ab-cdef-1234-567890abcdef")); assertThat(visitorId).hasToString("1234567890abcdef"); - } @Test @@ -183,7 +178,5 @@ void createsVisitorIdFromString() { VisitorId visitorId = VisitorId.fromString("test"); assertThat(visitorId).hasToString("0000000000364492"); - } - } diff --git a/core/src/test/java/org/matomo/java/tracking/servlet/ServletMatomoRequestTest.java b/core/src/test/java/org/matomo/java/tracking/servlet/ServletMatomoRequestTest.java index 8f11d935..12789f62 100644 --- a/core/src/test/java/org/matomo/java/tracking/servlet/ServletMatomoRequestTest.java +++ b/core/src/test/java/org/matomo/java/tracking/servlet/ServletMatomoRequestTest.java @@ -12,16 +12,14 @@ class ServletMatomoRequestTest { private MatomoRequest.MatomoRequestBuilder requestBuilder; - - private HttpServletRequestWrapper.HttpServletRequestWrapperBuilder wrapperBuilder = + + private HttpServletRequestWrapper.HttpServletRequestWrapperBuilder wrapperBuilder = HttpServletRequestWrapper.builder(); @Test void addsServletRequestHeaders() { - wrapperBuilder - .headers(singletonMap("headername", "headerValue")) - .build(); + wrapperBuilder.headers(singletonMap("headername", "headerValue")).build(); whenBuildsRequest(); @@ -32,37 +30,29 @@ void addsServletRequestHeaders() { @Test void skipsEmptyHeaderNames() { - wrapperBuilder - .headers(singletonMap("", "headerValue")) - .build(); + wrapperBuilder.headers(singletonMap("", "headerValue")).build(); whenBuildsRequest(); MatomoRequest matomoRequest = requestBuilder.build(); assertThat(matomoRequest.getHeaders()).isEmpty(); - } @Test void skipsBlankHeaderNames() { - wrapperBuilder - .headers(singletonMap(" ", "headerValue")) - .build(); + wrapperBuilder.headers(singletonMap(" ", "headerValue")).build(); whenBuildsRequest(); MatomoRequest matomoRequest = requestBuilder.build(); assertThat(matomoRequest.getHeaders()).isEmpty(); - } @ParameterizedTest @ValueSource(strings = {"connection", "content-length", "expect", "host", "upgrade"}) void doesNotAddRestrictedHeaders(String restrictedHeader) { - wrapperBuilder - .headers(singletonMap(restrictedHeader, "headerValue")) - .build(); + wrapperBuilder.headers(singletonMap(restrictedHeader, "headerValue")).build(); whenBuildsRequest(); @@ -79,10 +69,10 @@ void failsIfServletRequestIsNull() { @Test void failsIfBuilderIsNull() { - assertThatThrownBy(() -> ServletMatomoRequest.addServletRequestHeaders( - null, - HttpServletRequestWrapper.builder().build() - )) + assertThatThrownBy( + () -> + ServletMatomoRequest.addServletRequestHeaders( + null, HttpServletRequestWrapper.builder().build())) .isInstanceOf(NullPointerException.class) .hasMessage("builder is marked non-null but is null"); } @@ -90,9 +80,10 @@ void failsIfBuilderIsNull() { @Test void extractsVisitorIdFromCookie() { wrapperBuilder - .cookies(new CookieWrapper[] { - new CookieWrapper("_pk_id.1.1fff", "be40d677d6c7270b.1699801331.") - }) + .cookies( + new CookieWrapper[] { + new CookieWrapper("_pk_id.1.1fff", "be40d677d6c7270b.1699801331.") + }) .build(); whenBuildsRequest(); @@ -105,13 +96,9 @@ void extractsVisitorIdFromCookie() { } @ParameterizedTest - @ValueSource( - strings = {"_pk_ses.1.1fff", "_pk_ref.1.1fff", "_pk_hsr.1.1fff"} - ) + @ValueSource(strings = {"_pk_ses.1.1fff", "_pk_ref.1.1fff", "_pk_hsr.1.1fff"}) void extractsMatomoCookies(String cookieName) { - wrapperBuilder - .cookies(new CookieWrapper[] {new CookieWrapper(cookieName, "anything")}) - .build(); + wrapperBuilder.cookies(new CookieWrapper[] {new CookieWrapper(cookieName, "anything")}).build(); whenBuildsRequest(); @@ -122,12 +109,10 @@ void extractsMatomoCookies(String cookieName) { @Test void extractsSessionIdFromMatomoSessIdCookie() { wrapperBuilder - .cookies(new CookieWrapper[] { - new CookieWrapper( - "MATOMO_SESSID", - "2cbf8b5ba00fbf9ba70853308cd0944a" - ) - }) + .cookies( + new CookieWrapper[] { + new CookieWrapper("MATOMO_SESSID", "2cbf8b5ba00fbf9ba70853308cd0944a") + }) .build(); whenBuildsRequest(); @@ -139,30 +124,28 @@ void extractsSessionIdFromMatomoSessIdCookie() { @Test void parsesVisitCustomVariablesFromCookie() { wrapperBuilder - .cookies(new CookieWrapper[] { - new CookieWrapper( - "_pk_cvar.1.1fff", - "{\"1\":[\"VAR 1 set, var 2 not set\",\"yes\"],\"3\":[\"var 3 set\",\"yes!!!!\"]}" - ) - }) + .cookies( + new CookieWrapper[] { + new CookieWrapper( + "_pk_cvar.1.1fff", + "{\"1\":[\"VAR 1 set, var 2 not set\",\"yes\"],\"3\":[\"var 3" + + " set\",\"yes!!!!\"]}") + }) .build(); whenBuildsRequest(); MatomoRequest matomoRequest = requestBuilder.build(); - assertThat(matomoRequest.getVisitCustomVariables().get(1).getKey()).isEqualTo( - "VAR 1 set, var 2 not set"); + assertThat(matomoRequest.getVisitCustomVariables().get(1).getKey()) + .isEqualTo("VAR 1 set, var 2 not set"); assertThat(matomoRequest.getVisitCustomVariables().get(1).getValue()).isEqualTo("yes"); assertThat(matomoRequest.getVisitCustomVariables().get(3).getKey()).isEqualTo("var 3 set"); assertThat(matomoRequest.getVisitCustomVariables().get(3).getValue()).isEqualTo("yes!!!!"); - } @Test void determinerVisitorIpFromXForwardedForHeader() { - wrapperBuilder - .headers(singletonMap("x-forwarded-for", "44.55.66.77")) - .build(); + wrapperBuilder.headers(singletonMap("x-forwarded-for", "44.55.66.77")).build(); whenBuildsRequest(); @@ -172,9 +155,7 @@ void determinerVisitorIpFromXForwardedForHeader() { @Test void setsActionUrlFromRequestURL() { - wrapperBuilder - .requestURL(new StringBuffer("https://localhost/test")) - .build(); + wrapperBuilder.requestURL(new StringBuffer("https://localhost/test")).build(); whenBuildsRequest(); @@ -184,9 +165,7 @@ void setsActionUrlFromRequestURL() { @Test void setsUserIdFromRemoteUser() { - wrapperBuilder - .remoteUser("remote-user") - .build(); + wrapperBuilder.remoteUser("remote-user").build(); whenBuildsRequest(); @@ -197,5 +176,4 @@ void setsUserIdFromRemoteUser() { private void whenBuildsRequest() { requestBuilder = ServletMatomoRequest.fromServletRequest(wrapperBuilder.build()); } - -} \ No newline at end of file +} diff --git a/core/src/test/java/org/piwik/java/tracking/CustomVariableTest.java b/core/src/test/java/org/piwik/java/tracking/CustomVariableTest.java index 4492d0a2..9b1c4387 100644 --- a/core/src/test/java/org/piwik/java/tracking/CustomVariableTest.java +++ b/core/src/test/java/org/piwik/java/tracking/CustomVariableTest.java @@ -13,5 +13,4 @@ void createsCustomVariable() { assertThat(customVariable.getKey()).isEqualTo("key"); assertThat(customVariable.getValue()).isEqualTo("value"); } - } diff --git a/core/src/test/java/org/piwik/java/tracking/PiwikTrackerIT.java b/core/src/test/java/org/piwik/java/tracking/PiwikTrackerIT.java index c4ce73e6..00282d38 100644 --- a/core/src/test/java/org/piwik/java/tracking/PiwikTrackerIT.java +++ b/core/src/test/java/org/piwik/java/tracking/PiwikTrackerIT.java @@ -14,7 +14,6 @@ void createsNewPiwikTrackerInstanceWithHostUrl() { piwikTracker = new PiwikTracker("http://localhost:8080"); assertThat(piwikTracker).isNotNull(); - } @Test @@ -23,7 +22,6 @@ void createsNewPiwikTrackerInstanceWithHostUrlAndTimeout() { piwikTracker = new PiwikTracker("http://localhost:8080", 1000); assertThat(piwikTracker).isNotNull(); - } @Test @@ -32,7 +30,6 @@ void createsNewPiwikTrackerInstanceWithHostUrlAndProxySettings() { piwikTracker = new PiwikTracker("http://localhost:8080", "localhost", 8080); assertThat(piwikTracker).isNotNull(); - } @Test @@ -41,7 +38,5 @@ void createsNewPiwikTrackerInstanceWithHostUrlAndProxySettingsAndTimeout() { piwikTracker = new PiwikTracker("http://localhost:8080", "localhost", 8080, 1000); assertThat(piwikTracker).isNotNull(); - } - -} \ No newline at end of file +} diff --git a/docker-compose.yml b/docker-compose.yml index 4064bcf8..084d4d1d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,7 +1,6 @@ -version: '3.8' services: database: - image: mariadb:10.11.5-jammy + image: mariadb:12.2.2-noble command: --max-allowed-packet=64MB environment: - MYSQL_ROOT_PASSWORD=matomo @@ -9,7 +8,7 @@ services: - MYSQL_DATABASE=matomo - MYSQL_USER=matomo matomo: - image: matomo:4.15.1-apache + image: matomo:5.8.0-apache environment: - MATOMO_DATABASE_HOST=database - MATOMO_DATABASE_ADAPTER=mysql diff --git a/java11/pom.xml b/java11/pom.xml index fb03eedf..ae7d829c 100644 --- a/java11/pom.xml +++ b/java11/pom.xml @@ -1,15 +1,16 @@ + 4.0.0 org.piwik.java.tracking matomo-java-tracker-parent - 3.4.1-SNAPSHOT + 3.5.0-SNAPSHOT ../pom.xml matomo-java-tracker-java11 - 3.4.1-SNAPSHOT + 3.5.0-SNAPSHOT jar Matomo Java Tracker Java 11 diff --git a/java11/src/main/java/org/matomo/java/tracking/Java11Sender.java b/java11/src/main/java/org/matomo/java/tracking/Java11Sender.java index abb6181f..feae7c23 100644 --- a/java11/src/main/java/org/matomo/java/tracking/Java11Sender.java +++ b/java11/src/main/java/org/matomo/java/tracking/Java11Sender.java @@ -21,33 +21,25 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -/** - * A {@link Sender} implementation that uses the Java 11 HTTP client. - */ +/** A {@link Sender} implementation that uses the Java 11 HTTP client. */ @RequiredArgsConstructor @Slf4j public class Java11Sender implements Sender { - @lombok.NonNull - private final TrackerConfiguration trackerConfiguration; + @lombok.NonNull private final TrackerConfiguration trackerConfiguration; - @lombok.NonNull - private final QueryCreator queryCreator; + @lombok.NonNull private final QueryCreator queryCreator; - @lombok.NonNull - private final HttpClient httpClient; + @lombok.NonNull private final HttpClient httpClient; - @lombok.NonNull - private final CookieStore cookieStore; + @lombok.NonNull private final CookieStore cookieStore; - @lombok.NonNull - private final ExecutorService executorService; + @lombok.NonNull private final ExecutorService executorService; @NonNull @Override public CompletableFuture sendSingleAsync( - @NonNull @lombok.NonNull MatomoRequest request - ) { + @NonNull @lombok.NonNull MatomoRequest request) { return sendAsyncAndCheckResponse(buildHttpGetRequest(request), request); } @@ -60,24 +52,20 @@ private void sendAndCheckResponse(@NonNull HttpRequest httpRequest) { checkResponse( send( httpRequest, - () -> httpClient.send(httpRequest, HttpResponse.BodyHandlers.discarding()) - ), - httpRequest - ); + () -> httpClient.send(httpRequest, HttpResponse.BodyHandlers.discarding())), + httpRequest); } @Override public void sendBulk( @NonNull @lombok.NonNull Iterable requests, - @Nullable String overrideAuthToken - ) { + @Nullable String overrideAuthToken) { sendAndCheckResponse(buildHttpPostRequest(requests, overrideAuthToken)); } @NonNull private HttpRequest buildHttpPostRequest( - @NonNull Iterable requests, @Nullable String overrideAuthToken - ) { + @NonNull Iterable requests, @Nullable String overrideAuthToken) { String authToken = AuthToken.determineAuthToken(overrideAuthToken, requests, trackerConfiguration); Collection queries = new ArrayList<>(); @@ -95,17 +83,14 @@ private HttpRequest buildHttpPostRequest( queries.add(queryCreator.createQuery(request, null)); addCookies(request); } - HttpRequest.Builder builder = HttpRequest - .newBuilder() - .uri(trackerConfiguration.getApiEndpoint()) - .header("Accept", "*/*") - .header("Content-Type", "application/json") - .POST(HttpRequest.BodyPublishers.ofByteArray(BulkRequest - .builder() - .queries(queries) - .authToken(authToken) - .build() - .toBytes())); + HttpRequest.Builder builder = + HttpRequest.newBuilder() + .uri(trackerConfiguration.getApiEndpoint()) + .header("Accept", "*/*") + .header("Content-Type", "application/json") + .POST( + HttpRequest.BodyPublishers.ofByteArray( + BulkRequest.builder().queries(queries).authToken(authToken).build().toBytes())); applyTrackerConfiguration(builder); setUserAgentHeader(builder, headerUserAgent, headers); addHeaders(builder, headers); @@ -116,23 +101,23 @@ private HttpRequest buildHttpPostRequest( @Override public CompletableFuture sendBulkAsync( @NonNull @lombok.NonNull Collection requests, - @Nullable String overrideAuthToken - ) { + @Nullable String overrideAuthToken) { return sendAsyncAndCheckResponse(buildHttpPostRequest(requests, overrideAuthToken), null); } @NonNull private CompletableFuture sendAsyncAndCheckResponse( - @NonNull HttpRequest httpRequest, @Nullable T result - ) { + @NonNull HttpRequest httpRequest, @Nullable T result) { return send( httpRequest, - () -> httpClient.sendAsync(httpRequest, HttpResponse.BodyHandlers.discarding()) - .thenApply(response -> { - checkResponse(response, httpRequest); - return result; - }) - ); + () -> + httpClient + .sendAsync(httpRequest, HttpResponse.BodyHandlers.discarding()) + .thenApply( + response -> { + checkResponse(response, httpRequest); + return result; + })); } @NonNull @@ -142,22 +127,20 @@ private HttpRequest buildHttpGetRequest(@NonNull MatomoRequest request) { cookieStore.removeAll(); addCookies(request); URI apiEndpoint = trackerConfiguration.getApiEndpoint(); - HttpRequest.Builder builder = HttpRequest - .newBuilder() - .uri(apiEndpoint.resolve(String.format( - "%s?%s", - apiEndpoint.getPath(), - queryCreator.createQuery(request, authToken) - ))); + HttpRequest.Builder builder = + HttpRequest.newBuilder() + .uri( + apiEndpoint.resolve( + String.format( + "%s?%s", + apiEndpoint.getPath(), queryCreator.createQuery(request, authToken)))); applyTrackerConfiguration(builder); setUserAgentHeader(builder, request.getHeaderUserAgent(), request.getHeaders()); addHeaders(builder, request.getHeaders()); return builder.build(); } - private T send( - @NonNull HttpRequest httpRequest, @NonNull Callable callable - ) { + private T send(@NonNull HttpRequest httpRequest, @NonNull Callable callable) { try { log.debug("Sending request to Matomo: {}", httpRequest); log.debug("Headers: {}", httpRequest.headers()); @@ -172,21 +155,14 @@ private T send( } private void checkResponse( - @NonNull HttpResponse response, - @NonNull HttpRequest httpRequest - ) { + @NonNull HttpResponse response, @NonNull HttpRequest httpRequest) { if (response.statusCode() > 399) { if (trackerConfiguration.isLogFailedTracking()) { log.error( - "Received HTTP error code {} for URL {}", - response.statusCode(), - httpRequest.uri() - ); + "Received HTTP error code {} for URL {}", response.statusCode(), httpRequest.uri()); } - throw new MatomoException(String.format( - "Tracking endpoint responded with code %d", - response.statusCode() - )); + throw new MatomoException( + String.format("Tracking endpoint responded with code %d", response.statusCode())); } } @@ -211,25 +187,23 @@ private void applyTrackerConfiguration(@NonNull HttpRequest.Builder builder) { private void setUserAgentHeader( HttpRequest.Builder builder, @Nullable String headerUserAgent, - @Nullable Map headers - ) { + @Nullable Map headers) { String userAgentHeader = null; if ((headerUserAgent == null || headerUserAgent.trim().isEmpty()) && headers != null) { TreeMap caseInsensitiveMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); caseInsensitiveMap.putAll(headers); userAgentHeader = caseInsensitiveMap.get("User-Agent"); } - if ((userAgentHeader == null || userAgentHeader.trim().isEmpty()) && ( - headerUserAgent == null || headerUserAgent.trim().isEmpty()) - && trackerConfiguration.getUserAgent() != null && !trackerConfiguration.getUserAgent().isEmpty()) { + if ((userAgentHeader == null || userAgentHeader.trim().isEmpty()) + && (headerUserAgent == null || headerUserAgent.trim().isEmpty()) + && trackerConfiguration.getUserAgent() != null + && !trackerConfiguration.getUserAgent().isEmpty()) { builder.header("User-Agent", trackerConfiguration.getUserAgent()); } } private void addHeaders( - @NonNull HttpRequest.Builder builder, - @Nullable Map headers - ) { + @NonNull HttpRequest.Builder builder, @Nullable Map headers) { if (headers != null) { for (Map.Entry header : headers.entrySet()) { builder.header(header.getKey(), header.getValue()); diff --git a/java11/src/main/java/org/matomo/java/tracking/Java11SenderProvider.java b/java11/src/main/java/org/matomo/java/tracking/Java11SenderProvider.java index d6145198..ea429632 100644 --- a/java11/src/main/java/org/matomo/java/tracking/Java11SenderProvider.java +++ b/java11/src/main/java/org/matomo/java/tracking/Java11SenderProvider.java @@ -11,41 +11,34 @@ import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; -/** - * Provides a {@link Sender} implementation based on Java 11. - */ +/** Provides a {@link Sender} implementation based on Java 11. */ public class Java11SenderProvider implements SenderProvider { private static final TrustManager[] TRUST_ALL_MANAGERS = {new TrustingX509TrustManager()}; @Override public Sender provideSender( - TrackerConfiguration trackerConfiguration, QueryCreator queryCreator - ) { + TrackerConfiguration trackerConfiguration, QueryCreator queryCreator) { CookieManager cookieManager = new CookieManager(); - ExecutorService executorService = Executors.newFixedThreadPool( - trackerConfiguration.getThreadPoolSize(), - new DaemonThreadFactory() - ); - HttpClient.Builder builder = HttpClient - .newBuilder() - .cookieHandler(cookieManager) - .executor(executorService); + ExecutorService executorService = + Executors.newFixedThreadPool( + trackerConfiguration.getThreadPoolSize(), new DaemonThreadFactory()); + HttpClient.Builder builder = + HttpClient.newBuilder().cookieHandler(cookieManager).executor(executorService); if (trackerConfiguration.getConnectTimeout() != null && trackerConfiguration.getConnectTimeout().toMillis() > 0L) { builder.connectTimeout(trackerConfiguration.getConnectTimeout()); } if (!isEmpty(trackerConfiguration.getProxyHost()) && trackerConfiguration.getProxyPort() > 0) { - builder.proxy(ProxySelector.of(new InetSocketAddress( - trackerConfiguration.getProxyHost(), - trackerConfiguration.getProxyPort() - ))); + builder.proxy( + ProxySelector.of( + new InetSocketAddress( + trackerConfiguration.getProxyHost(), trackerConfiguration.getProxyPort()))); if (!isEmpty(trackerConfiguration.getProxyUsername()) && !isEmpty(trackerConfiguration.getProxyPassword())) { - builder.authenticator(new ProxyAuthenticator( - trackerConfiguration.getProxyUsername(), - trackerConfiguration.getProxyPassword() - )); + builder.authenticator( + new ProxyAuthenticator( + trackerConfiguration.getProxyUsername(), trackerConfiguration.getProxyPassword())); } } if (trackerConfiguration.isDisableSslCertValidation()) { @@ -58,7 +51,9 @@ public Sender provideSender( } } if (trackerConfiguration.isDisableSslHostVerification()) { - throw new MatomoException("Please disable SSL hostname verification manually using the system parameter -Djdk.internal.httpclient.disableHostnameVerification=true"); + throw new MatomoException( + "Please disable SSL hostname verification manually using the system parameter" + + " -Djdk.internal.httpclient.disableHostnameVerification=true"); } return new Java11Sender( @@ -66,14 +61,10 @@ public Sender provideSender( queryCreator, builder.build(), cookieManager.getCookieStore(), - executorService - ); + executorService); } - private static boolean isEmpty( - @Nullable String str - ) { + private static boolean isEmpty(@Nullable String str) { return str == null || str.isEmpty() || str.trim().isEmpty(); } - } diff --git a/java11/src/test/java/org/matomo/java/tracking/Java11SenderIT.java b/java11/src/test/java/org/matomo/java/tracking/Java11SenderIT.java index 6ce1a63b..18b86791 100644 --- a/java11/src/test/java/org/matomo/java/tracking/Java11SenderIT.java +++ b/java11/src/test/java/org/matomo/java/tracking/Java11SenderIT.java @@ -40,82 +40,97 @@ void disableSslHostnameVerification() { @Test void failsIfTrackerConfigurationIsNotSet() { CookieManager cookieManager = new CookieManager(); - assertThatThrownBy(() -> new Java11Sender( - null, - new QueryCreator(TrackerConfiguration.builder() - .apiEndpoint(URI.create("http://localhost")) - .build()), - HttpClient.newBuilder().cookieHandler(cookieManager).build(), - cookieManager.getCookieStore(), - Executors.newFixedThreadPool(2, new DaemonThreadFactory()) - )).isInstanceOf(NullPointerException.class) - .hasMessage("trackerConfiguration is marked non-null but is null"); + assertThatThrownBy( + () -> + new Java11Sender( + null, + new QueryCreator( + TrackerConfiguration.builder() + .apiEndpoint(URI.create("http://localhost")) + .build()), + HttpClient.newBuilder().cookieHandler(cookieManager).build(), + cookieManager.getCookieStore(), + Executors.newFixedThreadPool(2, new DaemonThreadFactory()))) + .isInstanceOf(NullPointerException.class) + .hasMessage("trackerConfiguration is marked non-null but is null"); } @Test void failsIfQueryCreatorIsNotSet() { CookieManager cookieManager = new CookieManager(); - assertThatThrownBy(() -> new Java11Sender( - TrackerConfiguration.builder().apiEndpoint(URI.create("http://localhost")).build(), - null, - HttpClient.newBuilder().cookieHandler(cookieManager).build(), - cookieManager.getCookieStore(), - Executors.newFixedThreadPool(2, new DaemonThreadFactory()) - )).isInstanceOf(NullPointerException.class) - .hasMessage("queryCreator is marked non-null but is null"); + assertThatThrownBy( + () -> + new Java11Sender( + TrackerConfiguration.builder() + .apiEndpoint(URI.create("http://localhost")) + .build(), + null, + HttpClient.newBuilder().cookieHandler(cookieManager).build(), + cookieManager.getCookieStore(), + Executors.newFixedThreadPool(2, new DaemonThreadFactory()))) + .isInstanceOf(NullPointerException.class) + .hasMessage("queryCreator is marked non-null but is null"); } @Test void failsIfHttpClientIsNotSet() { CookieManager cookieManager = new CookieManager(); - assertThatThrownBy(() -> new Java11Sender( - TrackerConfiguration.builder().apiEndpoint(URI.create("http://localhost")).build(), - new QueryCreator(TrackerConfiguration.builder() - .apiEndpoint(URI.create("http://localhost")) - .build()), - null, - cookieManager.getCookieStore(), - Executors.newFixedThreadPool(2, new DaemonThreadFactory()) - )).isInstanceOf(NullPointerException.class) - .hasMessage("httpClient is marked non-null but is null"); + assertThatThrownBy( + () -> + new Java11Sender( + TrackerConfiguration.builder() + .apiEndpoint(URI.create("http://localhost")) + .build(), + new QueryCreator( + TrackerConfiguration.builder() + .apiEndpoint(URI.create("http://localhost")) + .build()), + null, + cookieManager.getCookieStore(), + Executors.newFixedThreadPool(2, new DaemonThreadFactory()))) + .isInstanceOf(NullPointerException.class) + .hasMessage("httpClient is marked non-null but is null"); } @Test void failsIfCookieStoreIsNotSet() { CookieManager cookieManager = new CookieManager(); - assertThatThrownBy(() -> new Java11Sender( - TrackerConfiguration.builder().apiEndpoint(URI.create("http://localhost")).build(), - new QueryCreator(TrackerConfiguration.builder() - .apiEndpoint(URI.create("http://localhost")) - .build()), - HttpClient.newBuilder().cookieHandler(cookieManager).build(), - null, - Executors.newFixedThreadPool(2, new DaemonThreadFactory()) - )).isInstanceOf(NullPointerException.class) - .hasMessage("cookieStore is marked non-null but is null"); + assertThatThrownBy( + () -> + new Java11Sender( + TrackerConfiguration.builder() + .apiEndpoint(URI.create("http://localhost")) + .build(), + new QueryCreator( + TrackerConfiguration.builder() + .apiEndpoint(URI.create("http://localhost")) + .build()), + HttpClient.newBuilder().cookieHandler(cookieManager).build(), + null, + Executors.newFixedThreadPool(2, new DaemonThreadFactory()))) + .isInstanceOf(NullPointerException.class) + .hasMessage("cookieStore is marked non-null but is null"); } @Test void sendSingleFailsIfQueryIsMalformedWithSocketTimeout() { - trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create("telnet://localhost")) - .socketTimeout(Duration.ofSeconds(30L)) - .build(); + trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create("telnet://localhost")) + .socketTimeout(Duration.ofSeconds(30L)) + .build(); givenSender(); - assertThatThrownBy(() -> sender.sendSingle(MatomoRequests.ecommerceCartUpdate(50.0) - .goalId(0).build())) + assertThatThrownBy( + () -> sender.sendSingle(MatomoRequests.ecommerceCartUpdate(50.0).goalId(0).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("invalid URI scheme telnet"); } @Test void sendSingleFailsIfQueryIsMalformedWithoutSocketTimeout() { - trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create("telnet://localhost")) - .build(); + trackerConfiguration = + TrackerConfiguration.builder().apiEndpoint(URI.create("telnet://localhost")).build(); givenSender(); assertThatThrownBy(() -> sender.sendSingle(new MatomoRequest())) @@ -124,20 +139,19 @@ void sendSingleFailsIfQueryIsMalformedWithoutSocketTimeout() { } private void givenSender() { - sender = new Java11SenderProvider().provideSender( - trackerConfiguration, - new QueryCreator(trackerConfiguration) - ); + sender = + new Java11SenderProvider() + .provideSender(trackerConfiguration, new QueryCreator(trackerConfiguration)); } @Test void failsIfEndpointReturnsNotFound(WireMockRuntimeInfo wireMockRuntimeInfo) { - trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create(wireMockRuntimeInfo.getHttpBaseUrl())) - .disableSslCertValidation(true) - .socketTimeout(Duration.ofSeconds(0L)) - .build(); + trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create(wireMockRuntimeInfo.getHttpBaseUrl())) + .disableSslCertValidation(true) + .socketTimeout(Duration.ofSeconds(0L)) + .build(); givenSender(); @@ -148,12 +162,12 @@ void failsIfEndpointReturnsNotFound(WireMockRuntimeInfo wireMockRuntimeInfo) { @Test void failsAndLogsIfCouldNotConnectToEndpoint() { - trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create("http://localhost:1234")) - .userAgent("") - .logFailedTracking(true) - .build(); + trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create("http://localhost:1234")) + .userAgent("") + .logFailedTracking(true) + .build(); givenSender(); @@ -166,9 +180,9 @@ void failsAndLogsIfCouldNotConnectToEndpoint() { void failsAndDoesNotLogIfCouldNotConnectToEndpoint() { trackerConfiguration = TrackerConfiguration.builder() - .apiEndpoint(URI.create("http://localhost:1234")) - .userAgent("") - .build(); + .apiEndpoint(URI.create("http://localhost:1234")) + .userAgent("") + .build(); givenSender(); @@ -179,14 +193,14 @@ void failsAndDoesNotLogIfCouldNotConnectToEndpoint() { @Test void connectsViaProxy(WireMockRuntimeInfo wireMockRuntimeInfo) { - trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create(wireMockRuntimeInfo.getHttpBaseUrl())) - .disableSslCertValidation(true) - .proxyHost("localhost") - .proxyPort(wireMockRuntimeInfo.getHttpPort()) - .userAgent(null) - .build(); + trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create(wireMockRuntimeInfo.getHttpBaseUrl())) + .disableSslCertValidation(true) + .proxyHost("localhost") + .proxyPort(wireMockRuntimeInfo.getHttpPort()) + .userAgent(null) + .build(); givenSender(); @@ -197,15 +211,15 @@ void connectsViaProxy(WireMockRuntimeInfo wireMockRuntimeInfo) { @Test void connectsViaProxyWithProxyUserNameAndPassword(WireMockRuntimeInfo wireMockRuntimeInfo) { - trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create(wireMockRuntimeInfo.getHttpBaseUrl())) - .disableSslCertValidation(true) - .proxyHost("localhost") - .proxyPort(wireMockRuntimeInfo.getHttpPort()) - .proxyUsername("user") - .proxyPassword("password") - .build(); + trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create(wireMockRuntimeInfo.getHttpBaseUrl())) + .disableSslCertValidation(true) + .proxyHost("localhost") + .proxyPort(wireMockRuntimeInfo.getHttpPort()) + .proxyUsername("user") + .proxyPassword("password") + .build(); givenSender(); @@ -216,12 +230,12 @@ void connectsViaProxyWithProxyUserNameAndPassword(WireMockRuntimeInfo wireMockRu @Test void logsFailedTracking(WireMockRuntimeInfo wireMockRuntimeInfo) { - trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create(wireMockRuntimeInfo.getHttpsBaseUrl())) - .disableSslCertValidation(true) - .logFailedTracking(true) - .build(); + trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create(wireMockRuntimeInfo.getHttpsBaseUrl())) + .disableSslCertValidation(true) + .logFailedTracking(true) + .build(); givenSender(); @@ -233,71 +247,69 @@ void logsFailedTracking(WireMockRuntimeInfo wireMockRuntimeInfo) { @Test void skipSslCertificationValidation(WireMockRuntimeInfo wireMockRuntimeInfo) { stubFor(get(urlPathEqualTo("/matomo_ssl.php")).willReturn(status(204))); - trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create(String.format( - "https://localhost:%d/matomo_ssl.php", - wireMockRuntimeInfo.getHttpsPort() - ))) - .disableSslCertValidation(true) - .build(); + trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint( + URI.create( + String.format( + "https://localhost:%d/matomo_ssl.php", wireMockRuntimeInfo.getHttpsPort()))) + .disableSslCertValidation(true) + .build(); givenSender(); sender.sendSingle(MatomoRequests.goal(2, 60.0).build()); verify(getRequestedFor(urlPathEqualTo("/matomo_ssl.php"))); - } @Test void addsHeadersToSingleRequest(WireMockRuntimeInfo wireMockRuntimeInfo) { stubFor(get(urlPathEqualTo("/matomo.php")).willReturn(status(204))); - trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create(wireMockRuntimeInfo.getHttpBaseUrl() + "/matomo.php")) - .build(); + trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create(wireMockRuntimeInfo.getHttpBaseUrl() + "/matomo.php")) + .build(); givenSender(); - sender.sendSingle(MatomoRequests.ping() - .headers(singletonMap("headerName", "headerValue")) - .build()); + sender.sendSingle( + MatomoRequests.ping().headers(singletonMap("headerName", "headerValue")).build()); - verify(getRequestedFor(urlPathEqualTo("/matomo.php")).withHeader( - "headerName", - equalTo("headerValue") - )); + verify( + getRequestedFor(urlPathEqualTo("/matomo.php")) + .withHeader("headerName", equalTo("headerValue"))); } @Test void addsHeadersToBulkRequest(WireMockRuntimeInfo wireMockRuntimeInfo) { stubFor(post(urlPathEqualTo("/matomo.php")).willReturn(status(204))); - trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create(wireMockRuntimeInfo.getHttpBaseUrl() + "/matomo.php")) - .build(); + trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create(wireMockRuntimeInfo.getHttpBaseUrl() + "/matomo.php")) + .build(); givenSender(); - sender.sendBulk(List.of(MatomoRequests.goal(1, 23.50).headers(singletonMap( - "headerName", - "headerValue" - )).build()), null); + sender.sendBulk( + List.of( + MatomoRequests.goal(1, 23.50) + .headers(singletonMap("headerName", "headerValue")) + .build()), + null); - verify(postRequestedFor(urlPathEqualTo("/matomo.php")).withHeader( - "headerName", - equalTo("headerValue") - )); + verify( + postRequestedFor(urlPathEqualTo("/matomo.php")) + .withHeader("headerName", equalTo("headerValue"))); } @Test void doesNotAddEmptyHeaders(WireMockRuntimeInfo wireMockRuntimeInfo) { stubFor(post(urlPathEqualTo("/matomo.php")).willReturn(status(204))); - trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create(wireMockRuntimeInfo.getHttpBaseUrl() + "/matomo.php")) - .build(); + trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create(wireMockRuntimeInfo.getHttpBaseUrl() + "/matomo.php")) + .build(); givenSender(); @@ -309,23 +321,23 @@ void doesNotAddEmptyHeaders(WireMockRuntimeInfo wireMockRuntimeInfo) { @Test void addsHeadersToBulkAsyncRequest(WireMockRuntimeInfo wireMockRuntimeInfo) { stubFor(post(urlPathEqualTo("/matomo.php")).willReturn(status(204))); - trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create(wireMockRuntimeInfo.getHttpBaseUrl() + "/matomo.php")) - .build(); + trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create(wireMockRuntimeInfo.getHttpBaseUrl() + "/matomo.php")) + .build(); givenSender(); - CompletableFuture future = sender.sendBulkAsync(List.of(MatomoRequest - .request() - .headers(singletonMap("headerName", "headerValue")) - .build()), null); + CompletableFuture future = + sender.sendBulkAsync( + List.of( + MatomoRequest.request().headers(singletonMap("headerName", "headerValue")).build()), + null); future.join(); - verify(postRequestedFor(urlPathEqualTo("/matomo.php")).withHeader( - "headerName", - equalTo("headerValue") - )); + verify( + postRequestedFor(urlPathEqualTo("/matomo.php")) + .withHeader("headerName", equalTo("headerValue"))); } @Test @@ -383,14 +395,12 @@ void failsOnSendBulkAsyncIfOverrideAuthTokenIsMalformed() { givenSender(); - assertThatThrownBy(() -> sender.sendBulkAsync( - List.of(MatomoRequests - .siteSearch("Special offers", "Products", 5L).build()), - "telnet://localhost" - )) + assertThatThrownBy( + () -> + sender.sendBulkAsync( + List.of(MatomoRequests.siteSearch("Special offers", "Products", 5L).build()), + "telnet://localhost")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Auth token must be exactly 32 characters long"); } - - } diff --git a/java11/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java b/java11/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java index 734d69e0..08468144 100644 --- a/java11/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java +++ b/java11/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java @@ -46,12 +46,13 @@ class MatomoTrackerIT { private static final int SITE_ID = 42; - private final TrackerConfigurationBuilder trackerConfigurationBuilder = TrackerConfiguration.builder(); + private final TrackerConfigurationBuilder trackerConfigurationBuilder = + TrackerConfiguration.builder(); - private final MatomoRequestBuilder requestBuilder = MatomoRequest - .builder() - .visitorId(VisitorId.fromHex("bbccddeeff1122")) - .randomValue(RandomValue.fromString("someRandom")); + private final MatomoRequestBuilder requestBuilder = + MatomoRequest.request() + .visitorId(VisitorId.fromHex("bbccddeeff1122")) + .randomValue(RandomValue.fromString("someRandom")); private CompletableFuture future; @@ -67,12 +68,13 @@ void givenStub() { @Test void requiresSiteId(WireMockRuntimeInfo wireMockRuntimeInfo) { - trackerConfigurationBuilder.apiEndpoint(URI.create(wireMockRuntimeInfo.getHttpBaseUrl() + "/matomo.php")).build(); + trackerConfigurationBuilder + .apiEndpoint(URI.create(wireMockRuntimeInfo.getHttpBaseUrl() + "/matomo.php")) + .build(); assertThatThrownBy(this::whenSendsRequestAsync) .isInstanceOf(IllegalArgumentException.class) .hasMessage("No default site ID and no request site ID is given"); - } private void whenSendsRequestAsync() { @@ -88,7 +90,6 @@ void usesDefaultSiteId(WireMockRuntimeInfo wireMockRuntimeInfo) { whenSendsRequestAsync(); thenGetsRequest("idsite=42&rec=1&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom"); - } private void givenTrackerConfigurationWithDefaultSiteId(WireMockRuntimeInfo wireMockRuntimeInfo) { @@ -98,11 +99,14 @@ private void givenTrackerConfigurationWithDefaultSiteId(WireMockRuntimeInfo wire } private void thenGetsRequest(String expectedQuery) { - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - verify(getRequestedFor(urlEqualTo(String.format("/matomo.php?%s", expectedQuery))).withHeader("User-Agent", - equalTo("MatomoJavaClient") - )); - }); + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + verify( + getRequestedFor(urlEqualTo(String.format("/matomo.php?%s", expectedQuery))) + .withHeader("User-Agent", equalTo("MatomoJavaClient"))); + }); } @Test @@ -114,7 +118,6 @@ void overridesDefaultSiteId(WireMockRuntimeInfo wireMockRuntimeInfo) { whenSendsRequestAsync(); thenGetsRequest("rec=1&idsite=123&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom"); - } @Test @@ -126,7 +129,6 @@ void validatesTokenAuth(WireMockRuntimeInfo wireMockRuntimeInfo) { assertThatThrownBy(this::whenSendsRequestAsync) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Auth token must be exactly 32 characters long"); - } @Test @@ -137,8 +139,8 @@ void convertsTrueBooleanTo1(WireMockRuntimeInfo wireMockRuntimeInfo) { whenSendsRequestAsync(); - thenGetsRequest("idsite=42&rec=1&apiv=1&_id=00bbccddeeff1122&fla=1&send_image=0&rand=someRandom"); - + thenGetsRequest( + "idsite=42&rec=1&apiv=1&_id=00bbccddeeff1122&fla=1&send_image=0&rand=someRandom"); } @Test @@ -149,8 +151,8 @@ void convertsFalseBooleanTo0(WireMockRuntimeInfo wireMockRuntimeInfo) { whenSendsRequestAsync(); - thenGetsRequest("idsite=42&rec=1&apiv=1&_id=00bbccddeeff1122&java=0&send_image=0&rand=someRandom"); - + thenGetsRequest( + "idsite=42&rec=1&apiv=1&_id=00bbccddeeff1122&java=0&send_image=0&rand=someRandom"); } @Test @@ -163,7 +165,6 @@ void encodesUrl(WireMockRuntimeInfo wireMockRuntimeInfo) { thenGetsRequest( "idsite=42&rec=1&url=https%3A%2F%2Fwww.daniel-heid.de%2Fsome%2Fpage%3Ffoo%3Dbar&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom"); - } @Test @@ -176,7 +177,6 @@ void encodesReferrerUrl(WireMockRuntimeInfo wireMockRuntimeInfo) { thenGetsRequest( "idsite=42&rec=1&apiv=1&_id=00bbccddeeff1122&urlref=https%3A%2F%2Fwww.daniel-heid.de%2Fsome%2Freferrer%3Ffoo2%3Dbar2&send_image=0&rand=someRandom"); - } @Test @@ -189,9 +189,7 @@ void encodesLink(WireMockRuntimeInfo wireMockRuntimeInfo) { thenPostsRequestWithoutAuthToken( "idsite=42&rec=1&apiv=1&_id=00bbccddeeff1122&link=https%3A%2F%2Fwww.daniel-heid.de%2Fsome%2Fexternal%2Flink%23&send_image=0&rand=someRandom", - "156" - ); - + "156"); } @Test @@ -202,25 +200,29 @@ void sendsRequestsBulkAsynchronously(WireMockRuntimeInfo wireMockRuntimeInfo) { future = matomoTracker.sendBulkRequestAsync(requestBuilder.build()); - thenPostsRequestWithoutAuthToken("idsite=42&rec=1&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom", "90"); - + thenPostsRequestWithoutAuthToken( + "idsite=42&rec=1&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom", "90"); } private void whenSendsBulkRequestAsync() { future = - new MatomoTracker(trackerConfigurationBuilder.build()).sendBulkRequestAsync(singleton(requestBuilder.build())); + new MatomoTracker(trackerConfigurationBuilder.build()) + .sendBulkRequestAsync(singleton(requestBuilder.build())); } private void thenPostsRequestWithoutAuthToken(String expectedQuery, String contentLength) { - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - verify(postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo(contentLength)) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody(equalToJson("{\"requests\":[\"?" + expectedQuery + "\"]}"))); - }); - + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + verify( + postRequestedFor(urlEqualTo("/matomo.php")) + .withHeader("Content-Length", equalTo(contentLength)) + .withHeader("Accept", equalTo("*/*")) + .withHeader("Content-Type", equalTo("application/json")) + .withHeader("User-Agent", equalTo("MatomoJavaClient")) + .withRequestBody(equalToJson("{\"requests\":[\"?" + expectedQuery + "\"]}"))); + }); } @Test @@ -233,9 +235,7 @@ void encodesDownloadUrl(WireMockRuntimeInfo wireMockRuntimeInfo) { thenPostsRequestWithoutAuthToken( "idsite=42&rec=1&apiv=1&_id=00bbccddeeff1122&download=https%3A%2F%2Fwww.daniel-heid.de%2Fsome%2Fdownload.pdf&send_image=0&rand=someRandom", - "154" - ); - + "154"); } @Test @@ -245,10 +245,14 @@ void getContainsHeaders(WireMockRuntimeInfo wireMockRuntimeInfo) { whenSendsRequestAsync(); - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - verify(getRequestedFor(urlPathEqualTo("/matomo.php")).withHeader("User-Agent", equalTo("MatomoJavaClient"))); - }); - + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + verify( + getRequestedFor(urlPathEqualTo("/matomo.php")) + .withHeader("User-Agent", equalTo("MatomoJavaClient"))); + }); } @Test @@ -258,14 +262,17 @@ void postContainsHeaders(WireMockRuntimeInfo wireMockRuntimeInfo) { whenSendsBulkRequestAsync(); - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - verify(postRequestedFor(urlPathEqualTo("/matomo.php")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Length", equalTo("90")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient"))); - }); - + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + verify( + postRequestedFor(urlPathEqualTo("/matomo.php")) + .withHeader("Accept", equalTo("*/*")) + .withHeader("Content-Length", equalTo("90")) + .withHeader("Content-Type", equalTo("application/json")) + .withHeader("User-Agent", equalTo("MatomoJavaClient"))); + }); } @Test @@ -276,10 +283,14 @@ void allowsToOverrideUserAgent(WireMockRuntimeInfo wireMockRuntimeInfo) { whenSendsRequestAsync(); - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - verify(getRequestedFor(urlPathEqualTo("/matomo.php")).withHeader("User-Agent", equalTo("Mozilla/5.0"))); - }); - + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + verify( + getRequestedFor(urlPathEqualTo("/matomo.php")) + .withHeader("User-Agent", equalTo("Mozilla/5.0"))); + }); } @Test @@ -291,43 +302,56 @@ void tracksMinimalRequest(WireMockRuntimeInfo wireMockRuntimeInfo) { .actionUrl("https://www.daniel-heid.de/portfolio") .visitorId(VisitorId.fromHash(3434343434343434343L)) .referrerUrl("https://www.daniel-heid.de/referrer") - .visitCustomVariables(new CustomVariables() - .add(new CustomVariable("customVariable1Key", "customVariable1Value"), 4) - .add(new CustomVariable("customVariable2Key", "customVariable2Value"), 5)) + .visitCustomVariables( + new CustomVariables() + .add(new CustomVariable("customVariable1Key", "customVariable1Value"), 4) + .add(new CustomVariable("customVariable2Key", "customVariable2Value"), 5)) .visitorVisitCount(2) - .visitorFirstVisitTimestamp(LocalDateTime.of(2022, 8, 9, 18, 34, 12).toInstant(ZoneOffset.UTC)) + .visitorFirstVisitTimestamp( + LocalDateTime.of(2022, 8, 9, 18, 34, 12).toInstant(ZoneOffset.UTC)) .deviceResolution(DeviceResolution.builder().width(1024).height(768).build()) - .headerAcceptLanguage(AcceptLanguage - .builder() - .languageRange(new LanguageRange("de")) - .languageRange(new LanguageRange("de-DE", 0.9)) - .languageRange(new LanguageRange("en", 0.8)) - .build()) + .headerAcceptLanguage( + AcceptLanguage.builder() + .languageRange(new LanguageRange("de")) + .languageRange(new LanguageRange("de-DE", 0.9)) + .languageRange(new LanguageRange("en", 0.8)) + .build()) .pageViewId(UniqueId.fromValue(999999999999999999L)) .goalId(0) .ecommerceRevenue(12.34) - .ecommerceItems(EcommerceItems - .builder() - .item(EcommerceItem.builder().sku("SKU").build()) - .item(EcommerceItem.builder().sku("SKU").name("NAME").category("CATEGORY").price(123.4).build()) - .build()) + .ecommerceItems( + EcommerceItems.builder() + .item(EcommerceItem.builder().sku("SKU").build()) + .item( + EcommerceItem.builder() + .sku("SKU") + .name("NAME") + .category("CATEGORY") + .price(123.4) + .build()) + .build()) .authToken("fdf6e8461ea9de33176b222519627f78") - .visitorCountry(Country.fromLanguageRanges("en-GB;q=0.7,de,de-DE;q=0.9,en;q=0.8,en-US;q=0.6")); + .visitorCountry( + Country.fromLanguageRanges("en-GB;q=0.7,de,de-DE;q=0.9,en;q=0.8,en-US;q=0.6")); whenSendsBulkRequestAsync(); - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - verify(postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("711")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody(equalToJson("{\"requests\":[\"?" - + "idsite=42&rec=1&action_name=Help+%2F+Feedback&url=https%3A%2F%2Fwww.daniel-heid.de%2Fportfolio&apiv=1&_id=2fa93d2858bc4867&urlref=https%3A%2F%2Fwww.daniel-heid.de%2Freferrer&_cvar=%7B%224%22%3A%5B%22customVariable1Key%22%2C%22customVariable1Value%22%5D%2C%225%22%3A%5B%22customVariable2Key%22%2C%22customVariable2Value%22%5D%7D&_idvc=2&_idts=1660070052&res=1024x768&lang=de%2Cde-de%3Bq%3D0.9%2Cen%3Bq%3D0.8&pv_id=lbBbxG&idgoal=0&revenue=12.34&ec_items=%5B%5B%22SKU%22%2C%22%22%2C%22%22%2C0.0%2C0%5D%2C%5B%22SKU%22%2C%22NAME%22%2C%22CATEGORY%22%2C123.4%2C0%5D%5D&token_auth=fdf6e8461ea9de33176b222519627f78&country=de&send_image=0&rand=someRandom" - + "\"],\"token_auth\" : \"" + "fdf6e8461ea9de33176b222519627f78" + "\"}"))); - - }); - + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + verify( + postRequestedFor(urlEqualTo("/matomo.php")) + .withHeader("Content-Length", equalTo("711")) + .withHeader("Accept", equalTo("*/*")) + .withHeader("Content-Type", equalTo("application/json")) + .withHeader("User-Agent", equalTo("MatomoJavaClient")) + .withRequestBody( + equalToJson( + "{\"requests\":[\"?" + + "idsite=42&rec=1&action_name=Help+%2F+Feedback&url=https%3A%2F%2Fwww.daniel-heid.de%2Fportfolio&apiv=1&_id=2fa93d2858bc4867&urlref=https%3A%2F%2Fwww.daniel-heid.de%2Freferrer&_cvar=%7B%224%22%3A%5B%22customVariable1Key%22%2C%22customVariable1Value%22%5D%2C%225%22%3A%5B%22customVariable2Key%22%2C%22customVariable2Value%22%5D%7D&_idvc=2&_idts=1660070052&res=1024x768&lang=de%2Cde-de%3Bq%3D0.9%2Cen%3Bq%3D0.8&pv_id=lbBbxG&idgoal=0&revenue=12.34&ec_items=%5B%5B%22SKU%22%2C%22%22%2C%22%22%2C0.0%2C0%5D%2C%5B%22SKU%22%2C%22NAME%22%2C%22CATEGORY%22%2C123.4%2C0%5D%5D&token_auth=fdf6e8461ea9de33176b222519627f78&country=de&send_image=0&rand=someRandom\"],\"token_auth\"" + + " : \"fdf6e8461ea9de33176b222519627f78\"}"))); + }); } @Test @@ -340,7 +364,6 @@ void doesNothingIfNotEnabled(WireMockRuntimeInfo wireMockRuntimeInfo) throws Exc future.get(); verify(0, postRequestedFor(urlPathEqualTo("/matomo.php"))); - } @Test @@ -359,7 +382,6 @@ void reportsErrors(WireMockRuntimeInfo wireMockRuntimeInfo) { .havingRootCause() .isInstanceOf(MatomoException.class) .withMessage("Tracking endpoint responded with code 500"); - } @Test @@ -370,13 +392,16 @@ void includesDefaultTokenAuth(WireMockRuntimeInfo wireMockRuntimeInfo) { whenSendsRequestAsync(); - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - verify(getRequestedFor(urlEqualTo( - "/matomo.php?idsite=42&token_auth=fdf6e8461ea9de33176b222519627f78&rec=1&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom")).withHeader("User-Agent", - equalTo("MatomoJavaClient") - )); - }); - + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + verify( + getRequestedFor( + urlEqualTo( + "/matomo.php?idsite=42&token_auth=fdf6e8461ea9de33176b222519627f78&rec=1&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom")) + .withHeader("User-Agent", equalTo("MatomoJavaClient"))); + }); } @Test @@ -385,21 +410,31 @@ void includesMultipleQueriesInBulkRequest(WireMockRuntimeInfo wireMockRuntimeInf givenTrackerConfigurationWithDefaultSiteId(wireMockRuntimeInfo); matomoTracker = new MatomoTracker(trackerConfigurationBuilder.build()); - future = matomoTracker.sendBulkRequestAsync(Arrays.asList(requestBuilder.actionName("First").build(), - requestBuilder.actionName("Second").build(), - requestBuilder.actionName("Third").build() - )); - - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - verify(postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("297")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody(equalToJson( - "{\"requests\" : [ \"?idsite=42&rec=1&action_name=First&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom\", \"?idsite=42&rec=1&action_name=Second&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom\", \"?idsite=42&rec=1&action_name=Third&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom\" ]}"))); - }); + future = + matomoTracker.sendBulkRequestAsync( + Arrays.asList( + requestBuilder.actionName("First").build(), + requestBuilder.actionName("Second").build(), + requestBuilder.actionName("Third").build())); + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + verify( + postRequestedFor(urlEqualTo("/matomo.php")) + .withHeader("Content-Length", equalTo("297")) + .withHeader("Accept", equalTo("*/*")) + .withHeader("Content-Type", equalTo("application/json")) + .withHeader("User-Agent", equalTo("MatomoJavaClient")) + .withRequestBody( + equalToJson( + "{\"requests\" : [" + + " \"?idsite=42&rec=1&action_name=First&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom\"," + + " \"?idsite=42&rec=1&action_name=Second&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom\"," + + " \"?idsite=42&rec=1&action_name=Third&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom\"" + + " ]}"))); + }); } @Test @@ -413,12 +448,11 @@ void failsOnNegativeSiteId(WireMockRuntimeInfo wireMockRuntimeInfo) { .hasMessage("Could not append parameter") .hasRootCauseInstanceOf(MatomoException.class) .hasRootCauseMessage("Invalid value for idsite. Must be greater or equal than 1"); - } @Test - void doesNotSendRequestAsyncIfTrackerConfigurationIsDisabled(WireMockRuntimeInfo wireMockRuntimeInfo) - throws Exception { + void doesNotSendRequestAsyncIfTrackerConfigurationIsDisabled( + WireMockRuntimeInfo wireMockRuntimeInfo) throws Exception { givenTrackerConfigurationWithDefaultSiteId(wireMockRuntimeInfo); trackerConfigurationBuilder.enabled(false); @@ -426,7 +460,6 @@ void doesNotSendRequestAsyncIfTrackerConfigurationIsDisabled(WireMockRuntimeInfo future.get(); verify(0, getRequestedFor(urlPathEqualTo("/matomo.php"))); - } @Test @@ -444,7 +477,8 @@ private void whenSendsSingleRequest() { } @Test - void doesNotSendBulkRequestIfTrackerConfigurationIsDisabled(WireMockRuntimeInfo wireMockRuntimeInfo) { + void doesNotSendBulkRequestIfTrackerConfigurationIsDisabled( + WireMockRuntimeInfo wireMockRuntimeInfo) { givenTrackerConfigurationWithDefaultSiteId(wireMockRuntimeInfo); trackerConfigurationBuilder.enabled(false); @@ -454,12 +488,13 @@ void doesNotSendBulkRequestIfTrackerConfigurationIsDisabled(WireMockRuntimeInfo } private void whenSendsBulkRequest() { - new MatomoTracker(trackerConfigurationBuilder.build()).sendBulkRequest(singleton(requestBuilder.build())); + new MatomoTracker(trackerConfigurationBuilder.build()) + .sendBulkRequest(singleton(requestBuilder.build())); } @Test - void doesNotSendBulkRequestAsyncIfTrackerConfigurationIsDisabled(WireMockRuntimeInfo wireMockRuntimeInfo) - throws Exception { + void doesNotSendBulkRequestAsyncIfTrackerConfigurationIsDisabled( + WireMockRuntimeInfo wireMockRuntimeInfo) throws Exception { givenTrackerConfigurationWithDefaultSiteId(wireMockRuntimeInfo); trackerConfigurationBuilder.enabled(false); @@ -474,13 +509,19 @@ void sendsRequestAsyncAndAcceptsCallback(WireMockRuntimeInfo wireMockRuntimeInfo givenTrackerConfigurationWithDefaultSiteId(wireMockRuntimeInfo); matomoTracker = new MatomoTracker(trackerConfigurationBuilder.build()); AtomicBoolean success = new AtomicBoolean(); - future = matomoTracker.sendRequestAsync(requestBuilder.build(), request -> { - success.set(true); - return null; - }); - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - verify(getRequestedFor(urlPathEqualTo("/matomo.php"))); - }); + future = + matomoTracker.sendRequestAsync( + requestBuilder.build(), + request -> { + success.set(true); + return null; + }); + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + verify(getRequestedFor(urlPathEqualTo("/matomo.php"))); + }); assertThat(success).isTrue(); } @@ -489,13 +530,18 @@ void sendsRequestsAsyncAndAcceptsCallback(WireMockRuntimeInfo wireMockRuntimeInf givenTrackerConfigurationWithDefaultSiteId(wireMockRuntimeInfo); matomoTracker = new MatomoTracker(trackerConfigurationBuilder.build()); AtomicBoolean success = new AtomicBoolean(); - future = matomoTracker.sendBulkRequestAsync(singleton(requestBuilder.build()), v -> { - success.set(true); - }); - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - verify(postRequestedFor(urlPathEqualTo("/matomo.php"))); - }); + future = + matomoTracker.sendBulkRequestAsync( + singleton(requestBuilder.build()), + v -> { + success.set(true); + }); + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + verify(postRequestedFor(urlPathEqualTo("/matomo.php"))); + }); assertThat(success).isTrue(); } - } diff --git a/java11/src/test/java/org/matomo/java/tracking/PiwikTrackerIT.java b/java11/src/test/java/org/matomo/java/tracking/PiwikTrackerIT.java index 799af605..f812714e 100644 --- a/java11/src/test/java/org/matomo/java/tracking/PiwikTrackerIT.java +++ b/java11/src/test/java/org/matomo/java/tracking/PiwikTrackerIT.java @@ -50,24 +50,21 @@ void setUp(WireMockRuntimeInfo wireMockRuntimeInfo) throws MalformedURLException request.setVisitorId(VisitorId.fromHash(999999999999999999L)); } - /** - * Test of sendRequest method, of class PiwikTracker. - */ + /** Test of sendRequest method, of class PiwikTracker. */ @Test void testSendRequest() { request.setCustomTrackingParameter("parameterName", "parameterValue"); piwikTracker.sendRequest(request); - verify(getRequestedFor(urlEqualTo( - "/matomo.php?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue")).withHeader("User-Agent", - equalTo("MatomoJavaClient") - )); + verify( + getRequestedFor( + urlEqualTo( + "/matomo.php?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue")) + .withHeader("User-Agent", equalTo("MatomoJavaClient"))); } - /** - * Test of sendRequestAsync method, of class PiwikTracker. - */ + /** Test of sendRequestAsync method, of class PiwikTracker. */ @Test void testSendRequestAsync() { request.setCustomTrackingParameter("parameterName", "parameterValue"); @@ -75,19 +72,19 @@ void testSendRequestAsync() { CompletableFuture future = piwikTracker.sendRequestAsync(request); assertThat(future).isNotCompletedExceptionally(); - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - verify(getRequestedFor(urlEqualTo( - "/matomo.php?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue")) - .withHeader("User-Agent", equalTo("MatomoJavaClient") - )); - }); - + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + verify( + getRequestedFor( + urlEqualTo( + "/matomo.php?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue")) + .withHeader("User-Agent", equalTo("MatomoJavaClient"))); + }); } - - /** - * Test of sendBulkRequest method, of class PiwikTracker. - */ + /** Test of sendBulkRequest method, of class PiwikTracker. */ @Test void testSendBulkRequest_Iterable() { List requests = Collections.singletonList(request); @@ -95,19 +92,20 @@ void testSendBulkRequest_Iterable() { piwikTracker.sendBulkRequest(requests); - verify(postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("167")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody(equalToJson( - "{ \"requests\" : [ \"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\" ]}"))); - + verify( + postRequestedFor(urlEqualTo("/matomo.php")) + .withHeader("Content-Length", equalTo("167")) + .withHeader("Accept", equalTo("*/*")) + .withHeader("Content-Type", equalTo("application/json")) + .withHeader("User-Agent", equalTo("MatomoJavaClient")) + .withRequestBody( + equalToJson( + "{ \"requests\" : [" + + " \"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"" + + " ]}"))); } - /** - * Test of sendBulkRequest method, of class PiwikTracker. - */ + /** Test of sendBulkRequest method, of class PiwikTracker. */ @Test void testSendBulkRequest_Iterable_StringTT() { List requests = Collections.singletonList(request); @@ -125,14 +123,15 @@ void testSendBulkRequest_Iterable_StringFF() { piwikTracker.sendBulkRequest(requests, null); - verify(postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("167")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody(equalToJson( - "{\"requests\":[\"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"]}"))); - + verify( + postRequestedFor(urlEqualTo("/matomo.php")) + .withHeader("Content-Length", equalTo("167")) + .withHeader("Accept", equalTo("*/*")) + .withHeader("Content-Type", equalTo("application/json")) + .withHeader("User-Agent", equalTo("MatomoJavaClient")) + .withRequestBody( + equalToJson( + "{\"requests\":[\"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"]}"))); } @Test @@ -142,19 +141,19 @@ void testSendBulkRequest_Iterable_StringFT() { piwikTracker.sendBulkRequest(requests, "12345678901234567890123456789012"); - verify(postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("215")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody(equalToJson( - "{\"requests\":[\"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\" ],\"token_auth\":\"12345678901234567890123456789012\"}"))); - + verify( + postRequestedFor(urlEqualTo("/matomo.php")) + .withHeader("Content-Length", equalTo("215")) + .withHeader("Accept", equalTo("*/*")) + .withHeader("Content-Type", equalTo("application/json")) + .withHeader("User-Agent", equalTo("MatomoJavaClient")) + .withRequestBody( + equalToJson( + "{\"requests\":[\"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"" + + " ],\"token_auth\":\"12345678901234567890123456789012\"}"))); } - /** - * Test of sendBulkRequestAsync method, of class PiwikTracker. - */ + /** Test of sendBulkRequestAsync method, of class PiwikTracker. */ @Test void testSendBulkRequestAsync_Iterable() { List requests = Collections.singletonList(request); @@ -162,22 +161,25 @@ void testSendBulkRequestAsync_Iterable() { CompletableFuture future = piwikTracker.sendBulkRequestAsync(requests); - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - verify(postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("167")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody(equalToJson( - "{\"requests\" : [ \"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\" ]}"))); - - }); - + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + verify( + postRequestedFor(urlEqualTo("/matomo.php")) + .withHeader("Content-Length", equalTo("167")) + .withHeader("Accept", equalTo("*/*")) + .withHeader("Content-Type", equalTo("application/json")) + .withHeader("User-Agent", equalTo("MatomoJavaClient")) + .withRequestBody( + equalToJson( + "{\"requests\" : [" + + " \"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"" + + " ]}"))); + }); } - /** - * Test of sendBulkRequestAsync method, of class PiwikTracker. - */ + /** Test of sendBulkRequestAsync method, of class PiwikTracker. */ @Test void testSendBulkRequestAsync_Iterable_StringTT() { @@ -187,10 +189,8 @@ void testSendBulkRequestAsync_Iterable_StringTT() { assertThatThrownBy(() -> piwikTracker.sendBulkRequestAsync(requests, "1").get()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Auth token must be exactly 32 characters long"); - } - @Test void testSendBulkRequestAsync_Iterable_String() { @@ -201,28 +201,35 @@ void testSendBulkRequestAsync_Iterable_String() { piwikTracker.sendBulkRequestAsync(requests, "12345678901234567890123456789012"); assertThat(future).isNotCompletedExceptionally(); - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - verify(postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("215")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody(equalToJson( - "{\"requests\":[ \"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"],\"token_auth\":\"12345678901234567890123456789012\"}"))); - - }); + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + verify( + postRequestedFor(urlEqualTo("/matomo.php")) + .withHeader("Content-Length", equalTo("215")) + .withHeader("Accept", equalTo("*/*")) + .withHeader("Content-Type", equalTo("application/json")) + .withHeader("User-Agent", equalTo("MatomoJavaClient")) + .withRequestBody( + equalToJson( + "{\"requests\":[" + + " \"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"],\"token_auth\":\"12345678901234567890123456789012\"}"))); + }); } @Test void createsPiwikTrackerWithHostUrl(WireMockRuntimeInfo wireMockRuntimeInfo) { - PiwikTracker piwikTracker = new PiwikTracker(wireMockRuntimeInfo.getHttpBaseUrl() + "/matomo.php"); + PiwikTracker piwikTracker = + new PiwikTracker(wireMockRuntimeInfo.getHttpBaseUrl() + "/matomo.php"); piwikTracker.sendRequest(request); - verify(getRequestedFor(urlEqualTo( - "/matomo.php?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand")).withHeader("User-Agent", - equalTo("MatomoJavaClient") - )); + verify( + getRequestedFor( + urlEqualTo( + "/matomo.php?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand")) + .withHeader("User-Agent", equalTo("MatomoJavaClient"))); } @Test @@ -230,20 +237,16 @@ void createPiwikTrackerWithHostUrlAndProxyHostAndPort(WireMockRuntimeInfo wireMo PiwikTracker piwikTracker = new PiwikTracker(wireMockRuntimeInfo.getHttpBaseUrl() + "/matomo.php", "localhost", 8080); - assertThatThrownBy(() -> piwikTracker.sendRequest(request)) - .isInstanceOf(MatomoException.class) - ; - + assertThatThrownBy(() -> piwikTracker.sendRequest(request)).isInstanceOf(MatomoException.class); } @Test - void createPiwikTrackerWithHostUrlAndProxyHostAndPortAndTimeout(WireMockRuntimeInfo wireMockRuntimeInfo) { + void createPiwikTrackerWithHostUrlAndProxyHostAndPortAndTimeout( + WireMockRuntimeInfo wireMockRuntimeInfo) { PiwikTracker piwikTracker = - new PiwikTracker(wireMockRuntimeInfo.getHttpBaseUrl() + "/matomo.php", "localhost", 8080, 1000); + new PiwikTracker( + wireMockRuntimeInfo.getHttpBaseUrl() + "/matomo.php", "localhost", 8080, 1000); - assertThatThrownBy(() -> piwikTracker.sendRequest(request)) - .isInstanceOf(MatomoException.class) - ; + assertThatThrownBy(() -> piwikTracker.sendRequest(request)).isInstanceOf(MatomoException.class); } - } diff --git a/java8/pom.xml b/java8/pom.xml index 4b4621ad..fba1ad81 100644 --- a/java8/pom.xml +++ b/java8/pom.xml @@ -1,15 +1,16 @@ + 4.0.0 org.piwik.java.tracking matomo-java-tracker-parent - 3.4.1-SNAPSHOT + 3.5.0-SNAPSHOT ../pom.xml matomo-java-tracker - 3.4.1-SNAPSHOT + 3.5.0-SNAPSHOT jar Matomo Java Tracker Java 8 diff --git a/java8/src/main/java/org/matomo/java/tracking/Java8Sender.java b/java8/src/main/java/org/matomo/java/tracking/Java8Sender.java index 9aca209c..d0a4cc85 100644 --- a/java8/src/main/java/org/matomo/java/tracking/Java8Sender.java +++ b/java8/src/main/java/org/matomo/java/tracking/Java8Sender.java @@ -40,14 +40,15 @@ import lombok.extern.slf4j.Slf4j; /** - * A {@link Sender} implementation that uses Java 8 {@link HttpURLConnection} to send requests to the Matomo. + * A {@link Sender} implementation that uses Java 8 {@link HttpURLConnection} to send requests to + * the Matomo. * - *

This implementation uses a thread pool to send requests asynchronously. The thread pool is configured using - * {@link TrackerConfiguration#getThreadPoolSize()}. The thread pool uses daemon threads. This means that the JVM will - * exit even if the thread pool is not shut down. + *

This implementation uses a thread pool to send requests asynchronously. The thread pool is + * configured using {@link TrackerConfiguration#getThreadPoolSize()}. The thread pool uses daemon + * threads. This means that the JVM will exit even if the thread pool is not shut down. * - *

If you use a newer Java version, please use the newer Java implementation from the Matomo Java Tracker for - * Java 11. + *

If you use a newer Java version, please use the newer Java implementation from the Matomo Java + * Tracker for Java 11. */ @Slf4j @RequiredArgsConstructor @@ -64,27 +65,30 @@ class Java8Sender implements Sender { @Override @NonNull - public CompletableFuture sendSingleAsync( - @NonNull MatomoRequest request - ) { - return CompletableFuture.supplyAsync(() -> { - sendSingle(request); - return request; - }, executorService); + public CompletableFuture sendSingleAsync(@NonNull MatomoRequest request) { + return CompletableFuture.supplyAsync( + () -> { + sendSingle(request); + return request; + }, + executorService); } @Override - public void sendSingle( - @NonNull MatomoRequest request - ) { + public void sendSingle(@NonNull MatomoRequest request) { String authToken = AuthToken.determineAuthToken(null, singleton(request), trackerConfiguration); RequestValidator.validate(request, authToken); HttpURLConnection connection; URI apiEndpoint = trackerConfiguration.getApiEndpoint(); try { - connection = openConnection(apiEndpoint - .resolve(String.format("%s?%s", apiEndpoint.getPath(), queryCreator.createQuery(request, authToken))) - .toURL()); + connection = + openConnection( + apiEndpoint + .resolve( + String.format( + "%s?%s", + apiEndpoint.getPath(), queryCreator.createQuery(request, authToken))) + .toURL()); } catch (MalformedURLException e) { throw new InvalidUrlException(e); } @@ -106,7 +110,8 @@ public void sendSingle( private HttpURLConnection openConnection(URL url) { HttpURLConnection connection; try { - if (isEmpty(trackerConfiguration.getProxyHost()) || trackerConfiguration.getProxyPort() <= 0) { + if (isEmpty(trackerConfiguration.getProxyHost()) + || trackerConfiguration.getProxyPort() <= 0) { log.debug("Proxy host or proxy port not configured. Will create connection without proxy"); connection = (HttpURLConnection) url.openConnection(); } else { @@ -132,22 +137,25 @@ private void applyTrackerConfiguration(HttpURLConnection connection) { } private void setUserAgentProperty( - @NonNull HttpURLConnection connection, @Nullable String headerUserAgent, @Nullable Map headers - ) { + @NonNull HttpURLConnection connection, + @Nullable String headerUserAgent, + @Nullable Map headers) { String userAgentHeader = null; if ((headerUserAgent == null || headerUserAgent.trim().isEmpty()) && headers != null) { TreeMap caseInsensitiveMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); caseInsensitiveMap.putAll(headers); userAgentHeader = caseInsensitiveMap.get("User-Agent"); } - if ((userAgentHeader == null || userAgentHeader.trim().isEmpty()) && ( - headerUserAgent == null || headerUserAgent.trim().isEmpty()) - && trackerConfiguration.getUserAgent() != null && !trackerConfiguration.getUserAgent().isEmpty()) { + if ((userAgentHeader == null || userAgentHeader.trim().isEmpty()) + && (headerUserAgent == null || headerUserAgent.trim().isEmpty()) + && trackerConfiguration.getUserAgent() != null + && !trackerConfiguration.getUserAgent().isEmpty()) { connection.setRequestProperty("User-Agent", trackerConfiguration.getUserAgent()); } } - private void addHeaders(@NonNull HttpURLConnection connection, @Nullable Map headers) { + private void addHeaders( + @NonNull HttpURLConnection connection, @Nullable Map headers) { if (headers != null) { for (Map.Entry header : headers.entrySet()) { connection.setRequestProperty(header.getKey(), header.getValue()); @@ -156,8 +164,7 @@ private void addHeaders(@NonNull HttpURLConnection connection, @Nullable Map cookies - ) { + HttpURLConnection connection, String sessionId, Map cookies) { StringBuilder cookiesValue = new StringBuilder(); if (sessionId != null && !sessionId.isEmpty()) { cookiesValue.append("MATOMO_SESSID=").append(sessionId); @@ -166,7 +173,8 @@ private static void addCookies( } } if (cookies != null) { - for (Iterator> iterator = cookies.entrySet().iterator(); iterator.hasNext(); ) { + for (Iterator> iterator = cookies.entrySet().iterator(); + iterator.hasNext(); ) { Map.Entry entry = iterator.next(); cookiesValue.append(entry.getKey()).append("=").append(entry.getValue()); if (iterator.hasNext()) { @@ -185,38 +193,39 @@ private void checkResponse(HttpURLConnection connection) throws IOException { if (trackerConfiguration.isLogFailedTracking()) { log.error("Received HTTP error code {} for URL {}", responseCode, connection.getURL()); } - throw new MatomoException(String.format("Tracking endpoint responded with code %d", responseCode)); + throw new MatomoException( + String.format("Tracking endpoint responded with code %d", responseCode)); } } - private static boolean isEmpty( - @Nullable String str - ) { + private static boolean isEmpty(@Nullable String str) { return str == null || str.isEmpty() || str.trim().isEmpty(); } - private HttpURLConnection openProxiedConnection( - @NonNull @lombok.NonNull URL url - ) throws IOException { + private HttpURLConnection openProxiedConnection(@NonNull @lombok.NonNull URL url) + throws IOException { requireNonNull(trackerConfiguration.getProxyHost(), "Proxy host must not be null"); if (trackerConfiguration.getProxyPort() <= 0) { throw new IllegalArgumentException("Proxy port must be configured"); } InetSocketAddress proxyAddress = - new InetSocketAddress(trackerConfiguration.getProxyHost(), trackerConfiguration.getProxyPort()); + new InetSocketAddress( + trackerConfiguration.getProxyHost(), trackerConfiguration.getProxyPort()); Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyAddress); - if (!isEmpty(trackerConfiguration.getProxyUsername()) && !isEmpty(trackerConfiguration.getProxyPassword())) { - Authenticator.setDefault(new ProxyAuthenticator(trackerConfiguration.getProxyUsername(), - trackerConfiguration.getProxyPassword() - )); + if (!isEmpty(trackerConfiguration.getProxyUsername()) + && !isEmpty(trackerConfiguration.getProxyPassword())) { + Authenticator.setDefault( + new ProxyAuthenticator( + trackerConfiguration.getProxyUsername(), trackerConfiguration.getProxyPassword())); } - log.debug("Using proxy {} on port {}", trackerConfiguration.getProxyHost(), trackerConfiguration.getProxyPort()); + log.debug( + "Using proxy {} on port {}", + trackerConfiguration.getProxyHost(), + trackerConfiguration.getProxyPort()); return (HttpURLConnection) url.openConnection(proxy); } - private void applySslConfiguration( - @NonNull @lombok.NonNull HttpsURLConnection connection - ) { + private void applySslConfiguration(@NonNull @lombok.NonNull HttpsURLConnection connection) { if (trackerConfiguration.isDisableSslCertValidation()) { try { SSLContext sslContext = SSLContext.getInstance("SSL"); @@ -233,9 +242,10 @@ private void applySslConfiguration( @Override public void sendBulk( - @NonNull @lombok.NonNull Iterable requests, @Nullable String overrideAuthToken - ) { - String authToken = AuthToken.determineAuthToken(overrideAuthToken, requests, trackerConfiguration); + @NonNull @lombok.NonNull Iterable requests, + @Nullable String overrideAuthToken) { + String authToken = + AuthToken.determineAuthToken(overrideAuthToken, requests, trackerConfiguration); Collection queries = new ArrayList<>(); Map headers = new LinkedHashMap<>(); String headerUserAgent = null; @@ -246,10 +256,9 @@ public void sendBulk( if (request.getHeaders() != null && !request.getHeaders().isEmpty()) { headers.putAll(request.getHeaders()); } - if (headerUserAgent == null && request.getHeaderUserAgent() != null && !request - .getHeaderUserAgent() - .trim() - .isEmpty()) { + if (headerUserAgent == null + && request.getHeaderUserAgent() != null + && !request.getHeaderUserAgent().trim().isEmpty()) { headerUserAgent = request.getHeaderUserAgent(); } queries.add(queryCreator.createQuery(request, null)); @@ -269,8 +278,7 @@ private void sendBulk( Map headers, String headerUserAgent, String sessionId, - Map cookies - ) { + Map cookies) { if (queries.isEmpty()) { throw new IllegalArgumentException("Queries must not be empty"); } @@ -285,12 +293,14 @@ private void sendBulk( setUserAgentProperty(connection, headerUserAgent, headers); addHeaders(connection, headers); addCookies(connection, sessionId, cookies); - log.debug("Sending bulk request using URI {} asynchronously", trackerConfiguration.getApiEndpoint()); + log.debug( + "Sending bulk request using URI {} asynchronously", trackerConfiguration.getApiEndpoint()); OutputStream outputStream = null; try { connection.connect(); outputStream = connection.getOutputStream(); - outputStream.write(BulkRequest.builder().queries(queries).authToken(authToken).build().toBytes()); + outputStream.write( + BulkRequest.builder().queries(queries).authToken(authToken).build().toBytes()); outputStream.flush(); checkResponse(connection); } catch (IOException e) { @@ -316,15 +326,14 @@ private static void preparePostConnection(HttpURLConnection connection) { connection.setDoOutput(true); connection.setRequestProperty("Accept", "*/*"); connection.setRequestProperty("Content-Type", "application/json"); - } @Override @NonNull public CompletableFuture sendBulkAsync( - @NonNull Collection requests, @Nullable String overrideAuthToken - ) { - String authToken = AuthToken.determineAuthToken(overrideAuthToken, requests, trackerConfiguration); + @NonNull Collection requests, @Nullable String overrideAuthToken) { + String authToken = + AuthToken.determineAuthToken(overrideAuthToken, requests, trackerConfiguration); Map headers = new LinkedHashMap<>(); String headerUserAgent = findHeaderUserAgent(requests); String sessionId = findSessionId(requests); @@ -337,8 +346,8 @@ public CompletableFuture sendBulkAsync( } queries.add(queryCreator.createQuery(request, null)); } - return CompletableFuture.supplyAsync(() -> - sendBulkAsync(queries, authToken, headers, headerUserAgent, sessionId, cookies), + return CompletableFuture.supplyAsync( + () -> sendBulkAsync(queries, authToken, headers, headerUserAgent, sessionId, cookies), executorService); } @@ -349,8 +358,7 @@ private Void sendBulkAsync( Map headers, String headerUserAgent, String sessionId, - Map cookies - ) { + Map cookies) { sendBulk(queries, authToken, headers, headerUserAgent, sessionId, cookies); return null; } diff --git a/java8/src/main/java/org/matomo/java/tracking/Java8SenderProvider.java b/java8/src/main/java/org/matomo/java/tracking/Java8SenderProvider.java index 0a3b40bf..1a62ffcb 100644 --- a/java8/src/main/java/org/matomo/java/tracking/Java8SenderProvider.java +++ b/java8/src/main/java/org/matomo/java/tracking/Java8SenderProvider.java @@ -2,19 +2,16 @@ import java.util.concurrent.Executors; -/** - * Provides a {@link Sender} implementation based on Java 8. - */ +/** Provides a {@link Sender} implementation based on Java 8. */ public class Java8SenderProvider implements SenderProvider { @Override public Sender provideSender( - TrackerConfiguration trackerConfiguration, QueryCreator queryCreator - ) { + TrackerConfiguration trackerConfiguration, QueryCreator queryCreator) { return new Java8Sender( trackerConfiguration, queryCreator, - Executors.newFixedThreadPool(trackerConfiguration.getThreadPoolSize(), new DaemonThreadFactory()) - ); + Executors.newFixedThreadPool( + trackerConfiguration.getThreadPoolSize(), new DaemonThreadFactory())); } } diff --git a/java8/src/main/java/org/matomo/java/tracking/TrustingHostnameVerifier.java b/java8/src/main/java/org/matomo/java/tracking/TrustingHostnameVerifier.java index 341487d6..1bba8314 100644 --- a/java8/src/main/java/org/matomo/java/tracking/TrustingHostnameVerifier.java +++ b/java8/src/main/java/org/matomo/java/tracking/TrustingHostnameVerifier.java @@ -7,12 +7,7 @@ class TrustingHostnameVerifier implements HostnameVerifier { @Override - public boolean verify( - @Nullable - String hostname, - @Nullable - SSLSession session - ) { + public boolean verify(@Nullable String hostname, @Nullable SSLSession session) { return true; } } diff --git a/java8/src/test/java/org/matomo/java/tracking/Java8SenderIT.java b/java8/src/test/java/org/matomo/java/tracking/Java8SenderIT.java index dcaeafa4..56bd3eb1 100644 --- a/java8/src/test/java/org/matomo/java/tracking/Java8SenderIT.java +++ b/java8/src/test/java/org/matomo/java/tracking/Java8SenderIT.java @@ -45,15 +45,14 @@ void sendSingleFailsIfQueryIsMalformed() { .hasRootCause(new MalformedURLException("unknown protocol: telnet")); } - @Test void failsIfEndpointReturnsNotFound() { - trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create(wireMockServer.baseUrl())) - .disableSslHostVerification(true) - .disableSslCertValidation(true) - .build(); + trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create(wireMockServer.baseUrl())) + .disableSslHostVerification(true) + .disableSslCertValidation(true) + .build(); givenSender(); @@ -76,14 +75,14 @@ void failsIfCouldNotConnectToEndpoint() { @Test void connectsViaProxy() { - trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create(wireMockServer.baseUrl())) - .disableSslCertValidation(true) - .disableSslHostVerification(true) - .proxyHost("localhost") - .proxyPort(wireMockServer.port()) - .build(); + trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create(wireMockServer.baseUrl())) + .disableSslCertValidation(true) + .disableSslHostVerification(true) + .proxyHost("localhost") + .proxyPort(wireMockServer.port()) + .build(); givenSender(); @@ -94,16 +93,16 @@ void connectsViaProxy() { @Test void connectsViaProxyWithProxyUserNameAndPassword() { - trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create(wireMockServer.baseUrl())) - .disableSslCertValidation(true) - .disableSslHostVerification(true) - .proxyHost("localhost") - .proxyPort(wireMockServer.port()) - .proxyUsername("user") - .proxyPassword("password") - .build(); + trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create(wireMockServer.baseUrl())) + .disableSslCertValidation(true) + .disableSslHostVerification(true) + .proxyHost("localhost") + .proxyPort(wireMockServer.port()) + .proxyUsername("user") + .proxyPassword("password") + .build(); givenSender(); @@ -114,13 +113,13 @@ void connectsViaProxyWithProxyUserNameAndPassword() { @Test void logsFailedTracking() { - trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create(wireMockServer.baseUrl())) - .disableSslCertValidation(true) - .disableSslHostVerification(true) - .logFailedTracking(true) - .build(); + trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create(wireMockServer.baseUrl())) + .disableSslCertValidation(true) + .disableSslHostVerification(true) + .logFailedTracking(true) + .build(); givenSender(); @@ -132,119 +131,102 @@ void logsFailedTracking() { @Test void skipSslCertificationValidation() { wireMockServer.stubFor(get(urlPathEqualTo("/matomo_ssl.php")).willReturn(status(204))); - trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create(String.format( - "https://localhost:%d/matomo_ssl.php", - wireMockServer.httpsPort() - ))) - .disableSslCertValidation(true) - .disableSslHostVerification(true) - .build(); + trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint( + URI.create( + String.format( + "https://localhost:%d/matomo_ssl.php", wireMockServer.httpsPort()))) + .disableSslCertValidation(true) + .disableSslHostVerification(true) + .build(); givenSender(); sender.sendSingle(MatomoRequests.pageView("Join Us").build()); wireMockServer.verify(getRequestedFor(urlPathEqualTo("/matomo_ssl.php"))); - } @Test void addsHeadersToSingleRequest() { wireMockServer.stubFor(get(urlPathEqualTo("/matomo.php")).willReturn(status(204))); - trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create(String.format( - "http://localhost:%d/matomo.php", - wireMockServer.port() - ))) - .disableSslCertValidation(true) - .disableSslHostVerification(true) - .build(); + trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint( + URI.create(String.format("http://localhost:%d/matomo.php", wireMockServer.port()))) + .disableSslCertValidation(true) + .disableSslHostVerification(true) + .build(); givenSender(); - sender.sendSingle(MatomoRequests - .action("http://localhost/example", ActionType.LINK) - .headers(singletonMap( - "headerName", - "headerValue" - )) - .build()); - - wireMockServer.verify(getRequestedFor(urlPathEqualTo("/matomo.php")).withHeader( - "headerName", - equalTo("headerValue") - )); + sender.sendSingle( + MatomoRequests.action("http://localhost/example", ActionType.LINK) + .headers(singletonMap("headerName", "headerValue")) + .build()); + wireMockServer.verify( + getRequestedFor(urlPathEqualTo("/matomo.php")) + .withHeader("headerName", equalTo("headerValue"))); } @Test void addsHeadersToBulkRequest() { wireMockServer.stubFor(post(urlPathEqualTo("/matomo.php")).willReturn(status(204))); - trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create(String.format( - "http://localhost:%d/matomo.php", - wireMockServer.port() - ))) - .disableSslCertValidation(true) - .disableSslHostVerification(true) - .build(); + trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint( + URI.create(String.format("http://localhost:%d/matomo.php", wireMockServer.port()))) + .disableSslCertValidation(true) + .disableSslHostVerification(true) + .build(); givenSender(); sender.sendBulk( - singleton(MatomoRequests.ecommerceCartUpdate(50.0).goalId(0) - .headers(singletonMap("headerName", "headerValue")) - .build()), - null - ); - - wireMockServer.verify(postRequestedFor(urlPathEqualTo("/matomo.php")).withHeader( - "headerName", - equalTo("headerValue") - )); - + singleton( + MatomoRequests.ecommerceCartUpdate(50.0) + .goalId(0) + .headers(singletonMap("headerName", "headerValue")) + .build()), + null); + + wireMockServer.verify( + postRequestedFor(urlPathEqualTo("/matomo.php")) + .withHeader("headerName", equalTo("headerValue"))); } - @Test void addsHeadersToBulkAsyncRequest() { wireMockServer.stubFor(post(urlPathEqualTo("/matomo.php")).willReturn(status(204))); - trackerConfiguration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create(String.format( - "http://localhost:%d/matomo.php", - wireMockServer.port() - ))) - .disableSslCertValidation(true) - .disableSslHostVerification(true) - .build(); + trackerConfiguration = + TrackerConfiguration.builder() + .apiEndpoint( + URI.create(String.format("http://localhost:%d/matomo.php", wireMockServer.port()))) + .disableSslCertValidation(true) + .disableSslHostVerification(true) + .build(); givenSender(); - CompletableFuture future = sender.sendBulkAsync(singleton(MatomoRequest - .request() - .headers(singletonMap("headerName", "headerValue")) - .build()), null); + CompletableFuture future = + sender.sendBulkAsync( + singleton( + MatomoRequest.request().headers(singletonMap("headerName", "headerValue")).build()), + null); future.join(); - wireMockServer.verify(postRequestedFor(urlPathEqualTo("/matomo.php")).withHeader( - "headerName", - equalTo("headerValue") - )); - + wireMockServer.verify( + postRequestedFor(urlPathEqualTo("/matomo.php")) + .withHeader("headerName", equalTo("headerValue"))); } - private void givenSender() { - sender = new Java8Sender( - trackerConfiguration, - new QueryCreator(trackerConfiguration), - Executors.newFixedThreadPool(2, new DaemonThreadFactory()) - ); + sender = + new Java8Sender( + trackerConfiguration, + new QueryCreator(trackerConfiguration), + Executors.newFixedThreadPool(2, new DaemonThreadFactory())); } - } diff --git a/java8/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java b/java8/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java index 04500061..3cedbebe 100644 --- a/java8/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java +++ b/java8/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java @@ -47,12 +47,13 @@ class MatomoTrackerIT { private static final int SITE_ID = 42; - private final TrackerConfigurationBuilder trackerConfigurationBuilder = TrackerConfiguration.builder(); + private final TrackerConfigurationBuilder trackerConfigurationBuilder = + TrackerConfiguration.builder(); - private final MatomoRequestBuilder requestBuilder = MatomoRequest - .builder() - .visitorId(VisitorId.fromHex("bbccddeeff1122")) - .randomValue(RandomValue.fromString("someRandom")); + private final MatomoRequestBuilder requestBuilder = + MatomoRequest.builder() + .visitorId(VisitorId.fromHex("bbccddeeff1122")) + .randomValue(RandomValue.fromString("someRandom")); private CompletableFuture future; @@ -80,12 +81,13 @@ void closeTracker() throws Exception { @Test void requiresSiteId() { - trackerConfigurationBuilder.apiEndpoint(URI.create(wireMockServer.baseUrl() + "/matomo.php")).build(); + trackerConfigurationBuilder + .apiEndpoint(URI.create(wireMockServer.baseUrl() + "/matomo.php")) + .build(); assertThatThrownBy(this::whenSendsRequestAsync) .isInstanceOf(IllegalArgumentException.class) .hasMessage("No default site ID and no request site ID is given"); - } private void whenSendsRequestAsync() { @@ -101,7 +103,6 @@ void usesDefaultSiteId() { whenSendsRequestAsync(); thenGetsRequest("idsite=42&rec=1&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom"); - } private void givenTrackerConfigurationWithDefaultSiteId() { @@ -111,12 +112,14 @@ private void givenTrackerConfigurationWithDefaultSiteId() { } private void thenGetsRequest(String expectedQuery) { - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - wireMockServer.verify(getRequestedFor(urlEqualTo( - String.format("/matomo.php?%s", expectedQuery))).withHeader("User-Agent", - equalTo("MatomoJavaClient") - )); - }); + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + wireMockServer.verify( + getRequestedFor(urlEqualTo(String.format("/matomo.php?%s", expectedQuery))) + .withHeader("User-Agent", equalTo("MatomoJavaClient"))); + }); } @Test @@ -128,7 +131,6 @@ void overridesDefaultSiteId() { whenSendsRequestAsync(); thenGetsRequest("rec=1&idsite=123&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom"); - } @Test @@ -145,7 +147,6 @@ void validatesTokenAuth() { .havingRootCause() .isInstanceOf(IllegalArgumentException.class) .withMessage("Auth token must be exactly 32 characters long"); - } @Test @@ -156,8 +157,8 @@ void convertsTrueBooleanTo1() { whenSendsRequestAsync(); - thenGetsRequest("idsite=42&rec=1&apiv=1&_id=00bbccddeeff1122&fla=1&send_image=0&rand=someRandom"); - + thenGetsRequest( + "idsite=42&rec=1&apiv=1&_id=00bbccddeeff1122&fla=1&send_image=0&rand=someRandom"); } @Test @@ -168,8 +169,8 @@ void convertsFalseBooleanTo0() { whenSendsRequestAsync(); - thenGetsRequest("idsite=42&rec=1&apiv=1&_id=00bbccddeeff1122&java=0&send_image=0&rand=someRandom"); - + thenGetsRequest( + "idsite=42&rec=1&apiv=1&_id=00bbccddeeff1122&java=0&send_image=0&rand=someRandom"); } @Test @@ -182,7 +183,6 @@ void encodesUrl() { thenGetsRequest( "idsite=42&rec=1&url=https%3A%2F%2Fwww.daniel-heid.de%2Fsome%2Fpage%3Ffoo%3Dbar&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom"); - } @Test @@ -195,7 +195,6 @@ void encodesReferrerUrl() { thenGetsRequest( "idsite=42&rec=1&apiv=1&_id=00bbccddeeff1122&urlref=https%3A%2F%2Fwww.daniel-heid.de%2Fsome%2Freferrer%3Ffoo2%3Dbar2&send_image=0&rand=someRandom"); - } @Test @@ -208,9 +207,7 @@ void encodesLink() { thenPostsRequestWithoutAuthToken( "idsite=42&rec=1&apiv=1&_id=00bbccddeeff1122&link=https%3A%2F%2Fwww.daniel-heid.de%2Fsome%2Fexternal%2Flink%23&send_image=0&rand=someRandom", - "156" - ); - + "156"); } @Test @@ -221,25 +218,29 @@ void sendsRequestsBulkAsynchronously() { future = matomoTracker.sendBulkRequestAsync(requestBuilder.build()); - thenPostsRequestWithoutAuthToken("idsite=42&rec=1&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom", "90"); - + thenPostsRequestWithoutAuthToken( + "idsite=42&rec=1&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom", "90"); } private void whenSendsBulkRequestAsync() { future = - new MatomoTracker(trackerConfigurationBuilder.build()).sendBulkRequestAsync(singleton(requestBuilder.build())); + new MatomoTracker(trackerConfigurationBuilder.build()) + .sendBulkRequestAsync(singleton(requestBuilder.build())); } private void thenPostsRequestWithoutAuthToken(String expectedQuery, String contentLength) { - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - wireMockServer.verify(postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo(contentLength)) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody(equalToJson("{\"requests\":[\"?" + expectedQuery + "\"]}"))); - }); - + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + wireMockServer.verify( + postRequestedFor(urlEqualTo("/matomo.php")) + .withHeader("Content-Length", equalTo(contentLength)) + .withHeader("Accept", equalTo("*/*")) + .withHeader("Content-Type", equalTo("application/json")) + .withHeader("User-Agent", equalTo("MatomoJavaClient")) + .withRequestBody(equalToJson("{\"requests\":[\"?" + expectedQuery + "\"]}"))); + }); } @Test @@ -252,9 +253,7 @@ void encodesDownloadUrl() { thenPostsRequestWithoutAuthToken( "idsite=42&rec=1&apiv=1&_id=00bbccddeeff1122&download=https%3A%2F%2Fwww.daniel-heid.de%2Fsome%2Fdownload.pdf&send_image=0&rand=someRandom", - "154" - ); - + "154"); } @Test @@ -264,12 +263,14 @@ void getContainsHeaders() { whenSendsRequestAsync(); - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - wireMockServer.verify(getRequestedFor(urlPathEqualTo("/matomo.php")).withHeader("User-Agent", - equalTo("MatomoJavaClient") - )); - }); - + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + wireMockServer.verify( + getRequestedFor(urlPathEqualTo("/matomo.php")) + .withHeader("User-Agent", equalTo("MatomoJavaClient"))); + }); } @Test @@ -279,14 +280,17 @@ void postContainsHeaders() { whenSendsBulkRequestAsync(); - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - wireMockServer.verify(postRequestedFor(urlPathEqualTo("/matomo.php")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Length", equalTo("90")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient"))); - }); - + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + wireMockServer.verify( + postRequestedFor(urlPathEqualTo("/matomo.php")) + .withHeader("Accept", equalTo("*/*")) + .withHeader("Content-Length", equalTo("90")) + .withHeader("Content-Type", equalTo("application/json")) + .withHeader("User-Agent", equalTo("MatomoJavaClient"))); + }); } @Test @@ -297,12 +301,14 @@ void allowsToOverrideUserAgent() { whenSendsRequestAsync(); - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - wireMockServer.verify(getRequestedFor(urlPathEqualTo("/matomo.php")).withHeader("User-Agent", - equalTo("Mozilla/5.0") - )); - }); - + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + wireMockServer.verify( + getRequestedFor(urlPathEqualTo("/matomo.php")) + .withHeader("User-Agent", equalTo("Mozilla/5.0"))); + }); } @Test @@ -314,43 +320,57 @@ void tracksMinimalRequest() { .actionUrl("https://www.daniel-heid.de/portfolio") .visitorId(VisitorId.fromHash(3434343434343434343L)) .referrerUrl("https://www.daniel-heid.de/referrer") - .visitCustomVariables(new CustomVariables() - .add(new CustomVariable("customVariable1Key", "customVariable1Value"), 4) - .add(new CustomVariable("customVariable2Key", "customVariable2Value"), 5)) + .visitCustomVariables( + new CustomVariables() + .add(new CustomVariable("customVariable1Key", "customVariable1Value"), 4) + .add(new CustomVariable("customVariable2Key", "customVariable2Value"), 5)) .visitorVisitCount(2) - .visitorFirstVisitTimestamp(LocalDateTime.of(2022, 8, 9, 18, 34, 12).toInstant(ZoneOffset.UTC)) + .visitorFirstVisitTimestamp( + LocalDateTime.of(2022, 8, 9, 18, 34, 12).toInstant(ZoneOffset.UTC)) .deviceResolution(DeviceResolution.builder().width(1024).height(768).build()) - .headerAcceptLanguage(AcceptLanguage - .builder() - .languageRange(new LanguageRange("de")) - .languageRange(new LanguageRange("de-DE", 0.9)) - .languageRange(new LanguageRange("en", 0.8)) - .build()) + .headerAcceptLanguage( + AcceptLanguage.builder() + .languageRange(new LanguageRange("de")) + .languageRange(new LanguageRange("de-DE", 0.9)) + .languageRange(new LanguageRange("en", 0.8)) + .build()) .pageViewId(UniqueId.fromValue(999999999999999999L)) .goalId(0) .ecommerceRevenue(12.34) - .ecommerceItems(EcommerceItems - .builder() - .item(org.matomo.java.tracking.parameters.EcommerceItem.builder().sku("SKU").build()) - .item(EcommerceItem.builder().sku("SKU").name("NAME").category("CATEGORY").price(123.4).build()) - .build()) + .ecommerceItems( + EcommerceItems.builder() + .item( + org.matomo.java.tracking.parameters.EcommerceItem.builder().sku("SKU").build()) + .item( + EcommerceItem.builder() + .sku("SKU") + .name("NAME") + .category("CATEGORY") + .price(123.4) + .build()) + .build()) .authToken("fdf6e8461ea9de33176b222519627f78") - .visitorCountry(Country.fromLanguageRanges("en-GB;q=0.7,de,de-DE;q=0.9,en;q=0.8,en-US;q=0.6")); + .visitorCountry( + Country.fromLanguageRanges("en-GB;q=0.7,de,de-DE;q=0.9,en;q=0.8,en-US;q=0.6")); whenSendsBulkRequestAsync(); - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - wireMockServer.verify(postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("711")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody(equalToJson("{\"requests\":[\"?" - + "idsite=42&rec=1&action_name=Help+%2F+Feedback&url=https%3A%2F%2Fwww.daniel-heid.de%2Fportfolio&apiv=1&_id=2fa93d2858bc4867&urlref=https%3A%2F%2Fwww.daniel-heid.de%2Freferrer&_cvar=%7B%224%22%3A%5B%22customVariable1Key%22%2C%22customVariable1Value%22%5D%2C%225%22%3A%5B%22customVariable2Key%22%2C%22customVariable2Value%22%5D%7D&_idvc=2&_idts=1660070052&res=1024x768&lang=de%2Cde-de%3Bq%3D0.9%2Cen%3Bq%3D0.8&pv_id=lbBbxG&idgoal=0&revenue=12.34&ec_items=%5B%5B%22SKU%22%2C%22%22%2C%22%22%2C0.0%2C0%5D%2C%5B%22SKU%22%2C%22NAME%22%2C%22CATEGORY%22%2C123.4%2C0%5D%5D&token_auth=fdf6e8461ea9de33176b222519627f78&country=de&send_image=0&rand=someRandom" - + "\"],\"token_auth\" : \"" + "fdf6e8461ea9de33176b222519627f78" + "\"}"))); - - }); - + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + wireMockServer.verify( + postRequestedFor(urlEqualTo("/matomo.php")) + .withHeader("Content-Length", equalTo("711")) + .withHeader("Accept", equalTo("*/*")) + .withHeader("Content-Type", equalTo("application/json")) + .withHeader("User-Agent", equalTo("MatomoJavaClient")) + .withRequestBody( + equalToJson( + "{\"requests\":[\"?" + + "idsite=42&rec=1&action_name=Help+%2F+Feedback&url=https%3A%2F%2Fwww.daniel-heid.de%2Fportfolio&apiv=1&_id=2fa93d2858bc4867&urlref=https%3A%2F%2Fwww.daniel-heid.de%2Freferrer&_cvar=%7B%224%22%3A%5B%22customVariable1Key%22%2C%22customVariable1Value%22%5D%2C%225%22%3A%5B%22customVariable2Key%22%2C%22customVariable2Value%22%5D%7D&_idvc=2&_idts=1660070052&res=1024x768&lang=de%2Cde-de%3Bq%3D0.9%2Cen%3Bq%3D0.8&pv_id=lbBbxG&idgoal=0&revenue=12.34&ec_items=%5B%5B%22SKU%22%2C%22%22%2C%22%22%2C0.0%2C0%5D%2C%5B%22SKU%22%2C%22NAME%22%2C%22CATEGORY%22%2C123.4%2C0%5D%5D&token_auth=fdf6e8461ea9de33176b222519627f78&country=de&send_image=0&rand=someRandom\"],\"token_auth\"" + + " : \"fdf6e8461ea9de33176b222519627f78\"}"))); + }); } @Test @@ -364,14 +384,15 @@ void doesNothingIfNotEnabled() throws Exception { future.get(); wireMockServer.verify(0, postRequestedFor(urlPathEqualTo("/matomo.php"))); - } @Test void reportsErrors() { wireMockServer.stubFor(get(urlPathEqualTo("/failing")).willReturn(status(500))); - trackerConfigurationBuilder.apiEndpoint(URI.create(wireMockServer.baseUrl() + "/failing")).defaultSiteId(SITE_ID); + trackerConfigurationBuilder + .apiEndpoint(URI.create(wireMockServer.baseUrl() + "/failing")) + .defaultSiteId(SITE_ID); whenSendsRequestAsync(); @@ -381,7 +402,6 @@ void reportsErrors() { .havingRootCause() .isInstanceOf(MatomoException.class) .withMessage("Tracking endpoint responded with code 500"); - } @Test @@ -392,13 +412,16 @@ void includesDefaultTokenAuth() { whenSendsRequestAsync(); - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - wireMockServer.verify(getRequestedFor(urlEqualTo( - "/matomo.php?idsite=42&token_auth=fdf6e8461ea9de33176b222519627f78&rec=1&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom")).withHeader("User-Agent", - equalTo("MatomoJavaClient") - )); - }); - + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + wireMockServer.verify( + getRequestedFor( + urlEqualTo( + "/matomo.php?idsite=42&token_auth=fdf6e8461ea9de33176b222519627f78&rec=1&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom")) + .withHeader("User-Agent", equalTo("MatomoJavaClient"))); + }); } @Test @@ -407,21 +430,31 @@ void includesMultipleQueriesInBulkRequest() { givenTrackerConfigurationWithDefaultSiteId(); matomoTracker = new MatomoTracker(trackerConfigurationBuilder.build()); - future = matomoTracker.sendBulkRequestAsync(Arrays.asList(requestBuilder.actionName("First").build(), - requestBuilder.actionName("Second").build(), - requestBuilder.actionName("Third").build() - )); - - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - wireMockServer.verify(postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("297")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody(equalToJson( - "{\"requests\" : [ \"?idsite=42&rec=1&action_name=First&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom\", \"?idsite=42&rec=1&action_name=Second&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom\", \"?idsite=42&rec=1&action_name=Third&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom\" ]}"))); - }); + future = + matomoTracker.sendBulkRequestAsync( + Arrays.asList( + requestBuilder.actionName("First").build(), + requestBuilder.actionName("Second").build(), + requestBuilder.actionName("Third").build())); + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + wireMockServer.verify( + postRequestedFor(urlEqualTo("/matomo.php")) + .withHeader("Content-Length", equalTo("297")) + .withHeader("Accept", equalTo("*/*")) + .withHeader("Content-Type", equalTo("application/json")) + .withHeader("User-Agent", equalTo("MatomoJavaClient")) + .withRequestBody( + equalToJson( + "{\"requests\" : [" + + " \"?idsite=42&rec=1&action_name=First&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom\"," + + " \"?idsite=42&rec=1&action_name=Second&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom\"," + + " \"?idsite=42&rec=1&action_name=Third&apiv=1&_id=00bbccddeeff1122&send_image=0&rand=someRandom\"" + + " ]}"))); + }); } @Test @@ -451,7 +484,6 @@ void doesNotSendRequestAsyncIfTrackerConfigurationIsDisabled() throws Exception future.get(); wireMockServer.verify(0, getRequestedFor(urlPathEqualTo("/matomo.php"))); - } @Test @@ -479,7 +511,8 @@ void doesNotSendBulkRequestIfTrackerConfigurationIsDisabled() { } private void whenSendsBulkRequest() { - new MatomoTracker(trackerConfigurationBuilder.build()).sendBulkRequest(singleton(requestBuilder.build())); + new MatomoTracker(trackerConfigurationBuilder.build()) + .sendBulkRequest(singleton(requestBuilder.build())); } @Test @@ -498,13 +531,19 @@ void sendsRequestAsyncAndAcceptsCallback() { givenTrackerConfigurationWithDefaultSiteId(); matomoTracker = new MatomoTracker(trackerConfigurationBuilder.build()); AtomicBoolean success = new AtomicBoolean(); - future = matomoTracker.sendRequestAsync(requestBuilder.build(), request -> { - success.set(true); - return null; - }); - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - wireMockServer.verify(getRequestedFor(urlPathEqualTo("/matomo.php"))); - }); + future = + matomoTracker.sendRequestAsync( + requestBuilder.build(), + request -> { + success.set(true); + return null; + }); + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + wireMockServer.verify(getRequestedFor(urlPathEqualTo("/matomo.php"))); + }); assertThat(success).isTrue(); } @@ -513,13 +552,18 @@ void sendsRequestsAsyncAndAcceptsCallback() { givenTrackerConfigurationWithDefaultSiteId(); matomoTracker = new MatomoTracker(trackerConfigurationBuilder.build()); AtomicBoolean success = new AtomicBoolean(); - future = matomoTracker.sendBulkRequestAsync(singleton(requestBuilder.build()), v -> { - success.set(true); - }); - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - wireMockServer.verify(postRequestedFor(urlPathEqualTo("/matomo.php"))); - }); + future = + matomoTracker.sendBulkRequestAsync( + singleton(requestBuilder.build()), + v -> { + success.set(true); + }); + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + wireMockServer.verify(postRequestedFor(urlPathEqualTo("/matomo.php"))); + }); assertThat(success).isTrue(); } - } diff --git a/java8/src/test/java/org/matomo/java/tracking/PiwikTrackerIT.java b/java8/src/test/java/org/matomo/java/tracking/PiwikTrackerIT.java index 523b9f4a..02c27b45 100644 --- a/java8/src/test/java/org/matomo/java/tracking/PiwikTrackerIT.java +++ b/java8/src/test/java/org/matomo/java/tracking/PiwikTrackerIT.java @@ -33,7 +33,6 @@ class PiwikTrackerIT { private static final WireMockServer wireMockServer = new WireMockServer(WireMockConfiguration.options().dynamicPort()); - private static final int SITE_ID = 42; private PiwikTracker piwikTracker; @@ -56,24 +55,21 @@ void setUp() throws MalformedURLException { request.setVisitorId(VisitorId.fromHash(999999999999999999L)); } - /** - * Test of sendRequest method, of class PiwikTracker. - */ + /** Test of sendRequest method, of class PiwikTracker. */ @Test void testSendRequest() { request.setCustomTrackingParameter("parameterName", "parameterValue"); piwikTracker.sendRequest(request); - wireMockServer.verify(getRequestedFor(urlEqualTo( - "/matomo.php?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue")).withHeader("User-Agent", - equalTo("MatomoJavaClient") - )); + wireMockServer.verify( + getRequestedFor( + urlEqualTo( + "/matomo.php?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue")) + .withHeader("User-Agent", equalTo("MatomoJavaClient"))); } - /** - * Test of sendRequestAsync method, of class PiwikTracker. - */ + /** Test of sendRequestAsync method, of class PiwikTracker. */ @Test void testSendRequestAsync() { request.setCustomTrackingParameter("parameterName", "parameterValue"); @@ -81,19 +77,19 @@ void testSendRequestAsync() { CompletableFuture future = piwikTracker.sendRequestAsync(request); assertThat(future).isNotCompletedExceptionally(); - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - wireMockServer.verify(getRequestedFor(urlEqualTo( - "/matomo.php?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue")) - .withHeader("User-Agent", equalTo("MatomoJavaClient") - )); - }); - + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + wireMockServer.verify( + getRequestedFor( + urlEqualTo( + "/matomo.php?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue")) + .withHeader("User-Agent", equalTo("MatomoJavaClient"))); + }); } - - /** - * Test of sendBulkRequest method, of class PiwikTracker. - */ + /** Test of sendBulkRequest method, of class PiwikTracker. */ @Test void testSendBulkRequest_Iterable() { List requests = Collections.singletonList(request); @@ -101,19 +97,20 @@ void testSendBulkRequest_Iterable() { piwikTracker.sendBulkRequest(requests); - wireMockServer.verify(postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("167")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody(equalToJson( - "{ \"requests\" : [ \"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\" ]}"))); - + wireMockServer.verify( + postRequestedFor(urlEqualTo("/matomo.php")) + .withHeader("Content-Length", equalTo("167")) + .withHeader("Accept", equalTo("*/*")) + .withHeader("Content-Type", equalTo("application/json")) + .withHeader("User-Agent", equalTo("MatomoJavaClient")) + .withRequestBody( + equalToJson( + "{ \"requests\" : [" + + " \"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"" + + " ]}"))); } - /** - * Test of sendBulkRequest method, of class PiwikTracker. - */ + /** Test of sendBulkRequest method, of class PiwikTracker. */ @Test void testSendBulkRequest_Iterable_StringTT() { List requests = Collections.singletonList(request); @@ -131,14 +128,15 @@ void testSendBulkRequest_Iterable_StringFF() { piwikTracker.sendBulkRequest(requests, null); - wireMockServer.verify(postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("167")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody(equalToJson( - "{\"requests\":[\"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"]}"))); - + wireMockServer.verify( + postRequestedFor(urlEqualTo("/matomo.php")) + .withHeader("Content-Length", equalTo("167")) + .withHeader("Accept", equalTo("*/*")) + .withHeader("Content-Type", equalTo("application/json")) + .withHeader("User-Agent", equalTo("MatomoJavaClient")) + .withRequestBody( + equalToJson( + "{\"requests\":[\"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"]}"))); } @Test @@ -148,19 +146,19 @@ void testSendBulkRequest_Iterable_StringFT() { piwikTracker.sendBulkRequest(requests, "12345678901234567890123456789012"); - wireMockServer.verify(postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("215")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody(equalToJson( - "{\"requests\":[\"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\" ],\"token_auth\":\"12345678901234567890123456789012\"}"))); - + wireMockServer.verify( + postRequestedFor(urlEqualTo("/matomo.php")) + .withHeader("Content-Length", equalTo("215")) + .withHeader("Accept", equalTo("*/*")) + .withHeader("Content-Type", equalTo("application/json")) + .withHeader("User-Agent", equalTo("MatomoJavaClient")) + .withRequestBody( + equalToJson( + "{\"requests\":[\"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"" + + " ],\"token_auth\":\"12345678901234567890123456789012\"}"))); } - /** - * Test of sendBulkRequestAsync method, of class PiwikTracker. - */ + /** Test of sendBulkRequestAsync method, of class PiwikTracker. */ @Test void testSendBulkRequestAsync_Iterable() { List requests = Collections.singletonList(request); @@ -168,22 +166,25 @@ void testSendBulkRequestAsync_Iterable() { CompletableFuture future = piwikTracker.sendBulkRequestAsync(requests); - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - wireMockServer.verify(postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("167")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody(equalToJson( - "{\"requests\" : [ \"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\" ]}"))); - - }); - + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + wireMockServer.verify( + postRequestedFor(urlEqualTo("/matomo.php")) + .withHeader("Content-Length", equalTo("167")) + .withHeader("Accept", equalTo("*/*")) + .withHeader("Content-Type", equalTo("application/json")) + .withHeader("User-Agent", equalTo("MatomoJavaClient")) + .withRequestBody( + equalToJson( + "{\"requests\" : [" + + " \"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"" + + " ]}"))); + }); } - /** - * Test of sendBulkRequestAsync method, of class PiwikTracker. - */ + /** Test of sendBulkRequestAsync method, of class PiwikTracker. */ @Test void testSendBulkRequestAsync_Iterable_StringTT() { @@ -193,10 +194,8 @@ void testSendBulkRequestAsync_Iterable_StringTT() { assertThatThrownBy(() -> piwikTracker.sendBulkRequestAsync(requests, "1").get()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Auth token must be exactly 32 characters long"); - } - @Test void testSendBulkRequestAsync_Iterable_String() { @@ -207,16 +206,21 @@ void testSendBulkRequestAsync_Iterable_String() { piwikTracker.sendBulkRequestAsync(requests, "12345678901234567890123456789012"); assertThat(future).isNotCompletedExceptionally(); - assertThat(future).succeedsWithin(1, MINUTES).satisfies(v -> { - wireMockServer.verify(postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("215")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody(equalToJson( - "{\"requests\":[ \"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"],\"token_auth\":\"12345678901234567890123456789012\"}"))); - - }); + assertThat(future) + .succeedsWithin(1, MINUTES) + .satisfies( + v -> { + wireMockServer.verify( + postRequestedFor(urlEqualTo("/matomo.php")) + .withHeader("Content-Length", equalTo("215")) + .withHeader("Accept", equalTo("*/*")) + .withHeader("Content-Type", equalTo("application/json")) + .withHeader("User-Agent", equalTo("MatomoJavaClient")) + .withRequestBody( + equalToJson( + "{\"requests\":[" + + " \"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"],\"token_auth\":\"12345678901234567890123456789012\"}"))); + }); } @Test @@ -225,10 +229,11 @@ void createsPiwikTrackerWithHostUrl() { piwikTracker.sendRequest(request); - wireMockServer.verify(getRequestedFor(urlEqualTo( - "/matomo.php?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand")).withHeader("User-Agent", - equalTo("MatomoJavaClient") - )); + wireMockServer.verify( + getRequestedFor( + urlEqualTo( + "/matomo.php?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand")) + .withHeader("User-Agent", equalTo("MatomoJavaClient"))); } @Test @@ -236,10 +241,7 @@ void createPiwikTrackerWithHostUrlAndProxyHostAndPort() { PiwikTracker piwikTracker = new PiwikTracker(wireMockServer.baseUrl() + "/matomo.php", "localhost", 8080); - assertThatThrownBy(() -> piwikTracker.sendRequest(request)) - .isInstanceOf(MatomoException.class) - ; - + assertThatThrownBy(() -> piwikTracker.sendRequest(request)).isInstanceOf(MatomoException.class); } @Test @@ -247,9 +249,6 @@ void createPiwikTrackerWithHostUrlAndProxyHostAndPortAndTimeout() { PiwikTracker piwikTracker = new PiwikTracker(wireMockServer.baseUrl() + "/matomo.php", "localhost", 8080, 1000); - assertThatThrownBy(() -> piwikTracker.sendRequest(request)) - .isInstanceOf(MatomoException.class) - ; + assertThatThrownBy(() -> piwikTracker.sendRequest(request)).isInstanceOf(MatomoException.class); } - } diff --git a/java8/src/test/java/org/matomo/java/tracking/TrustingHostnameVerifierTest.java b/java8/src/test/java/org/matomo/java/tracking/TrustingHostnameVerifierTest.java index e3e61969..b10a4016 100644 --- a/java8/src/test/java/org/matomo/java/tracking/TrustingHostnameVerifierTest.java +++ b/java8/src/test/java/org/matomo/java/tracking/TrustingHostnameVerifierTest.java @@ -13,5 +13,4 @@ void verifyAlwaysReturnsTrue() { assertThat(verified).isTrue(); } - -} \ No newline at end of file +} diff --git a/pom.xml b/pom.xml index 9e639923..a11d1a70 100644 --- a/pom.xml +++ b/pom.xml @@ -1,9 +1,10 @@ + 4.0.0 org.piwik.java.tracking matomo-java-tracker-parent - 3.4.1-SNAPSHOT + 3.5.0-SNAPSHOT pom Matomo Java Tracker Parent @@ -37,22 +38,32 @@ + + core + java8 + java11 + servlet-jakarta + servlet-javax + spring + test + + scm:git:https://@github.com/matomo-org/matomo-java-tracker.git scm:git:https://github.com/matomo-org/matomo-java-tracker.git - https://github.com/matomo-org/matomo-java-tracker HEAD + https://github.com/matomo-org/matomo-java-tracker - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - ossrh https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + @@ -178,10 +189,10 @@ sign-artifacts - verify sign + verify @@ -229,6 +240,11 @@ org.projectlombok lombok-maven-plugin 1.18.20.0 + + src/main/java + ${delombok.output} + false + org.projectlombok @@ -236,17 +252,12 @@ ${lombok.version} - - src/main/java - ${delombok.output} - false - - generate-sources delombok + generate-sources @@ -342,12 +353,10 @@ - - validate - check + validate @@ -364,6 +373,48 @@ true + + com.diffplug.spotless + spotless-maven-plugin + 2.44.3 + + + + + 1.24.0 + + true + true + + + + + **/*.md + + + + + + pom.xml + */pom.xml + + + false + true + 4 + + + + + + spotless-apply + + apply + + process-sources + + + @@ -384,14 +435,4 @@ - - - core - java8 - java11 - servlet-jakarta - servlet-javax - spring - test - diff --git a/servlet-jakarta/pom.xml b/servlet-jakarta/pom.xml index 0c31328f..35257c65 100644 --- a/servlet-jakarta/pom.xml +++ b/servlet-jakarta/pom.xml @@ -1,15 +1,16 @@ + 4.0.0 org.piwik.java.tracking matomo-java-tracker-parent - 3.4.1-SNAPSHOT + 3.5.0-SNAPSHOT ../pom.xml matomo-java-tracker-servlet-jakarta - 3.4.1-SNAPSHOT + 3.5.0-SNAPSHOT jar Matomo Java Tracker Servlet Jakarta @@ -53,7 +54,7 @@ org.eclipse.jetty.ee10 jetty-ee10-servlet - 12.0.16 + 12.1.8 test diff --git a/servlet-jakarta/src/main/java/org/matomo/java/tracking/servlet/JakartaHttpServletWrapper.java b/servlet-jakarta/src/main/java/org/matomo/java/tracking/servlet/JakartaHttpServletWrapper.java index 11a89de7..596da6d4 100644 --- a/servlet-jakarta/src/main/java/org/matomo/java/tracking/servlet/JakartaHttpServletWrapper.java +++ b/servlet-jakarta/src/main/java/org/matomo/java/tracking/servlet/JakartaHttpServletWrapper.java @@ -9,9 +9,7 @@ import java.util.stream.Stream; import lombok.NonNull; -/** - * Converts a Jakarta {@link HttpServletRequest} to a {@link HttpServletRequestWrapper}. - */ +/** Converts a Jakarta {@link HttpServletRequest} to a {@link HttpServletRequestWrapper}. */ public final class JakartaHttpServletWrapper { private JakartaHttpServletWrapper() { @@ -19,26 +17,29 @@ private JakartaHttpServletWrapper() { } /** - * Takes a Jakarta {@link HttpServletRequest} and converts it to a - * {@link HttpServletRequestWrapper}. + * Takes a Jakarta {@link HttpServletRequest} and converts it to a {@link + * HttpServletRequestWrapper}. * * @param request the request to convert to a wrapper object (must not be {@code null}). * @return the wrapper object (never {@code null}). */ @edu.umd.cs.findbugs.annotations.NonNull - public static HttpServletRequestWrapper fromHttpServletRequest(@NonNull HttpServletRequest request) { + public static HttpServletRequestWrapper fromHttpServletRequest( + @NonNull HttpServletRequest request) { Map headers = new LinkedHashMap<>(); - request.getHeaderNames() - .asIterator() - .forEachRemaining(name -> headers.put(name.toLowerCase(Locale.ROOT), request.getHeader(name))); + request + .getHeaderNames() + .asIterator() + .forEachRemaining( + name -> headers.put(name.toLowerCase(Locale.ROOT), request.getHeader(name))); List cookies = null; if (request.getCookies() != null) { - cookies = Stream.of(request.getCookies()) - .map(cookie -> new CookieWrapper(cookie.getName(), cookie.getValue())) - .collect(Collectors.toList()); + cookies = + Stream.of(request.getCookies()) + .map(cookie -> new CookieWrapper(cookie.getName(), cookie.getValue())) + .collect(Collectors.toList()); } - return HttpServletRequestWrapper - .builder() + return HttpServletRequestWrapper.builder() .requestURL(request.getRequestURL()) .remoteAddr(request.getRemoteAddr()) .remoteUser(request.getRemoteUser()) @@ -46,5 +47,4 @@ public static HttpServletRequestWrapper fromHttpServletRequest(@NonNull HttpServ .cookies(cookies == null ? null : cookies.toArray(new CookieWrapper[0])) .build(); } - } diff --git a/servlet-jakarta/src/main/java/org/matomo/java/tracking/servlet/MatomoTrackerFilter.java b/servlet-jakarta/src/main/java/org/matomo/java/tracking/servlet/MatomoTrackerFilter.java index 11ca4494..58ca7ef0 100644 --- a/servlet-jakarta/src/main/java/org/matomo/java/tracking/servlet/MatomoTrackerFilter.java +++ b/servlet-jakarta/src/main/java/org/matomo/java/tracking/servlet/MatomoTrackerFilter.java @@ -23,9 +23,11 @@ public class MatomoTrackerFilter extends HttpFilter { @Override protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) - throws IOException, ServletException { - MatomoRequest matomoRequest = ServletMatomoRequest - .fromServletRequest(JakartaHttpServletWrapper.fromHttpServletRequest(req)).build(); + throws IOException, ServletException { + MatomoRequest matomoRequest = + ServletMatomoRequest.fromServletRequest( + JakartaHttpServletWrapper.fromHttpServletRequest(req)) + .build(); log.debug("Sending request {}", matomoRequest); tracker.sendRequestAsync(matomoRequest); super.doFilter(req, res, chain); diff --git a/servlet-jakarta/src/test/java/org/matomo/java/tracking/MatomoTrackerFilterIT.java b/servlet-jakarta/src/test/java/org/matomo/java/tracking/MatomoTrackerFilterIT.java index fac0d472..380397f8 100644 --- a/servlet-jakarta/src/test/java/org/matomo/java/tracking/MatomoTrackerFilterIT.java +++ b/servlet-jakarta/src/test/java/org/matomo/java/tracking/MatomoTrackerFilterIT.java @@ -17,17 +17,16 @@ class MatomoTrackerFilterIT { @Test void sendsAnAsyncRequestOnFilter() throws Exception { - TestSenderFactory senderFactory = new TestSenderFactory(); - MatomoTracker tracker = new MatomoTracker( - TrackerConfiguration - .builder() - .apiEndpoint(URI.create("http://localhost:8080/matomo.php")) - .defaultSiteId(1) - .defaultAuthToken("ee6e3dd9ed1b61f5328cf5978b5a8c71") - .logFailedTracking(true) - .build()); + MatomoTracker tracker = + new MatomoTracker( + TrackerConfiguration.builder() + .apiEndpoint(URI.create("http://localhost:8080/matomo.php")) + .defaultSiteId(1) + .defaultAuthToken("ee6e3dd9ed1b61f5328cf5978b5a8c71") + .logFailedTracking(true) + .build()); tracker.setSenderFactory(senderFactory); ServletContextHandler context = new ServletContextHandler(); @@ -38,26 +37,25 @@ void sendsAnAsyncRequestOnFilter() throws Exception { server.start(); URI uri = server.getURI(); - HttpClient.newHttpClient().send( - HttpRequest.newBuilder() - .header("Accept-Language", "en-US,en;q=0.9,de;q=0.8") - .uri(uri) - .build(), - HttpResponse.BodyHandlers.discarding() - ); + HttpClient.newHttpClient() + .send( + HttpRequest.newBuilder() + .header("Accept-Language", "en-US,en;q=0.9,de;q=0.8") + .uri(uri) + .build(), + HttpResponse.BodyHandlers.discarding()); server.stop(); TestSender testSender = senderFactory.getTestSender(); - assertThat(testSender.getRequests()).hasSize(1).satisfiesExactly(matomoRequest -> { - assertThat(matomoRequest.getActionUrl()).isEqualTo(uri.toString()); - assertThat(matomoRequest.getVisitorId()).isNotNull(); - assertThat(matomoRequest.getVisitorIp()).isNotNull(); - assertThat(matomoRequest.getHeaders()).containsEntry( - "accept-language", - "en-US,en;q=0.9,de;q=0.8" - ); - }); - + assertThat(testSender.getRequests()) + .hasSize(1) + .satisfiesExactly( + matomoRequest -> { + assertThat(matomoRequest.getActionUrl()).isEqualTo(uri.toString()); + assertThat(matomoRequest.getVisitorId()).isNotNull(); + assertThat(matomoRequest.getVisitorIp()).isNotNull(); + assertThat(matomoRequest.getHeaders()) + .containsEntry("accept-language", "en-US,en;q=0.9,de;q=0.8"); + }); } - -} \ No newline at end of file +} diff --git a/servlet-jakarta/src/test/java/org/matomo/java/tracking/TestSender.java b/servlet-jakarta/src/test/java/org/matomo/java/tracking/TestSender.java index 14f8cde6..0f9404a3 100644 --- a/servlet-jakarta/src/test/java/org/matomo/java/tracking/TestSender.java +++ b/servlet-jakarta/src/test/java/org/matomo/java/tracking/TestSender.java @@ -11,8 +11,9 @@ /** * A {@link Sender} implementation that does not send anything but stores the requests. * - *

This class is intended for testing purposes only. It does not send anything to the Matomo server. Instead, it - * stores the requests and queries in collections that can be accessed via {@link #getRequests()}. + *

This class is intended for testing purposes only. It does not send anything to the Matomo + * server. Instead, it stores the requests and queries in collections that can be accessed via + * {@link #getRequests()}. */ @RequiredArgsConstructor @Getter @@ -38,16 +39,14 @@ public void sendSingle(@NonNull MatomoRequest request) { @Override public void sendBulk( - @NonNull Iterable requests, @Nullable String overrideAuthToken - ) { + @NonNull Iterable requests, @Nullable String overrideAuthToken) { throw new UnsupportedOperationException(); } @NonNull @Override public CompletableFuture sendBulkAsync( - @NonNull Collection requests, @Nullable String overrideAuthToken - ) { + @NonNull Collection requests, @Nullable String overrideAuthToken) { throw new UnsupportedOperationException(); } diff --git a/servlet-jakarta/src/test/java/org/matomo/java/tracking/TestSenderFactory.java b/servlet-jakarta/src/test/java/org/matomo/java/tracking/TestSenderFactory.java index fafafa90..4ddb321f 100644 --- a/servlet-jakarta/src/test/java/org/matomo/java/tracking/TestSenderFactory.java +++ b/servlet-jakarta/src/test/java/org/matomo/java/tracking/TestSenderFactory.java @@ -4,8 +4,7 @@ class TestSenderFactory implements SenderFactory { - @Getter - private TestSender testSender; + @Getter private TestSender testSender; @Override public Sender createSender(TrackerConfiguration trackerConfiguration, QueryCreator queryCreator) { diff --git a/servlet-jakarta/src/test/java/org/matomo/java/tracking/servlet/JakartaHttpServletWrapperTest.java b/servlet-jakarta/src/test/java/org/matomo/java/tracking/servlet/JakartaHttpServletWrapperTest.java index d15dbcbf..409ed1e2 100644 --- a/servlet-jakarta/src/test/java/org/matomo/java/tracking/servlet/JakartaHttpServletWrapperTest.java +++ b/servlet-jakarta/src/test/java/org/matomo/java/tracking/servlet/JakartaHttpServletWrapperTest.java @@ -27,11 +27,10 @@ void wrapsHttpServletRequest() { .containsEntry("accept-language", "en-US,en;q=0.9,de;q=0.8"); assertThat(httpServletRequestWrapper.getCookies()) .hasSize(1) - .satisfiesExactly(cookieWrapper -> { - assertThat(cookieWrapper.getName()).isEqualTo("foo"); - assertThat(cookieWrapper.getValue()).isEqualTo("bar"); - }); + .satisfiesExactly( + cookieWrapper -> { + assertThat(cookieWrapper.getName()).isEqualTo("foo"); + assertThat(cookieWrapper.getValue()).isEqualTo("bar"); + }); } - } - diff --git a/servlet-jakarta/src/test/java/org/matomo/java/tracking/servlet/MockHttpServletRequest.java b/servlet-jakarta/src/test/java/org/matomo/java/tracking/servlet/MockHttpServletRequest.java index 856c76db..ad787b61 100644 --- a/servlet-jakarta/src/test/java/org/matomo/java/tracking/servlet/MockHttpServletRequest.java +++ b/servlet-jakarta/src/test/java/org/matomo/java/tracking/servlet/MockHttpServletRequest.java @@ -67,7 +67,9 @@ public Enumeration getHeaders(String name) { @Override public Enumeration getHeaderNames() { - return headers == null ? Collections.emptyEnumeration() : Collections.enumeration(headers.keySet()); + return headers == null + ? Collections.emptyEnumeration() + : Collections.enumeration(headers.keySet()); } @Override @@ -161,14 +163,10 @@ public boolean authenticate(HttpServletResponse response) throws IOException, Se } @Override - public void login(String username, String password) throws ServletException { - - } + public void login(String username, String password) throws ServletException {} @Override - public void logout() throws ServletException { - - } + public void logout() throws ServletException {} @Override public Collection getParts() throws IOException, ServletException { @@ -181,7 +179,8 @@ public Part getPart(String name) throws IOException, ServletException { } @Override - public T upgrade(Class handlerClass) throws IOException, ServletException { + public T upgrade(Class handlerClass) + throws IOException, ServletException { return null; } @@ -201,9 +200,7 @@ public String getCharacterEncoding() { } @Override - public void setCharacterEncoding(String env) throws UnsupportedEncodingException { - - } + public void setCharacterEncoding(String env) throws UnsupportedEncodingException {} @Override public int getContentLength() { @@ -281,14 +278,10 @@ public String getRemoteHost() { } @Override - public void setAttribute(String name, Object o) { - - } + public void setAttribute(String name, Object o) {} @Override - public void removeAttribute(String name) { - - } + public void removeAttribute(String name) {} @Override public Locale getLocale() { @@ -342,7 +335,7 @@ public AsyncContext startAsync() throws IllegalStateException { @Override public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) - throws IllegalStateException { + throws IllegalStateException { return null; } diff --git a/servlet-javax/pom.xml b/servlet-javax/pom.xml index 7e76f0a5..ade58c26 100644 --- a/servlet-javax/pom.xml +++ b/servlet-javax/pom.xml @@ -1,15 +1,16 @@ + 4.0.0 org.piwik.java.tracking matomo-java-tracker-parent - 3.4.1-SNAPSHOT + 3.5.0-SNAPSHOT ../pom.xml matomo-java-tracker-servlet-javax - 3.4.1-SNAPSHOT + 3.5.0-SNAPSHOT jar Matomo Java Tracker Servlet Javax @@ -53,7 +54,7 @@ org.eclipse.jetty jetty-servlet - 10.0.24 + 10.0.26 test diff --git a/servlet-javax/src/main/java/org/matomo/java/tracking/servlet/JavaxHttpServletWrapper.java b/servlet-javax/src/main/java/org/matomo/java/tracking/servlet/JavaxHttpServletWrapper.java index 77c9838b..d72bbd96 100644 --- a/servlet-javax/src/main/java/org/matomo/java/tracking/servlet/JavaxHttpServletWrapper.java +++ b/servlet-javax/src/main/java/org/matomo/java/tracking/servlet/JavaxHttpServletWrapper.java @@ -1,5 +1,6 @@ package org.matomo.java.tracking.servlet; +import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; @@ -9,9 +10,7 @@ import javax.servlet.http.HttpServletRequest; import lombok.NonNull; -/** - * Converts a javax {@link HttpServletRequest} to a {@link HttpServletRequestWrapper}. - */ +/** Converts a javax {@link HttpServletRequest} to a {@link HttpServletRequestWrapper}. */ public final class JavaxHttpServletWrapper { private JavaxHttpServletWrapper() { @@ -19,26 +18,29 @@ private JavaxHttpServletWrapper() { } /** - * Takes a javax {@link HttpServletRequest} and converts it to a - * {@link HttpServletRequestWrapper}. + * Takes a javax {@link HttpServletRequest} and converts it to a {@link + * HttpServletRequestWrapper}. * * @param request the request to convert to a wrapper object (must not be {@code null}). * @return the wrapper object (never {@code null}). */ @edu.umd.cs.findbugs.annotations.NonNull - public static HttpServletRequestWrapper fromHttpServletRequest(@NonNull HttpServletRequest request) { + public static HttpServletRequestWrapper fromHttpServletRequest( + @NonNull HttpServletRequest request) { Map headers = new LinkedHashMap<>(); - request.getHeaderNames() - .asIterator() - .forEachRemaining(name -> headers.put(name.toLowerCase(Locale.ROOT), request.getHeader(name))); + Enumeration headerNames = request.getHeaderNames(); + while (headerNames.hasMoreElements()) { + String name = headerNames.nextElement(); + headers.put(name.toLowerCase(Locale.ROOT), request.getHeader(name)); + } List cookies = null; if (request.getCookies() != null) { - cookies = Stream.of(request.getCookies()) - .map(cookie -> new CookieWrapper(cookie.getName(), cookie.getValue())) - .collect(Collectors.toList()); + cookies = + Stream.of(request.getCookies()) + .map(cookie -> new CookieWrapper(cookie.getName(), cookie.getValue())) + .collect(Collectors.toList()); } - return HttpServletRequestWrapper - .builder() + return HttpServletRequestWrapper.builder() .requestURL(request.getRequestURL()) .remoteAddr(request.getRemoteAddr()) .remoteUser(request.getRemoteUser()) @@ -46,5 +48,4 @@ public static HttpServletRequestWrapper fromHttpServletRequest(@NonNull HttpServ .cookies(cookies == null ? null : cookies.toArray(new CookieWrapper[0])) .build(); } - } diff --git a/servlet-javax/src/main/java/org/matomo/java/tracking/servlet/MatomoTrackerFilter.java b/servlet-javax/src/main/java/org/matomo/java/tracking/servlet/MatomoTrackerFilter.java index abf0849d..b72efb77 100644 --- a/servlet-javax/src/main/java/org/matomo/java/tracking/servlet/MatomoTrackerFilter.java +++ b/servlet-javax/src/main/java/org/matomo/java/tracking/servlet/MatomoTrackerFilter.java @@ -23,11 +23,12 @@ public class MatomoTrackerFilter extends HttpFilter { private final MatomoTracker tracker; @Override - protected void doFilter(@NonNull HttpServletRequest req, @NonNull HttpServletResponse res, - @NonNull FilterChain chain) - throws IOException, ServletException { - MatomoRequest matomoRequest = ServletMatomoRequest - .fromServletRequest(JavaxHttpServletWrapper.fromHttpServletRequest(req)).build(); + protected void doFilter( + @NonNull HttpServletRequest req, @NonNull HttpServletResponse res, @NonNull FilterChain chain) + throws IOException, ServletException { + MatomoRequest matomoRequest = + ServletMatomoRequest.fromServletRequest(JavaxHttpServletWrapper.fromHttpServletRequest(req)) + .build(); log.debug("Sending request {}", matomoRequest); tracker.sendRequestAsync(matomoRequest); super.doFilter(req, res, chain); diff --git a/servlet-javax/src/test/java/org/matomo/java/tracking/MatomoTrackerFilterIT.java b/servlet-javax/src/test/java/org/matomo/java/tracking/MatomoTrackerFilterIT.java index 676524c2..cc0fb30e 100644 --- a/servlet-javax/src/test/java/org/matomo/java/tracking/MatomoTrackerFilterIT.java +++ b/servlet-javax/src/test/java/org/matomo/java/tracking/MatomoTrackerFilterIT.java @@ -17,17 +17,16 @@ class MatomoTrackerFilterIT { @Test void sendsAnAsyncRequestOnFilter() throws Exception { - TestSenderFactory senderFactory = new TestSenderFactory(); - MatomoTracker tracker = new MatomoTracker( - TrackerConfiguration - .builder() - .apiEndpoint(URI.create("http://localhost:8080/matomo.php")) - .defaultSiteId(1) - .defaultAuthToken("ee6e3dd9ed1b61f5328cf5978b5a8c71") - .logFailedTracking(true) - .build()); + MatomoTracker tracker = + new MatomoTracker( + TrackerConfiguration.builder() + .apiEndpoint(URI.create("http://localhost:8080/matomo.php")) + .defaultSiteId(1) + .defaultAuthToken("ee6e3dd9ed1b61f5328cf5978b5a8c71") + .logFailedTracking(true) + .build()); tracker.setSenderFactory(senderFactory); ServletContextHandler context = new ServletContextHandler(); @@ -38,28 +37,27 @@ void sendsAnAsyncRequestOnFilter() throws Exception { server.start(); URI uri = server.getURI(); - HttpClient.newHttpClient().send( - HttpRequest.newBuilder() - .header("Accept-Language", "en-US,en;q=0.9,de;q=0.8") - .uri(uri) - .build(), - HttpResponse.BodyHandlers.discarding() - ); + HttpClient.newHttpClient() + .send( + HttpRequest.newBuilder() + .header("Accept-Language", "en-US,en;q=0.9,de;q=0.8") + .uri(uri) + .build(), + HttpResponse.BodyHandlers.discarding()); server.stop(); TestSender testSender = senderFactory.getTestSender(); - assertThat(testSender.getRequests()).hasSize(1).satisfiesExactly(matomoRequest -> { - assertThat(matomoRequest.getActionUrl()).isEqualTo(uri.toString()); - assertThat(matomoRequest.getVisitorId()).isNotNull(); - assertThat(matomoRequest.getVisitorIp()).isNotNull(); - assertThat(matomoRequest.getHeaders()).containsEntry( - "accept-language", - "en-US,en;q=0.9,de;q=0.8" - ); - }); + assertThat(testSender.getRequests()) + .hasSize(1) + .satisfiesExactly( + matomoRequest -> { + assertThat(matomoRequest.getActionUrl()).isEqualTo(uri.toString()); + assertThat(matomoRequest.getVisitorId()).isNotNull(); + assertThat(matomoRequest.getVisitorIp()).isNotNull(); + assertThat(matomoRequest.getHeaders()) + .containsEntry("accept-language", "en-US,en;q=0.9,de;q=0.8"); + }); tracker.close(); - } - -} \ No newline at end of file +} diff --git a/servlet-javax/src/test/java/org/matomo/java/tracking/TestSender.java b/servlet-javax/src/test/java/org/matomo/java/tracking/TestSender.java index 0e1704f1..539d01ff 100644 --- a/servlet-javax/src/test/java/org/matomo/java/tracking/TestSender.java +++ b/servlet-javax/src/test/java/org/matomo/java/tracking/TestSender.java @@ -11,8 +11,9 @@ /** * A {@link Sender} implementation that does not send anything but stores the requests. * - *

This class is intended for testing purposes only. It does not send anything to the Matomo server. Instead, it - * stores the requests and queries in collections that can be accessed via {@link #getRequests()}. + *

This class is intended for testing purposes only. It does not send anything to the Matomo + * server. Instead, it stores the requests and queries in collections that can be accessed via + * {@link #getRequests()}. */ @RequiredArgsConstructor @Getter @@ -38,16 +39,14 @@ public void sendSingle(@NonNull MatomoRequest request) { @Override public void sendBulk( - @NonNull Iterable requests, @Nullable String overrideAuthToken - ) { + @NonNull Iterable requests, @Nullable String overrideAuthToken) { throw new UnsupportedOperationException(); } @NonNull @Override public CompletableFuture sendBulkAsync( - @NonNull Collection requests, @Nullable String overrideAuthToken - ) { + @NonNull Collection requests, @Nullable String overrideAuthToken) { throw new UnsupportedOperationException(); } diff --git a/servlet-javax/src/test/java/org/matomo/java/tracking/TestSenderFactory.java b/servlet-javax/src/test/java/org/matomo/java/tracking/TestSenderFactory.java index fafafa90..4ddb321f 100644 --- a/servlet-javax/src/test/java/org/matomo/java/tracking/TestSenderFactory.java +++ b/servlet-javax/src/test/java/org/matomo/java/tracking/TestSenderFactory.java @@ -4,8 +4,7 @@ class TestSenderFactory implements SenderFactory { - @Getter - private TestSender testSender; + @Getter private TestSender testSender; @Override public Sender createSender(TrackerConfiguration trackerConfiguration, QueryCreator queryCreator) { diff --git a/servlet-javax/src/test/java/org/matomo/java/tracking/servlet/JavaxHttpServletWrapperTest.java b/servlet-javax/src/test/java/org/matomo/java/tracking/servlet/JavaxHttpServletWrapperTest.java index e631d818..b21347df 100644 --- a/servlet-javax/src/test/java/org/matomo/java/tracking/servlet/JavaxHttpServletWrapperTest.java +++ b/servlet-javax/src/test/java/org/matomo/java/tracking/servlet/JavaxHttpServletWrapperTest.java @@ -4,7 +4,6 @@ import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; -import java.util.List; import javax.servlet.http.Cookie; import org.junit.jupiter.api.Test; @@ -28,11 +27,10 @@ void wrapsHttpServletRequest() { .containsEntry("accept-language", "en-US,en;q=0.9,de;q=0.8"); assertThat(httpServletRequestWrapper.getCookies()) .hasSize(1) - .satisfiesExactly(cookieWrapper -> { - assertThat(cookieWrapper.getName()).isEqualTo("foo"); - assertThat(cookieWrapper.getValue()).isEqualTo("bar"); - }); + .satisfiesExactly( + cookieWrapper -> { + assertThat(cookieWrapper.getName()).isEqualTo("foo"); + assertThat(cookieWrapper.getValue()).isEqualTo("bar"); + }); } - } - diff --git a/servlet-javax/src/test/java/org/matomo/java/tracking/servlet/MockHttpServletRequest.java b/servlet-javax/src/test/java/org/matomo/java/tracking/servlet/MockHttpServletRequest.java index e0de55b9..9122d383 100644 --- a/servlet-javax/src/test/java/org/matomo/java/tracking/servlet/MockHttpServletRequest.java +++ b/servlet-javax/src/test/java/org/matomo/java/tracking/servlet/MockHttpServletRequest.java @@ -66,7 +66,9 @@ public Enumeration getHeaders(String name) { @Override public Enumeration getHeaderNames() { - return headers == null ? Collections.emptyEnumeration() : Collections.enumeration(headers.keySet()); + return headers == null + ? Collections.emptyEnumeration() + : Collections.enumeration(headers.keySet()); } @Override @@ -165,14 +167,10 @@ public boolean authenticate(HttpServletResponse response) throws IOException, Se } @Override - public void login(String username, String password) throws ServletException { - - } + public void login(String username, String password) throws ServletException {} @Override - public void logout() throws ServletException { - - } + public void logout() throws ServletException {} @Override public Collection getParts() throws IOException, ServletException { @@ -185,7 +183,8 @@ public Part getPart(String name) throws IOException, ServletException { } @Override - public T upgrade(Class handlerClass) throws IOException, ServletException { + public T upgrade(Class handlerClass) + throws IOException, ServletException { return null; } @@ -205,9 +204,7 @@ public String getCharacterEncoding() { } @Override - public void setCharacterEncoding(String env) throws UnsupportedEncodingException { - - } + public void setCharacterEncoding(String env) throws UnsupportedEncodingException {} @Override public int getContentLength() { @@ -285,14 +282,10 @@ public String getRemoteHost() { } @Override - public void setAttribute(String name, Object o) { - - } + public void setAttribute(String name, Object o) {} @Override - public void removeAttribute(String name) { - - } + public void removeAttribute(String name) {} @Override public Locale getLocale() { @@ -351,7 +344,7 @@ public AsyncContext startAsync() throws IllegalStateException { @Override public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) - throws IllegalStateException { + throws IllegalStateException { return null; } @@ -374,5 +367,4 @@ public AsyncContext getAsyncContext() { public DispatcherType getDispatcherType() { return null; } - } diff --git a/spring/pom.xml b/spring/pom.xml index c55f8c43..7ef22e49 100644 --- a/spring/pom.xml +++ b/spring/pom.xml @@ -1,10 +1,11 @@ + 4.0.0 org.piwik.java.tracking matomo-java-tracker-parent - 3.4.1-SNAPSHOT + 3.5.0-SNAPSHOT ../pom.xml @@ -17,7 +18,7 @@ 17 17 - 3.4.2 + 4.0.5 diff --git a/spring/src/main/java/org/matomo/java/tracking/spring/MatomoTrackerAutoConfiguration.java b/spring/src/main/java/org/matomo/java/tracking/spring/MatomoTrackerAutoConfiguration.java index ae7e0376..192ae3c6 100644 --- a/spring/src/main/java/org/matomo/java/tracking/spring/MatomoTrackerAutoConfiguration.java +++ b/spring/src/main/java/org/matomo/java/tracking/spring/MatomoTrackerAutoConfiguration.java @@ -9,6 +9,7 @@ import java.net.URI; import java.util.List; +import org.jspecify.annotations.NonNull; import org.matomo.java.tracking.MatomoTracker; import org.matomo.java.tracking.TrackerConfiguration; import org.matomo.java.tracking.servlet.MatomoTrackerFilter; @@ -18,7 +19,6 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; -import org.springframework.lang.NonNull; /** * {@link AutoConfiguration Auto configuration} for Matomo Tracker. @@ -33,19 +33,18 @@ public class MatomoTrackerAutoConfiguration { /** - * Creates a {@link TrackerConfiguration.TrackerConfigurationBuilder} and applies all - * {@link TrackerConfigurationBuilderCustomizer}s. Can be overridden by custom beans. + * Creates a {@link TrackerConfiguration.TrackerConfigurationBuilder} and applies all {@link + * TrackerConfigurationBuilderCustomizer}s. Can be overridden by custom beans. * * @param customizers the customizers to apply to the builder instance (never {@code null}) - * @return the {@link TrackerConfiguration.TrackerConfigurationBuilder} instance (never {@code null}) + * @return the {@link TrackerConfiguration.TrackerConfigurationBuilder} instance (never {@code + * null}) * @see TrackerConfiguration#builder() */ @Bean @ConditionalOnMissingBean - @NonNull - public TrackerConfiguration.TrackerConfigurationBuilder trackerConfigurationBuilder( - @NonNull List customizers - ) { + public TrackerConfiguration.@NonNull TrackerConfigurationBuilder trackerConfigurationBuilder( + @NonNull List customizers) { TrackerConfiguration.TrackerConfigurationBuilder builder = TrackerConfiguration.builder(); customizers.forEach(customizer -> customizer.customize(builder)); return builder; @@ -55,10 +54,11 @@ public TrackerConfiguration.TrackerConfigurationBuilder trackerConfigurationBuil * Creates a {@link TrackerConfiguration} instance based on the current configuration. Can be * overridden by custom beans. * - *

If you define your own {@link TrackerConfiguration} bean, please don't forget to set the - * API endpoint. + *

If you define your own {@link TrackerConfiguration} bean, please don't forget to set the API + * endpoint. * - * @param builder the {@link TrackerConfiguration.TrackerConfigurationBuilder} instance (never {@code null}) + * @param builder the {@link TrackerConfiguration.TrackerConfigurationBuilder} instance (never + * {@code null}) * @return the {@link TrackerConfiguration} instance (never {@code null}) * @see TrackerConfiguration#builder() * @see TrackerConfiguration.TrackerConfigurationBuilder#apiEndpoint(URI) @@ -67,14 +67,13 @@ public TrackerConfiguration.TrackerConfigurationBuilder trackerConfigurationBuil @ConditionalOnMissingBean @NonNull public TrackerConfiguration trackerConfiguration( - TrackerConfiguration.TrackerConfigurationBuilder builder - ) { + TrackerConfiguration.TrackerConfigurationBuilder builder) { return builder.build(); } /** - * Configures the {@link TrackerConfiguration.TrackerConfigurationBuilder} with the properties from - * {@link MatomoTrackerProperties}. + * Configures the {@link TrackerConfiguration.TrackerConfigurationBuilder} with the properties + * from {@link MatomoTrackerProperties}. * * @param properties the {@link MatomoTrackerProperties} instance (never {@code null}) * @return the {@link StandardTrackerConfigurationBuilderCustomizer} instance (never {@code null}) @@ -83,15 +82,14 @@ public TrackerConfiguration trackerConfiguration( */ @Bean @NonNull - public StandardTrackerConfigurationBuilderCustomizer standardTrackerConfigurationBuilderCustomizer( - @NonNull MatomoTrackerProperties properties - ) { + public StandardTrackerConfigurationBuilderCustomizer + standardTrackerConfigurationBuilderCustomizer(@NonNull MatomoTrackerProperties properties) { return new StandardTrackerConfigurationBuilderCustomizer(properties); } /** - * A {@link MatomoTracker} instance based on the current configuration. Only created if a bean of the same type is not - * already configured. + * A {@link MatomoTracker} instance based on the current configuration. Only created if a bean of + * the same type is not already configured. * * @param trackerConfiguration the {@link TrackerConfiguration} instance (never {@code null}) * @return the {@link MatomoTracker} instance (never {@code null}) @@ -108,8 +106,8 @@ public MatomoTracker matomoTracker(@NonNull TrackerConfiguration trackerConfigur /** * A {@link FilterRegistrationBean} for the {@link MatomoTrackerFilter}. * - *

Only created if a bean of the same type is not already configured. The filter is only registered if - * {@code matomo.tracker.filter.enabled} is set to {@code true}. + *

Only created if a bean of the same type is not already configured. The filter is only + * registered if {@code matomo.tracker.filter.enabled} is set to {@code true}. * * @param matomoTracker the {@link MatomoTracker} instance (never {@code null}) * @return the {@link FilterRegistrationBean} instance (never {@code null}) @@ -118,9 +116,7 @@ public MatomoTracker matomoTracker(@NonNull TrackerConfiguration trackerConfigur @ConditionalOnProperty(value = "matomo.tracker.filter.enabled", havingValue = "true") @NonNull public FilterRegistrationBean matomoTrackerSpringFilter( - @NonNull MatomoTracker matomoTracker - ) { + @NonNull MatomoTracker matomoTracker) { return new FilterRegistrationBean<>(new MatomoTrackerFilter(matomoTracker)); } - } diff --git a/spring/src/main/java/org/matomo/java/tracking/spring/MatomoTrackerProperties.java b/spring/src/main/java/org/matomo/java/tracking/spring/MatomoTrackerProperties.java index 8be4023d..2ae72559 100644 --- a/spring/src/main/java/org/matomo/java/tracking/spring/MatomoTrackerProperties.java +++ b/spring/src/main/java/org/matomo/java/tracking/spring/MatomoTrackerProperties.java @@ -17,6 +17,7 @@ * Configuration properties for the Matomo Tracker. * *

These properties can be configured in the application.properties file. For example: + * *

  *   matomo.tracker.api-endpoint=https://your-matomo-domain.example/matomo.php
  *   matomo.tracker.default-site-id=1
@@ -44,70 +45,62 @@
 public class MatomoTrackerProperties {
 
   /**
-   * The Matomo Tracking HTTP API endpoint, for example https://your-matomo-domain.example/matomo.php
+   * The Matomo Tracking HTTP API endpoint. Example: https://your-matomo-domain.example/matomo.php
    */
   private String apiEndpoint;
 
-  /**
-   * The default ID of the website that will be used if not specified explicitly.
-   */
+  /** The default ID of the website that will be used if not specified explicitly. */
   private Integer defaultSiteId;
 
-  /**
-   * The authorization token (parameter token_auth) to use if not specified explicitly.
-   */
+  /** The authorization token (parameter token_auth) to use if not specified explicitly. */
   private String defaultAuthToken;
 
-  /**
-   * Allows to stop the tracker to send requests to the Matomo endpoint.
-   */
+  /** Allows to stop the tracker to send requests to the Matomo endpoint. */
   private Boolean enabled = true;
 
   /**
    * The timeout until a connection is established.
    *
-   * 

A timeout value of zero is interpreted as an infinite timeout. - * A `null` value is interpreted as undefined (system default if applicable).

+ *

A timeout value of zero is interpreted as an infinite timeout. A `null` value is interpreted + * as undefined (system default if applicable). * - *

Default: 10 seconds

+ *

Default: 10 seconds */ private Duration connectTimeout = Duration.ofSeconds(5L); /** - * The socket timeout ({@code SO_TIMEOUT}), which is the timeout for waiting for data or, put differently, a maximum - * period inactivity between two consecutive data packets. + * The socket timeout ({@code SO_TIMEOUT}), which is the timeout for waiting for data or, put + * differently, a maximum period inactivity between two consecutive data packets. * - *

A timeout value of zero is interpreted as an infinite timeout. - * A `null value is interpreted as undefined (system default if applicable).

+ *

A timeout value of zero is interpreted as an infinite timeout. A `null value is interpreted + * as undefined (system default if applicable). * - *

Default: 30 seconds

+ *

Default: 30 seconds */ private Duration socketTimeout = Duration.ofSeconds(5L); /** - * The hostname or IP address of an optional HTTP proxy. {@code proxyPort} must be configured as well + * The hostname or IP address of an optional HTTP proxy. {@code proxyPort} must be configured as + * well */ private String proxyHost; - /** - * The port of an HTTP proxy. {@code proxyHost} must be configured as well. - */ + /** The port of an HTTP proxy. {@code proxyHost} must be configured as well. */ private Integer proxyPort; /** - * If the HTTP proxy requires a username for basic authentication, it can be configured here. Proxy host, port and - * password must also be set. + * If the HTTP proxy requires a username for basic authentication, it can be configured here. + * Proxy host, port and password must also be set. */ private String proxyUsername; /** - * The corresponding password for the basic auth proxy user. The proxy host, port and username must be set as well. + * The corresponding password for the basic auth proxy user. The proxy host, port and username + * must be set as well. */ private String proxyPassword; - /** - * A custom user agent to be set. Defaults to "MatomoJavaClient" - */ + /** A custom user agent to be set. Defaults to "MatomoJavaClient" */ private String userAgent = "MatomoJavaClient"; /** @@ -121,7 +114,7 @@ public class MatomoTrackerProperties { * Do not use in production environments. Defaults to false. * *

Attention: This slows down performance - + * * @see #disableSslHostVerification */ private Boolean disableSslCertValidation; @@ -140,9 +133,7 @@ public class MatomoTrackerProperties { * The thread pool size for the async sender. Defaults to 2. * *

Attention: If you use this library in a web application, make sure that this thread pool - * does not exceed the thread pool of the web application. Otherwise, you might run into - * problems. + * does not exceed the thread pool of the web application. Otherwise, you might run into problems. */ private Integer threadPoolSize = 2; - } diff --git a/spring/src/main/java/org/matomo/java/tracking/spring/StandardTrackerConfigurationBuilderCustomizer.java b/spring/src/main/java/org/matomo/java/tracking/spring/StandardTrackerConfigurationBuilderCustomizer.java index e9f1acd2..afd00d33 100644 --- a/spring/src/main/java/org/matomo/java/tracking/spring/StandardTrackerConfigurationBuilderCustomizer.java +++ b/spring/src/main/java/org/matomo/java/tracking/spring/StandardTrackerConfigurationBuilderCustomizer.java @@ -8,12 +8,13 @@ package org.matomo.java.tracking.spring; import java.net.URI; +import org.jspecify.annotations.NonNull; import org.matomo.java.tracking.TrackerConfiguration; import org.springframework.boot.context.properties.PropertyMapper; import org.springframework.core.Ordered; -import org.springframework.lang.NonNull; -class StandardTrackerConfigurationBuilderCustomizer implements TrackerConfigurationBuilderCustomizer, Ordered { +class StandardTrackerConfigurationBuilderCustomizer + implements TrackerConfigurationBuilderCustomizer, Ordered { private final MatomoTrackerProperties properties; @@ -27,8 +28,8 @@ public int getOrder() { } @Override - public void customize(@NonNull TrackerConfiguration.TrackerConfigurationBuilder builder) { - PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); + public void customize(TrackerConfiguration.@NonNull TrackerConfigurationBuilder builder) { + PropertyMapper map = PropertyMapper.get(); map.from(properties::getApiEndpoint).as(URI::create).to(builder::apiEndpoint); map.from(properties::getDefaultSiteId).to(builder::defaultSiteId); map.from(properties::getDefaultAuthToken).to(builder::defaultAuthToken); @@ -45,6 +46,4 @@ public void customize(@NonNull TrackerConfiguration.TrackerConfigurationBuilder map.from(properties::getDisableSslHostVerification).to(builder::disableSslHostVerification); map.from(properties::getThreadPoolSize).to(builder::threadPoolSize); } - - -} \ No newline at end of file +} diff --git a/spring/src/main/java/org/matomo/java/tracking/spring/TrackerConfigurationBuilderCustomizer.java b/spring/src/main/java/org/matomo/java/tracking/spring/TrackerConfigurationBuilderCustomizer.java index e147a64f..621cc4b1 100644 --- a/spring/src/main/java/org/matomo/java/tracking/spring/TrackerConfigurationBuilderCustomizer.java +++ b/spring/src/main/java/org/matomo/java/tracking/spring/TrackerConfigurationBuilderCustomizer.java @@ -7,13 +7,15 @@ package org.matomo.java.tracking.spring; +import org.jspecify.annotations.NonNull; import org.matomo.java.tracking.TrackerConfiguration; -import org.springframework.lang.NonNull; /** - * Allows to customize the {@link TrackerConfiguration.TrackerConfigurationBuilder} with additional properties. + * Allows to customize the {@link TrackerConfiguration.TrackerConfigurationBuilder} with additional + * properties. * - *

Implementations of this interface are detected automatically by the {@link MatomoTrackerAutoConfiguration}. + *

Implementations of this interface are detected automatically by the {@link + * MatomoTrackerAutoConfiguration}. * * @see MatomoTrackerAutoConfiguration * @see TrackerConfiguration @@ -25,10 +27,10 @@ public interface TrackerConfigurationBuilderCustomizer { /** * Customize the {@link TrackerConfiguration.TrackerConfigurationBuilder}. * - * @param builder the {@link TrackerConfiguration.TrackerConfigurationBuilder} instance (never {@code null}) + * @param builder the {@link TrackerConfiguration.TrackerConfigurationBuilder} instance (never + * {@code null}) * @see TrackerConfiguration#builder() * @see MatomoTrackerProperties */ - void customize(@NonNull TrackerConfiguration.TrackerConfigurationBuilder builder); - + void customize(TrackerConfiguration.@NonNull TrackerConfigurationBuilder builder); } diff --git a/spring/src/main/java/org/matomo/java/tracking/spring/package-info.java b/spring/src/main/java/org/matomo/java/tracking/spring/package-info.java index 784c9d72..b7db4c90 100644 --- a/spring/src/main/java/org/matomo/java/tracking/spring/package-info.java +++ b/spring/src/main/java/org/matomo/java/tracking/spring/package-info.java @@ -1,10 +1,10 @@ /** * Provides Spring specific classes to integrate Matomo tracking into Spring applications. * - *

See {@link org.matomo.java.tracking.spring.MatomoTrackerProperties} for the available configuration properties. + *

See {@link org.matomo.java.tracking.spring.MatomoTrackerProperties} for the available + * configuration properties. * - *

See {@link org.matomo.java.tracking.spring.MatomoTrackerAutoConfiguration} for the available configuration - * options. + *

See {@link org.matomo.java.tracking.spring.MatomoTrackerAutoConfiguration} for the available + * configuration options. */ - -package org.matomo.java.tracking.spring; \ No newline at end of file +package org.matomo.java.tracking.spring; diff --git a/spring/src/test/java/org/matomo/java/tracking/spring/MatomoTrackerAutoConfigurationIT.java b/spring/src/test/java/org/matomo/java/tracking/spring/MatomoTrackerAutoConfigurationIT.java index c008dbc8..d185ea0c 100644 --- a/spring/src/test/java/org/matomo/java/tracking/spring/MatomoTrackerAutoConfigurationIT.java +++ b/spring/src/test/java/org/matomo/java/tracking/spring/MatomoTrackerAutoConfigurationIT.java @@ -15,14 +15,17 @@ class MatomoTrackerAutoConfigurationIT { private final ApplicationContextRunner contextRunner = - new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(MatomoTrackerAutoConfiguration.class)); - + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(MatomoTrackerAutoConfiguration.class)); @Test void matomoTrackerRegistration() { - contextRunner.withPropertyValues("matomo.tracker.api-endpoint:https://test.com/matomo.php").run(context -> { - assertThat(context).hasSingleBean(MatomoTracker.class).hasBean("matomoTracker"); - }); + contextRunner + .withPropertyValues("matomo.tracker.api-endpoint:https://test.com/matomo.php") + .run( + context -> { + assertThat(context).hasSingleBean(MatomoTracker.class).hasBean("matomoTracker"); + }); } @Test @@ -30,10 +33,13 @@ void additionalTrackerConfigurationBuilderCustomization() { this.contextRunner .withPropertyValues("matomo.tracker.api-endpoint:https://test.com/matomo.php") .withUserConfiguration(TrackerConfigurationBuilderCustomizerConfig.class) - .run(context -> { - TrackerConfiguration trackerConfiguration = context.getBean(TrackerConfiguration.class); - assertThat(trackerConfiguration.getConnectTimeout()).isEqualTo(Duration.ofMinutes(1L)); - }); + .run( + context -> { + TrackerConfiguration trackerConfiguration = + context.getBean(TrackerConfiguration.class); + assertThat(trackerConfiguration.getConnectTimeout()) + .isEqualTo(Duration.ofMinutes(1L)); + }); } @Test @@ -41,10 +47,12 @@ void customTrackerConfigurationBuilder() { this.contextRunner .withPropertyValues("matomo.tracker.api-endpoint:https://test.com/matomo.php") .withUserConfiguration(TrackerConfigurationBuilderConfig.class) - .run(context -> { - TrackerConfiguration trackerConfiguration = context.getBean(TrackerConfiguration.class); - assertThat(trackerConfiguration.isDisableSslHostVerification()).isTrue(); - }); + .run( + context -> { + TrackerConfiguration trackerConfiguration = + context.getBean(TrackerConfiguration.class); + assertThat(trackerConfiguration.isDisableSslHostVerification()).isTrue(); + }); } @Configuration @@ -54,7 +62,6 @@ static class TrackerConfigurationBuilderCustomizerConfig { TrackerConfigurationBuilderCustomizer customConnectTimeout() { return configurationBuilder -> configurationBuilder.connectTimeout(Duration.ofMinutes(1L)); } - } @Configuration @@ -62,9 +69,9 @@ static class TrackerConfigurationBuilderConfig { @Bean TrackerConfiguration.TrackerConfigurationBuilder customTrackerConfigurationBuilder() { - return TrackerConfiguration.builder().apiEndpoint(URI.create("https://test.com/matomo.php")).disableSslHostVerification(true); + return TrackerConfiguration.builder() + .apiEndpoint(URI.create("https://test.com/matomo.php")) + .disableSslHostVerification(true); } - } - -} \ No newline at end of file +} diff --git a/spring/src/test/java/org/matomo/java/tracking/spring/StandardTrackerConfigurationBuilderCustomizerIT.java b/spring/src/test/java/org/matomo/java/tracking/spring/StandardTrackerConfigurationBuilderCustomizerIT.java index b62eafec..22052c8a 100644 --- a/spring/src/test/java/org/matomo/java/tracking/spring/StandardTrackerConfigurationBuilderCustomizerIT.java +++ b/spring/src/test/java/org/matomo/java/tracking/spring/StandardTrackerConfigurationBuilderCustomizerIT.java @@ -44,12 +44,11 @@ void createsStandardTrackerConfigurationBuilderCustomizer() { assertThat(configuration.getProxyPort()).isEqualTo(8080); assertThat(configuration.getProxyUsername()).isEqualTo("user"); assertThat(configuration.getProxyPassword()).isEqualTo("password"); - assertThat(configuration.getUserAgent()).isEqualTo( - "Mozilla/5.0 (compatible; AcmeInc/1.0; +https://example.com/bot.html)"); + assertThat(configuration.getUserAgent()) + .isEqualTo("Mozilla/5.0 (compatible; AcmeInc/1.0; +https://example.com/bot.html)"); assertThat(configuration.isLogFailedTracking()).isTrue(); assertThat(configuration.isDisableSslCertValidation()).isTrue(); assertThat(configuration.isDisableSslHostVerification()).isTrue(); assertThat(configuration.getThreadPoolSize()).isEqualTo(10); } - -} \ No newline at end of file +} diff --git a/test/pom.xml b/test/pom.xml index 7a2eb183..d02fa589 100644 --- a/test/pom.xml +++ b/test/pom.xml @@ -1,10 +1,11 @@ + 4.0.0 org.piwik.java.tracking matomo-java-tracker-parent - 3.4.1-SNAPSHOT + 3.5.0-SNAPSHOT ../pom.xml @@ -46,7 +47,7 @@ org.eclipse.jetty.ee10 jetty-ee10-servlet - 12.0.16 + 12.1.8 diff --git a/test/src/main/java/org/matomo/java/tracking/test/BulkExample.java b/test/src/main/java/org/matomo/java/tracking/test/BulkExample.java index 54f35f92..9c9fef0c 100644 --- a/test/src/main/java/org/matomo/java/tracking/test/BulkExample.java +++ b/test/src/main/java/org/matomo/java/tracking/test/BulkExample.java @@ -6,9 +6,7 @@ import org.matomo.java.tracking.TrackerConfiguration; import org.matomo.java.tracking.parameters.VisitorId; -/** - * Example for sending multiple requests in one bulk request. - */ +/** Example for sending multiple requests in one bulk request. */ public class BulkExample { /** @@ -18,29 +16,24 @@ public class BulkExample { */ public static void main(String[] args) { - TrackerConfiguration configuration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create("https://www.yourdomain.com/matomo.php")) - .defaultSiteId(1) - .defaultAuthToken("ee6e3dd9ed1b61f5328cf5978b5a8c71") - .logFailedTracking(true) - .build(); + TrackerConfiguration configuration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create("https://www.yourdomain.com/matomo.php")) + .defaultSiteId(1) + .defaultAuthToken("ee6e3dd9ed1b61f5328cf5978b5a8c71") + .logFailedTracking(true) + .build(); try (MatomoTracker tracker = new MatomoTracker(configuration)) { VisitorId visitorId = VisitorId.fromString("customer@mail.com"); tracker.sendBulkRequestAsync( - MatomoRequests.siteSearch("Running shoes", "Running", 120L) - .visitorId(visitorId).build(), - MatomoRequests.pageView("VelocityStride ProX Running Shoes") - .visitorId(visitorId).build(), + MatomoRequests.siteSearch("Running shoes", "Running", 120L).visitorId(visitorId).build(), + MatomoRequests.pageView("VelocityStride ProX Running Shoes").visitorId(visitorId).build(), MatomoRequests.ecommerceOrder("QXZ-789LMP", 100.0, 124.0, 19.0, 10.0, 5.0) .visitorId(visitorId) - .build() - ); + .build()); } catch (Exception e) { throw new RuntimeException("Could not close tracker", e); } - } - } diff --git a/test/src/main/java/org/matomo/java/tracking/test/ConsumerExample.java b/test/src/main/java/org/matomo/java/tracking/test/ConsumerExample.java index 6c37626a..e1f8b323 100644 --- a/test/src/main/java/org/matomo/java/tracking/test/ConsumerExample.java +++ b/test/src/main/java/org/matomo/java/tracking/test/ConsumerExample.java @@ -19,30 +19,30 @@ public class ConsumerExample { */ public static void main(String[] args) { - TrackerConfiguration configuration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create("https://www.yourdomain.com/matomo.php")) - .defaultSiteId(1) - .defaultAuthToken("ee6e3dd9ed1b61f5328cf5978b5a8c71") - .logFailedTracking(true) - .build(); + TrackerConfiguration configuration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create("https://www.yourdomain.com/matomo.php")) + .defaultSiteId(1) + .defaultAuthToken("ee6e3dd9ed1b61f5328cf5978b5a8c71") + .logFailedTracking(true) + .build(); try (MatomoTracker tracker = new MatomoTracker(configuration)) { - MatomoRequest request = MatomoRequests - .event("Training", "Workout completed", "Bench press", 60.0) - .visitorId(VisitorId.fromString("customer@mail.com")) - .build(); + MatomoRequest request = + MatomoRequests.event("Training", "Workout completed", "Bench press", 60.0) + .visitorId(VisitorId.fromString("customer@mail.com")) + .build(); - tracker.sendRequestAsync(request) + tracker + .sendRequestAsync(request) .thenAccept(req -> System.out.printf("Sent request %s%n", req)) - .exceptionally(throwable -> { - System.err.printf("Failed to send request: %s%n", throwable.getMessage()); - return null; - }); + .exceptionally( + throwable -> { + System.err.printf("Failed to send request: %s%n", throwable.getMessage()); + return null; + }); } catch (Exception e) { throw new RuntimeException("Could not close tracker", e); } - } - } diff --git a/test/src/main/java/org/matomo/java/tracking/test/EcommerceExample.java b/test/src/main/java/org/matomo/java/tracking/test/EcommerceExample.java index 3f16258a..51bf6338 100644 --- a/test/src/main/java/org/matomo/java/tracking/test/EcommerceExample.java +++ b/test/src/main/java/org/matomo/java/tracking/test/EcommerceExample.java @@ -8,9 +8,7 @@ import org.matomo.java.tracking.parameters.EcommerceItems; import org.matomo.java.tracking.parameters.VisitorId; -/** - * Example for sending an ecommerce request. - */ +/** Example for sending an ecommerce request. */ public class EcommerceExample { /** @@ -20,43 +18,40 @@ public class EcommerceExample { */ public static void main(String[] args) { - TrackerConfiguration configuration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create("https://www.yourdomain.com/matomo.php")) - .defaultSiteId(1) - .defaultAuthToken("ee6e3dd9ed1b61f5328cf5978b5a8c71") - .logFailedTracking(true) - .build(); + TrackerConfiguration configuration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create("https://www.yourdomain.com/matomo.php")) + .defaultSiteId(1) + .defaultAuthToken("ee6e3dd9ed1b61f5328cf5978b5a8c71") + .logFailedTracking(true) + .build(); try (MatomoTracker tracker = new MatomoTracker(configuration)) { - tracker.sendBulkRequestAsync(MatomoRequests - .ecommerceCartUpdate(50.0) - .ecommerceItems(EcommerceItems - .builder() - .item(EcommerceItem - .builder() - .sku("XYZ12345") - .name("Matomo - The big book about web analytics") - .category("Education & Teaching") - .price(23.1) - .quantity(2) - .build()) - .item(EcommerceItem - .builder() - .sku("B0C2WV3MRJ") - .name("Matomo for data visualization") - .category("Education & Teaching") - .price(15.0) - .quantity(1) - .build()) - .build()) - .visitorId(VisitorId.fromString("customer@mail.com")) - .build() - ); + tracker.sendBulkRequestAsync( + MatomoRequests.ecommerceCartUpdate(50.0) + .ecommerceItems( + EcommerceItems.builder() + .item( + EcommerceItem.builder() + .sku("XYZ12345") + .name("Matomo - The big book about web analytics") + .category("Education & Teaching") + .price(23.1) + .quantity(2) + .build()) + .item( + EcommerceItem.builder() + .sku("B0C2WV3MRJ") + .name("Matomo for data visualization") + .category("Education & Teaching") + .price(15.0) + .quantity(1) + .build()) + .build()) + .visitorId(VisitorId.fromString("customer@mail.com")) + .build()); } catch (Exception e) { throw new RuntimeException("Could not close tracker", e); } - } - } diff --git a/test/src/main/java/org/matomo/java/tracking/test/MatomoServletTester.java b/test/src/main/java/org/matomo/java/tracking/test/MatomoServletTester.java index 0b4d9174..a59c4751 100644 --- a/test/src/main/java/org/matomo/java/tracking/test/MatomoServletTester.java +++ b/test/src/main/java/org/matomo/java/tracking/test/MatomoServletTester.java @@ -18,25 +18,27 @@ public static void main(String[] args) throws Exception { ServletHolder servletHolder = new ServletHolder("default", new DefaultServlet()); servletHolder.setInitParameter( "resourceBase", - MatomoServletTester.class.getClassLoader().getResource("web").toExternalForm() - ); + MatomoServletTester.class.getClassLoader().getResource("web").toExternalForm()); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); context.addServlet(servletHolder, "/"); - context.addFilter(new FilterHolder(new MatomoTrackerFilter(new MatomoTracker( - TrackerConfiguration - .builder() - .apiEndpoint(URI.create("http://localhost:8080/matomo.php")) - .defaultSiteId(1) - .defaultAuthToken("ee6e3dd9ed1b61f5328cf5978b5a8c71") - .logFailedTracking(true) - .build()))), "/*", null); + context.addFilter( + new FilterHolder( + new MatomoTrackerFilter( + new MatomoTracker( + TrackerConfiguration.builder() + .apiEndpoint(URI.create("http://localhost:8080/matomo.php")) + .defaultSiteId(1) + .defaultAuthToken("ee6e3dd9ed1b61f5328cf5978b5a8c71") + .logFailedTracking(true) + .build()))), + "/*", + null); Server server = new Server(8090); server.setHandler(context); server.start(); server.join(); - } -} \ No newline at end of file +} diff --git a/test/src/main/java/org/matomo/java/tracking/test/MatomoTrackerTester.java b/test/src/main/java/org/matomo/java/tracking/test/MatomoTrackerTester.java index 8532c370..f82e71d7 100644 --- a/test/src/main/java/org/matomo/java/tracking/test/MatomoTrackerTester.java +++ b/test/src/main/java/org/matomo/java/tracking/test/MatomoTrackerTester.java @@ -41,13 +41,13 @@ class MatomoTrackerTester implements AutoCloseable { public static void main(String[] args) throws Exception { - TrackerConfiguration configuration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create("http://localhost:8080/matomo.php")) - .defaultSiteId(1) - .defaultAuthToken("ee6e3dd9ed1b61f5328cf5978b5a8c71") - .logFailedTracking(true) - .build(); + TrackerConfiguration configuration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create("http://localhost:8080/matomo.php")) + .defaultSiteId(1) + .defaultAuthToken("124caba9946005ce0be2bf16e05d019f") + .logFailedTracking(true) + .build(); try (MatomoTrackerTester matomoTrackerTester = new MatomoTrackerTester(configuration)) { matomoTrackerTester.sendRequestAsync(); @@ -55,7 +55,6 @@ public static void main(String[] args) throws Exception { matomoTrackerTester.sendRequest(); matomoTrackerTester.sendBulkRequests(); } - } private void sendRequest() { @@ -73,44 +72,45 @@ private void sendBulkRequests() { private void sendRequestAsync() { MatomoRequest request = randomRequest(); CompletableFuture future = tracker.sendRequestAsync(request); - future.thenAccept(v -> log.info("Successfully sent async single request to Matomo server: {}", request)); + future.thenAccept( + v -> log.info("Successfully sent async single request to Matomo server: {}", request)); } private void sendBulkRequestsAsync() { List requests = randomRequests(); tracker .sendBulkRequestAsync(requests) - .thenAccept(v -> log.info("Successfully sent async bulk requests to Matomo server: {}", requests)); + .thenAccept( + v -> log.info("Successfully sent async bulk requests to Matomo server: {}", requests)); } private List randomRequests() { - return IntStream - .range(0, 5) + return IntStream.range(0, 5) .mapToObj(i -> randomRequest()) .collect(Collectors.toCollection(() -> new ArrayList<>(10))); } private MatomoRequest randomRequest() { Country country = faker.country(); - return MatomoRequest - .request() + return MatomoRequest.request() .actionName(faker.funnyName().name()) .actionUrl("https://" + faker.internet().url()) .visitorId(vistors.get(faker.random().nextInt(vistors.size()))) .referrerUrl("https://" + faker.internet().url()) - .visitCustomVariables(new CustomVariables() - .add(new CustomVariable("color", faker.color().hex())) - .add(new CustomVariable("beer", faker.beer().name()))) + .visitCustomVariables( + new CustomVariables() + .add(new CustomVariable("color", faker.color().hex())) + .add(new CustomVariable("beer", faker.beer().name()))) .visitorVisitCount(faker.random().nextInt(10)) .visitorPreviousVisitTimestamp(Instant.now().minusSeconds(faker.random().nextInt(10000))) .visitorFirstVisitTimestamp(Instant.now().minusSeconds(faker.random().nextInt(10000))) .campaignName(faker.dragonBall().character()) .campaignKeyword(faker.buffy().celebrities()) - .deviceResolution(DeviceResolution - .builder() - .width(faker.random().nextInt(1920)) - .height(faker.random().nextInt(1280)) - .build()) + .deviceResolution( + DeviceResolution.builder() + .width(faker.random().nextInt(1920)) + .height(faker.random().nextInt(1280)) + .build()) .currentHour(faker.random().nextInt(24)) .currentMinute(faker.random().nextInt(60)) .currentSecond(faker.random().nextInt(60)) @@ -128,9 +128,10 @@ private MatomoRequest randomRequest() { .userId(faker.random().hex()) .visitorCustomId(VisitorId.random()) .newVisit(true) - .pageCustomVariables(new CustomVariables() - .add(new CustomVariable("job", faker.job().position())) - .add(new CustomVariable("team", faker.team().name()))) + .pageCustomVariables( + new CustomVariables() + .add(new CustomVariable("job", faker.job().position())) + .add(new CustomVariable("team", faker.team().name()))) .outlinkUrl("https://" + faker.internet().url()) .downloadUrl("https://" + faker.internet().url()) .searchQuery(faker.cat().name()) @@ -140,30 +141,31 @@ private MatomoRequest randomRequest() { .goalId(0) .ecommerceRevenue(faker.random().nextInt(50) + faker.random().nextDouble()) .ecommerceId(faker.random().hex()) - .ecommerceItems(EcommerceItems - .builder() - .item(EcommerceItem - .builder() - .sku(faker.random().hex()) - .name(faker.commerce().productName()) - .quantity(faker.random().nextInt(10)) - .price(faker.random().nextInt(100) + faker.random().nextDouble()) - .build()) - .item(EcommerceItem - .builder() - .sku(faker.random().hex()) - .name(faker.commerce().productName()) - .quantity(faker.random().nextInt(10)) - .price(faker.random().nextInt(100) + faker.random().nextDouble()) + .ecommerceItems( + EcommerceItems.builder() + .item( + EcommerceItem.builder() + .sku(faker.random().hex()) + .name(faker.commerce().productName()) + .quantity(faker.random().nextInt(10)) + .price(faker.random().nextInt(100) + faker.random().nextDouble()) + .build()) + .item( + EcommerceItem.builder() + .sku(faker.random().hex()) + .name(faker.commerce().productName()) + .quantity(faker.random().nextInt(10)) + .price(faker.random().nextInt(100) + faker.random().nextDouble()) + .build()) .build()) - .build()) .ecommerceSubtotal(faker.random().nextInt(1000) + faker.random().nextDouble()) .ecommerceTax(faker.random().nextInt(100) + faker.random().nextDouble()) .ecommerceDiscount(faker.random().nextInt(100) + faker.random().nextDouble()) .ecommerceLastOrderTimestamp(Instant.now()) .visitorIp(faker.internet().ipV4Address()) .requestTimestamp(Instant.now()) - .visitorCountry(org.matomo.java.tracking.parameters.Country.fromCode(faker.address().countryCode())) + .visitorCountry( + org.matomo.java.tracking.parameters.Country.fromCode(faker.address().countryCode())) .visitorCity(faker.address().cityName()) .visitorLatitude(faker.random().nextDouble() * 180 - 90) .visitorLongitude(faker.random().nextDouble() * 360 - 180) diff --git a/test/src/main/java/org/matomo/java/tracking/test/SendExample.java b/test/src/main/java/org/matomo/java/tracking/test/SendExample.java index d43bcfc3..8453d7dd 100644 --- a/test/src/main/java/org/matomo/java/tracking/test/SendExample.java +++ b/test/src/main/java/org/matomo/java/tracking/test/SendExample.java @@ -6,9 +6,7 @@ import org.matomo.java.tracking.TrackerConfiguration; import org.matomo.java.tracking.parameters.VisitorId; -/** - * Example for sending a request. - */ +/** Example for sending a request. */ public class SendExample { /** @@ -18,23 +16,21 @@ public class SendExample { */ public static void main(String[] args) { - TrackerConfiguration configuration = TrackerConfiguration - .builder() - .apiEndpoint(URI.create("https://www.yourdomain.com/matomo.php")) - .defaultSiteId(1) - .defaultAuthToken("ee6e3dd9ed1b61f5328cf5978b5a8c71") - .logFailedTracking(true) - .build(); + TrackerConfiguration configuration = + TrackerConfiguration.builder() + .apiEndpoint(URI.create("https://www.yourdomain.com/matomo.php")) + .defaultSiteId(1) + .defaultAuthToken("ee6e3dd9ed1b61f5328cf5978b5a8c71") + .logFailedTracking(true) + .build(); try (MatomoTracker tracker = new MatomoTracker(configuration)) { - tracker.sendRequestAsync(MatomoRequests - .event("Training", "Workout completed", "Bench press", 60.0) - .visitorId(VisitorId.fromString("customer@mail.com")) - .build() - ); + tracker.sendRequestAsync( + MatomoRequests.event("Training", "Workout completed", "Bench press", 60.0) + .visitorId(VisitorId.fromString("customer@mail.com")) + .build()); } catch (Exception e) { throw new RuntimeException("Could not close tracker", e); } } - } diff --git a/test/src/main/java/org/matomo/java/tracking/test/ServletMatomoRequestExample.java b/test/src/main/java/org/matomo/java/tracking/test/ServletMatomoRequestExample.java index 3a2be7a1..dc4135e8 100644 --- a/test/src/main/java/org/matomo/java/tracking/test/ServletMatomoRequestExample.java +++ b/test/src/main/java/org/matomo/java/tracking/test/ServletMatomoRequestExample.java @@ -8,9 +8,7 @@ import org.matomo.java.tracking.servlet.JakartaHttpServletWrapper; import org.matomo.java.tracking.servlet.ServletMatomoRequest; -/** - * This is an example of how to use the ServletMatomoRequest class. - */ +/** This is an example of how to use the ServletMatomoRequest class. */ public class ServletMatomoRequestExample { private final MatomoTracker tracker; @@ -25,19 +23,17 @@ public ServletMatomoRequestExample(MatomoTracker tracker) { * @param request the servlet request */ public void someControllerMethod(HttpServletRequest request) { - MatomoRequest matomoRequest = ServletMatomoRequest - .addServletRequestHeaders( - MatomoRequests.contentImpression( - "Latest Product Announced", - "Main Blog Text", - "https://www.yourdomain.com/blog/2018/10/01/new-product-launches" - ), - JakartaHttpServletWrapper.fromHttpServletRequest(request) - ).visitorId(VisitorId.fromString("customer@mail.com")) - // ... - .build(); + MatomoRequest matomoRequest = + ServletMatomoRequest.addServletRequestHeaders( + MatomoRequests.contentImpression( + "Latest Product Announced", + "Main Blog Text", + "https://www.yourdomain.com/blog/2018/10/01/new-product-launches"), + JakartaHttpServletWrapper.fromHttpServletRequest(request)) + .visitorId(VisitorId.fromString("customer@mail.com")) + // ... + .build(); tracker.sendRequestAsync(matomoRequest); // ... } - } From 7f569b1e9883ee5f7b49aaa246d12cbfa544a3e3 Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Thu, 16 Apr 2026 15:34:42 +0200 Subject: [PATCH 32/71] Remove auto-merge --- .github/workflows/dependabot-auto-merge.yml | 17 ----------------- 1 file changed, 17 deletions(-) delete mode 100644 .github/workflows/dependabot-auto-merge.yml diff --git a/.github/workflows/dependabot-auto-merge.yml b/.github/workflows/dependabot-auto-merge.yml deleted file mode 100644 index 3936911a..00000000 --- a/.github/workflows/dependabot-auto-merge.yml +++ /dev/null @@ -1,17 +0,0 @@ -name: Dependabot auto-merge - -on: pull_request - -jobs: - auto-merge: - runs-on: ubuntu-latest - if: github.actor == 'dependabot[bot]' - permissions: - pull-requests: write - contents: write - steps: - - uses: dependabot/fetch-metadata@v2 - - run: gh pr merge --auto --squash "$PR_URL" - env: - PR_URL: ${{ github.event.pull_request.html_url }} - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} From 3e730aa89add4050d82a44f49c4615c32008e622 Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Thu, 16 Apr 2026 15:37:30 +0200 Subject: [PATCH 33/71] Fix badge --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0bd92494..a715bcdc 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Official Matomo Java Tracker -[![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.piwik.java.tracking/matomo-java-tracker/badge.svg?style=flat)](https://maven-badges.herokuapp.com/maven-central/org.piwik.java.tracking/matomo-java-tracker) +![Maven Central Version](https://img.shields.io/maven-central/v/org.piwik.java.tracking/matomo-java-tracker-core) [![Build Status](https://github.com/matomo-org/matomo-java-tracker/actions/workflows/build.yml/badge.svg)](https://github.com/matomo-org/matomo-java-tracker/actions/workflows/build.yml) [![Average time to resolve an issue](https://isitmaintained.com/badge/resolution/matomo-org/matomo-java-tracker.svg)](https://isitmaintained.com/project/matomo-org/matomo-java-tracker "Average time to resolve an issue") [![Percentage of issues still open](https://isitmaintained.com/badge/open/matomo-org/matomo-java-tracker.svg)](https://isitmaintained.com/project/matomo-org/matomo-java-tracker "Percentage of issues still open") From 0192865eedbc8ce96cc94f8517365642b0af3698 Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Thu, 16 Apr 2026 15:43:38 +0200 Subject: [PATCH 34/71] Update README --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index a715bcdc..ae9c12c8 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Key features: * Customization options: Support for custom dimensions and variables. * Extensive tracking parameters: Capture data on campaigns, events, downloads, outlinks, site searches, devices, and visitors. -* Java compatibility: Supports Java 8 and higher, with a dedicated artifact (matomo-java-tracker-java11) for Java 11. +* Java compatibility: Supports Java 8 and higher, with a dedicated artifact (matomo-java-tracker-java11) for Java 11 or newer. * SSL certificate flexibility: Option to skip SSL certificate validation (caution: not recommended for production). * Minimal runtime dependencies: Relies solely on SLF4J. * Asynchronous request support: Permits non-blocking requests. @@ -28,7 +28,7 @@ Key features: * Seamless integration: Easily integrates into frameworks such as Spring by creating the MatomoTracker Spring bean for use in other beans. -Please prefer the Java 11 version as the Java 8 will become obsolete in the future. +Please prefer the Java 11 or newer version as the Java 8 will become obsolete in the future. You can find our [Developer Guide here](https://developer.matomo.org/api-reference/tracking-java) @@ -101,7 +101,7 @@ Here are the most important changes: * less dependencies * new dimension parameter * special types allow to provide valid parameters now -* a new implementation for Java 11 uses the HttpClient available since Java 11 +* a new implementation for Java 11 or newer uses the HttpClient available since Java 11 See also the [Developer Guide here](https://developer.matomo.org/api-reference/tracking-java) @@ -136,8 +136,8 @@ This project contains the following Maven artifacts: 2. **matomo-java-tracker**: This is a specific implementation of the core module designed for Java 8. It provides the main functionality of the Matomo Java Tracker and is built upon the core. This artifact is specifically designed for applications running on Java 8. -3. **matomo-java-tracker-java11**: This artifact is a Java 11 implementation of the Matomo Java Tracker. It uses the - HttpClient available since Java 11. It is recommended to use this version if you are using Java 11 or higher. +3. **matomo-java-tracker-java11**: This artifact is a Java 11 or newer implementation of the Matomo Java Tracker. It uses the + HttpClient available since Java 11. It is recommended to use this version if you are using Java 11 or newer. 4. **matomo-java-tracker-spring-boot-starter**: This artifact is a Spring Boot Starter for the Matomo Java Tracker. It provides auto-configuration for the Matomo Java Tracker in a Spring Boot application. By including this artifact in your project, you can take advantage of Spring Boot's auto-configuration features to automatically set up and @@ -166,7 +166,7 @@ Add a dependency on Matomo Java Tracker using Maven. For Java 8: ``` -For Java 11: +For Java 11 or newer: ```xml @@ -185,7 +185,7 @@ dependencies { } ``` -or Gradle (Java 11): +or Gradle (Java 11 or newer): ```groovy dependencies { @@ -199,7 +199,7 @@ or Gradle with Kotlin DSL (Java 8) implementation("org.piwik.java.tracking:matomo-java-tracker:3.5.0") ``` -or Gradle with Kotlin DSL (Java 11) +or Gradle with Kotlin DSL (Java 11 or newer) ```kotlin implementation("org.piwik.java.tracking:matomo-java-tracker-java11:3.5.0") From bc4f1a12466422a3ea891ed623648ae13c8de1ef Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Thu, 16 Apr 2026 15:50:30 +0200 Subject: [PATCH 35/71] Improve performance of Java 11 sender --- README.md | 13 ++++++- .../matomo/java/tracking/Java11Sender.java | 34 ++++++++++--------- 2 files changed, 30 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index ae9c12c8..542b507c 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,18 @@ The Spring Boot Starter now requires Spring Boot 4. The `@NonNull` annotation ha Fixed a Java 8 compatibility issue in `JavaxHttpServletWrapper` where `Enumeration.asIterator()` (introduced in Java 9) was used to iterate over HTTP header names. It has been replaced with a standard `while` loop. -Dependency updates: Spring Boot 3.4.2 → 4.0.5, Jetty EE10 12.0.16 → 12.1.8, Jetty (javax) 10.0.24 → 10.0.26. +Zero is now accepted as a valid value for numeric tracking parameters such as `idGoal`, `revenue`, and ecommerce +fields, where it was previously treated as absent and omitted from requests. + +Several performance improvements were made to `Java11Sender`: URL construction no longer uses `String.format`, +the case-insensitive `User-Agent` header lookup no longer allocates a `TreeMap`, `.trim().isEmpty()` checks were +replaced with the Java 11 `.isBlank()` method, and debug log statements are now guarded to avoid allocating +cookie list copies when debug logging is disabled. + +Spotless now automatically removes unused imports during the build. + +Dependency updates: Spring Boot 3.4.2 → 4.0.5, JUnit Jupiter 5.11.4 → 6.0.3, SLF4J 2.0.16 → 2.0.17, +Jetty EE10 12.0.16 → 12.1.8, Jetty (javax) 10.0.24 → 10.0.26. The local testing Docker setup now uses MariaDB 12 and Matomo 5. diff --git a/java11/src/main/java/org/matomo/java/tracking/Java11Sender.java b/java11/src/main/java/org/matomo/java/tracking/Java11Sender.java index feae7c23..9dac1d36 100644 --- a/java11/src/main/java/org/matomo/java/tracking/Java11Sender.java +++ b/java11/src/main/java/org/matomo/java/tracking/Java11Sender.java @@ -14,7 +14,6 @@ import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; -import java.util.TreeMap; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; @@ -77,7 +76,7 @@ private HttpRequest buildHttpPostRequest( if (request.getHeaders() != null && !request.getHeaders().isEmpty()) { headers.putAll(request.getHeaders()); } - if (request.getHeaderUserAgent() != null && !request.getHeaderUserAgent().trim().isEmpty()) { + if (request.getHeaderUserAgent() != null && !request.getHeaderUserAgent().isBlank()) { headerUserAgent = request.getHeaderUserAgent(); } queries.add(queryCreator.createQuery(request, null)); @@ -131,9 +130,7 @@ private HttpRequest buildHttpGetRequest(@NonNull MatomoRequest request) { HttpRequest.newBuilder() .uri( apiEndpoint.resolve( - String.format( - "%s?%s", - apiEndpoint.getPath(), queryCreator.createQuery(request, authToken)))); + apiEndpoint.getPath() + "?" + queryCreator.createQuery(request, authToken))); applyTrackerConfiguration(builder); setUserAgentHeader(builder, request.getHeaderUserAgent(), request.getHeaders()); addHeaders(builder, request.getHeaders()); @@ -142,9 +139,11 @@ private HttpRequest buildHttpGetRequest(@NonNull MatomoRequest request) { private T send(@NonNull HttpRequest httpRequest, @NonNull Callable callable) { try { - log.debug("Sending request to Matomo: {}", httpRequest); - log.debug("Headers: {}", httpRequest.headers()); - log.debug("Cookies: {}", cookieStore.getCookies()); + if (log.isDebugEnabled()) { + log.debug("Sending request to Matomo: {}", httpRequest); + log.debug("Headers: {}", httpRequest.headers()); + log.debug("Cookies: {}", cookieStore.getCookies()); + } return callable.call(); } catch (Exception e) { if (trackerConfiguration.isLogFailedTracking()) { @@ -188,15 +187,18 @@ private void setUserAgentHeader( HttpRequest.Builder builder, @Nullable String headerUserAgent, @Nullable Map headers) { - String userAgentHeader = null; - if ((headerUserAgent == null || headerUserAgent.trim().isEmpty()) && headers != null) { - TreeMap caseInsensitiveMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); - caseInsensitiveMap.putAll(headers); - userAgentHeader = caseInsensitiveMap.get("User-Agent"); + boolean noExplicitUserAgent = headerUserAgent == null || headerUserAgent.isBlank(); + if (!noExplicitUserAgent) { + return; + } + if (headers != null) { + for (Map.Entry entry : headers.entrySet()) { + if ("User-Agent".equalsIgnoreCase(entry.getKey()) && entry.getValue() != null && !entry.getValue().isBlank()) { + return; + } + } } - if ((userAgentHeader == null || userAgentHeader.trim().isEmpty()) - && (headerUserAgent == null || headerUserAgent.trim().isEmpty()) - && trackerConfiguration.getUserAgent() != null + if (trackerConfiguration.getUserAgent() != null && !trackerConfiguration.getUserAgent().isEmpty()) { builder.header("User-Agent", trackerConfiguration.getUserAgent()); } From 7faff0b80ee0f613ea770f0b2cf1435dde1dc0be Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Thu, 16 Apr 2026 16:03:47 +0200 Subject: [PATCH 36/71] Improve performance of core --- .../matomo/java/tracking/DaemonThreadFactory.java | 3 +-- .../java/org/matomo/java/tracking/QueryCreator.java | 9 ++++++--- .../matomo/java/tracking/TrackerConfiguration.java | 2 +- .../java/tracking/parameters/AcceptLanguage.java | 2 +- .../java/tracking/parameters/DeviceResolution.java | 2 +- .../java/tracking/parameters/EcommerceItem.java | 2 +- .../org/matomo/java/tracking/parameters/Hex.java | 4 +++- .../java/tracking/servlet/ServletMatomoRequest.java | 13 +++++++------ .../java/org/matomo/java/tracking/Java11Sender.java | 4 +++- 9 files changed, 24 insertions(+), 17 deletions(-) diff --git a/core/src/main/java/org/matomo/java/tracking/DaemonThreadFactory.java b/core/src/main/java/org/matomo/java/tracking/DaemonThreadFactory.java index 72e1bf0f..9b0a9cd2 100644 --- a/core/src/main/java/org/matomo/java/tracking/DaemonThreadFactory.java +++ b/core/src/main/java/org/matomo/java/tracking/DaemonThreadFactory.java @@ -10,8 +10,7 @@ class DaemonThreadFactory implements ThreadFactory { @Override public Thread newThread(@NonNull Runnable r) { - Thread thread = - new Thread(null, r, String.format("MatomoJavaTracker-%d", count.getAndIncrement())); + Thread thread = new Thread(null, r, "MatomoJavaTracker-" + count.getAndIncrement()); thread.setDaemon(true); return thread; } diff --git a/core/src/main/java/org/matomo/java/tracking/QueryCreator.java b/core/src/main/java/org/matomo/java/tracking/QueryCreator.java index 04a3967e..a824dedb 100644 --- a/core/src/main/java/org/matomo/java/tracking/QueryCreator.java +++ b/core/src/main/java/org/matomo/java/tracking/QueryCreator.java @@ -91,9 +91,12 @@ String createQuery(@NonNull MatomoRequest request, @Nullable String authToken) { if (request.getAdditionalParameters() != null) { for (Entry entry : request.getAdditionalParameters().entrySet()) { Object value = entry.getValue(); - if (value != null && !value.toString().trim().isEmpty()) { - appendAmpersand(query); - query.append(encode(entry.getKey())).append('=').append(encode(value.toString())); + if (value != null) { + String valueString = value.toString(); + if (!valueString.isEmpty() && !valueString.trim().isEmpty()) { + appendAmpersand(query); + query.append(encode(entry.getKey())).append('=').append(encode(valueString)); + } } } } diff --git a/core/src/main/java/org/matomo/java/tracking/TrackerConfiguration.java b/core/src/main/java/org/matomo/java/tracking/TrackerConfiguration.java index 39aa8df2..110ae027 100644 --- a/core/src/main/java/org/matomo/java/tracking/TrackerConfiguration.java +++ b/core/src/main/java/org/matomo/java/tracking/TrackerConfiguration.java @@ -124,7 +124,7 @@ public void validate() { throw new IllegalArgumentException("API endpoint must not be null"); } if (defaultAuthToken != null) { - if (defaultAuthToken.trim().length() != 32) { + if (defaultAuthToken.length() != 32) { throw new IllegalArgumentException("Auth token must be exactly 32 characters long"); } if (!AUTH_TOKEN_PATTERN.matcher(defaultAuthToken).matches()) { diff --git a/core/src/main/java/org/matomo/java/tracking/parameters/AcceptLanguage.java b/core/src/main/java/org/matomo/java/tracking/parameters/AcceptLanguage.java index cb4ea46e..d30aadaa 100644 --- a/core/src/main/java/org/matomo/java/tracking/parameters/AcceptLanguage.java +++ b/core/src/main/java/org/matomo/java/tracking/parameters/AcceptLanguage.java @@ -64,6 +64,6 @@ public String toString() { private static String format(@NonNull LanguageRange languageRange) { return languageRange.getWeight() == LanguageRange.MAX_WEIGHT ? languageRange.getRange() - : String.format("%s;q=%s", languageRange.getRange(), languageRange.getWeight()); + : languageRange.getRange() + ";q=" + languageRange.getWeight(); } } diff --git a/core/src/main/java/org/matomo/java/tracking/parameters/DeviceResolution.java b/core/src/main/java/org/matomo/java/tracking/parameters/DeviceResolution.java index f466dd83..684b054f 100644 --- a/core/src/main/java/org/matomo/java/tracking/parameters/DeviceResolution.java +++ b/core/src/main/java/org/matomo/java/tracking/parameters/DeviceResolution.java @@ -48,6 +48,6 @@ public static DeviceResolution fromString(@Nullable String deviceResolution) { @Override public String toString() { - return String.format("%dx%d", width, height); + return width + "x" + height; } } diff --git a/core/src/main/java/org/matomo/java/tracking/parameters/EcommerceItem.java b/core/src/main/java/org/matomo/java/tracking/parameters/EcommerceItem.java index 124158f8..59821849 100644 --- a/core/src/main/java/org/matomo/java/tracking/parameters/EcommerceItem.java +++ b/core/src/main/java/org/matomo/java/tracking/parameters/EcommerceItem.java @@ -30,6 +30,6 @@ public class EcommerceItem { @Builder.Default private Integer quantity = 0; public String toString() { - return String.format("[\"%s\",\"%s\",\"%s\",%s,%d]", sku, name, category, price, quantity); + return "[\"" + sku + "\",\"" + name + "\",\"" + category + "\"," + price + "," + quantity + "]"; } } diff --git a/core/src/main/java/org/matomo/java/tracking/parameters/Hex.java b/core/src/main/java/org/matomo/java/tracking/parameters/Hex.java index f6b12c92..cc007506 100644 --- a/core/src/main/java/org/matomo/java/tracking/parameters/Hex.java +++ b/core/src/main/java/org/matomo/java/tracking/parameters/Hex.java @@ -11,6 +11,8 @@ final class Hex { + private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray(); + private Hex() { // utility class } @@ -18,7 +20,7 @@ private Hex() { static String fromBytes(@NonNull byte[] bytes) { StringBuilder result = new StringBuilder(bytes.length * 2); for (byte b : bytes) { - result.append(String.format("%02x", b)); + result.append(HEX_CHARS[(b >> 4) & 0xF]).append(HEX_CHARS[b & 0xF]); } return result.toString(); } diff --git a/core/src/main/java/org/matomo/java/tracking/servlet/ServletMatomoRequest.java b/core/src/main/java/org/matomo/java/tracking/servlet/ServletMatomoRequest.java index 7ec30f8b..9dbb4e7c 100644 --- a/core/src/main/java/org/matomo/java/tracking/servlet/ServletMatomoRequest.java +++ b/core/src/main/java/org/matomo/java/tracking/servlet/ServletMatomoRequest.java @@ -126,18 +126,19 @@ private static void processCookie( @edu.umd.cs.findbugs.annotations.NonNull Map cookies, @edu.umd.cs.findbugs.annotations.NonNull String cookieName, @edu.umd.cs.findbugs.annotations.NonNull String cookieValue) { - if (cookieName.toLowerCase(Locale.ROOT).startsWith("_pk_id")) { + String lowerCookieName = cookieName.toLowerCase(Locale.ROOT); + if (lowerCookieName.startsWith("_pk_id")) { extractVisitorId(builder, cookies, cookieValue, cookieName); } - if (cookieName.toLowerCase(Locale.ROOT).equalsIgnoreCase("MATOMO_SESSID")) { + if (lowerCookieName.equals("matomo_sessid")) { builder.sessionId(cookieValue); } - if (cookieName.toLowerCase(Locale.ROOT).startsWith("_pk_ses") - || cookieName.toLowerCase(Locale.ROOT).startsWith("_pk_ref") - || cookieName.toLowerCase(Locale.ROOT).startsWith("_pk_hsr")) { + if (lowerCookieName.startsWith("_pk_ses") + || lowerCookieName.startsWith("_pk_ref") + || lowerCookieName.startsWith("_pk_hsr")) { cookies.put(cookieName, cookieValue); } - if (cookieName.toLowerCase(Locale.ROOT).startsWith("_pk_cvar")) { + if (lowerCookieName.startsWith("_pk_cvar")) { builder.visitCustomVariables(CustomVariables.parse(cookieValue)); } } diff --git a/java11/src/main/java/org/matomo/java/tracking/Java11Sender.java b/java11/src/main/java/org/matomo/java/tracking/Java11Sender.java index 9dac1d36..057c434b 100644 --- a/java11/src/main/java/org/matomo/java/tracking/Java11Sender.java +++ b/java11/src/main/java/org/matomo/java/tracking/Java11Sender.java @@ -193,7 +193,9 @@ private void setUserAgentHeader( } if (headers != null) { for (Map.Entry entry : headers.entrySet()) { - if ("User-Agent".equalsIgnoreCase(entry.getKey()) && entry.getValue() != null && !entry.getValue().isBlank()) { + if ("User-Agent".equalsIgnoreCase(entry.getKey()) + && entry.getValue() != null + && !entry.getValue().isBlank()) { return; } } From 8613fd39d499829b7145738059f82babbf1dec0e Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Thu, 16 Apr 2026 16:05:24 +0200 Subject: [PATCH 37/71] Update README --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 542b507c..220bb08f 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,13 @@ the case-insensitive `User-Agent` header lookup no longer allocates a `TreeMap`, replaced with the Java 11 `.isBlank()` method, and debug log statements are now guarded to avoid allocating cookie list copies when debug logging is disabled. +Several performance improvements were also made to the core module: hex encoding in `VisitorId` now uses a +lookup table instead of `String.format` per byte, `String.format` calls in `DeviceResolution`, `AcceptLanguage`, +`EcommerceItem`, and `DaemonThreadFactory` were replaced with string concatenation, `ServletMatomoRequest` now +computes `cookieName.toLowerCase()` once per cookie instead of six times, `QueryCreator` caches the +`value.toString()` result to avoid calling it twice, and redundant double-check patterns such as +`isEmpty() || trim().isEmpty()` were simplified throughout. + Spotless now automatically removes unused imports during the build. Dependency updates: Spring Boot 3.4.2 → 4.0.5, JUnit Jupiter 5.11.4 → 6.0.3, SLF4J 2.0.16 → 2.0.17, From b49e47c1d7aaa87d96e025f1d37b0a45838fd71f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 16 Apr 2026 16:11:20 +0200 Subject: [PATCH 38/71] build(deps-dev): bump org.owasp:dependency-check-maven from 12.2.0 to 12.2.1 (#393) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Daniel Heid --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index a11d1a70..a794732f 100644 --- a/pom.xml +++ b/pom.xml @@ -368,7 +368,7 @@ org.owasp dependency-check-maven - 12.2.0 + 12.2.1 true From 41ff29905e49a1d27c9da5e07829d6a3edde47af Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 16 Apr 2026 16:11:46 +0200 Subject: [PATCH 39/71] build(deps-dev): bump org.eclipse.jetty.ee10:jetty-ee10-servlet from 12.0.16 to 12.1.8 (#390) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Daniel Heid --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index a794732f..252fb30d 100644 --- a/pom.xml +++ b/pom.xml @@ -117,7 +117,7 @@ org.eclipse.jetty.ee10 jetty-ee10-servlet - 12.0.16 + 12.1.8 From 1d3d95576e9a305c171667f0eda64ceb93e43576 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 16 Apr 2026 16:12:16 +0200 Subject: [PATCH 40/71] build(deps-dev): bump com.github.spotbugs:spotbugs-maven-plugin from 4.9.8.2 to 4.9.8.3 (#389) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Daniel Heid --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 252fb30d..110e4563 100644 --- a/pom.xml +++ b/pom.xml @@ -363,7 +363,7 @@ com.github.spotbugs spotbugs-maven-plugin - 4.9.8.2 + 4.9.8.3 org.owasp From 6bcae48cc642dc0ff0a8e10d17a09392477a85e1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 16 Apr 2026 16:12:25 +0200 Subject: [PATCH 41/71] build(deps-dev): bump org.apache.maven.plugins:maven-source-plugin from 3.3.1 to 3.4.0 (#388) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Daniel Heid --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 110e4563..c6d85c65 100644 --- a/pom.xml +++ b/pom.xml @@ -226,7 +226,7 @@ org.apache.maven.plugins maven-source-plugin - 3.3.1 + 3.4.0 attach-sources From c27ac207e58647e12905ae0432909d6d0bd8898c Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Thu, 16 Apr 2026 16:19:37 +0200 Subject: [PATCH 42/71] #165 Update Versions in README.md during Release Workflow --- .github/workflows/release.yml | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3ab20fb0..3558c16d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -21,13 +21,33 @@ jobs: git config user.name "Matomo Java Tracker" - id: version run: | - VERSION=$( mvn -B help:evaluate -Dexpression=project.version -q -DforceStdout ) - echo "::set-output name=version::${VERSION%-SNAPSHOT}" + VERSION=$(mvn -B help:evaluate -Dexpression=project.version -q -DforceStdout) + echo "version=${VERSION%-SNAPSHOT}" >> $GITHUB_OUTPUT - run: mvn -B release:prepare release:perform env: OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }} OSSRH_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} + - name: Update README.md with release version + env: + RELEASE_VERSION: ${{ steps.version.outputs.version }} + run: | + # Update tags in Maven XML snippets. + # The pattern intentionally excludes -SNAPSHOT versions because the regex + # requires to follow immediately after the numeric version. + sed -i -E \ + "s|[0-9]+\.[0-9]+\.[0-9]+|${RELEASE_VERSION}|g" \ + README.md + # Update version in Gradle dependency snippets (Groovy and Kotlin DSL). + # Matches the groupId:artifactId:version pattern for this project's artifacts. + sed -i -E \ + "s|(org\.piwik\.java\.tracking:[^:\"]+:)[0-9]+\.[0-9]+\.[0-9]+|\1${RELEASE_VERSION}|g" \ + README.md + git add README.md + # Only commit if the file actually changed (idempotent on re-runs). + git diff --cached --quiet || \ + git commit -m "[ci skip] Update README.md dependency snippets to ${RELEASE_VERSION}" + git push - uses: release-drafter/release-drafter@v7 with: version: ${{ steps.version.outputs.version }} From d97acc5443b7640c7399b774b542cc5b8667e323 Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Thu, 16 Apr 2026 16:24:54 +0200 Subject: [PATCH 43/71] Revert "#165 Update Versions in README.md during Release Workflow" This reverts commit c27ac207e58647e12905ae0432909d6d0bd8898c. --- .github/workflows/release.yml | 24 ++---------------------- 1 file changed, 2 insertions(+), 22 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3558c16d..3ab20fb0 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -21,33 +21,13 @@ jobs: git config user.name "Matomo Java Tracker" - id: version run: | - VERSION=$(mvn -B help:evaluate -Dexpression=project.version -q -DforceStdout) - echo "version=${VERSION%-SNAPSHOT}" >> $GITHUB_OUTPUT + VERSION=$( mvn -B help:evaluate -Dexpression=project.version -q -DforceStdout ) + echo "::set-output name=version::${VERSION%-SNAPSHOT}" - run: mvn -B release:prepare release:perform env: OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }} OSSRH_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} - - name: Update README.md with release version - env: - RELEASE_VERSION: ${{ steps.version.outputs.version }} - run: | - # Update tags in Maven XML snippets. - # The pattern intentionally excludes -SNAPSHOT versions because the regex - # requires to follow immediately after the numeric version. - sed -i -E \ - "s|[0-9]+\.[0-9]+\.[0-9]+|${RELEASE_VERSION}|g" \ - README.md - # Update version in Gradle dependency snippets (Groovy and Kotlin DSL). - # Matches the groupId:artifactId:version pattern for this project's artifacts. - sed -i -E \ - "s|(org\.piwik\.java\.tracking:[^:\"]+:)[0-9]+\.[0-9]+\.[0-9]+|\1${RELEASE_VERSION}|g" \ - README.md - git add README.md - # Only commit if the file actually changed (idempotent on re-runs). - git diff --cached --quiet || \ - git commit -m "[ci skip] Update README.md dependency snippets to ${RELEASE_VERSION}" - git push - uses: release-drafter/release-drafter@v7 with: version: ${{ steps.version.outputs.version }} From d17eb43b4217b460137ad1aa48be0de7bc3422c6 Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Thu, 16 Apr 2026 16:39:43 +0200 Subject: [PATCH 44/71] Add more tracking parameters for user agent data, ecommerce product, bot recording mode, HTTP status, bandwidth, source label and media attributes. --- README.md | 3 + .../matomo/java/tracking/MatomoRequest.java | 165 ++++++++++++++ .../java/tracking/QueryCreatorTest.java | 201 ++++++++++++++++++ 3 files changed, 369 insertions(+) diff --git a/README.md b/README.md index 220bb08f..9d13f6c4 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,9 @@ Projects that use Matomo Java Tracker: ### Version 3.5.x +Added more tracking parameters for user agent data, ecommerce product, bot recording mode, HTTP status, bandwidth, +source label and media attributes. + The Spring Boot Starter now requires Spring Boot 4. The `@NonNull` annotation has been migrated from `org.springframework.lang.NonNull` to `org.jspecify.annotations.NonNull` across the Spring module. The `PropertyMapper` usage was updated to align with the Spring Boot 4 API (`alwaysApplyingWhenNonNull()` was removed). diff --git a/core/src/main/java/org/matomo/java/tracking/MatomoRequest.java b/core/src/main/java/org/matomo/java/tracking/MatomoRequest.java index 8c17fd35..7a71bc86 100644 --- a/core/src/main/java/org/matomo/java/tracking/MatomoRequest.java +++ b/core/src/main/java/org/matomo/java/tracking/MatomoRequest.java @@ -210,6 +210,16 @@ public class MatomoRequest { @TrackingParameter(name = "ua") private String headerUserAgent; + /** + * JSON-encoded User Agent + * Client Hints collected by JavaScript. Used to enrich the detected user agent data. + * + *

Example: {@code {"brands":[{"brand":"Chromium","version":"110"}],"mobile":false}} + */ + @TrackingParameter(name = "uadata") + private String clientHints; + /** * An override value for the Accept-Language HTTP header field. This value is used to detect the * visitor's country if GeoIP is not enabled. @@ -407,6 +417,40 @@ public class MatomoRequest { @TrackingParameter(name = "_ects") private Instant ecommerceLastOrderTimestamp; + /** + * The SKU of the product being viewed. Used for ecommerce product page tracking. + * + *

Requires {@code idgoal=0} and {@code _pks} to be set. + */ + @TrackingParameter(name = "_pks") + private String ecommerceProductSku; + + /** + * The name of the product being viewed. Used for ecommerce product page tracking. + * + *

Requires {@code idgoal=0} and {@code _pks} to be set. + */ + @TrackingParameter(name = "_pkn") + private String ecommerceProductName; + + /** + * The category of the product being viewed. Used for ecommerce product page tracking. + * + *

Can be a string or a JSON-encoded array of up to five category names. + * + *

Requires {@code idgoal=0} and {@code _pks} to be set. + */ + @TrackingParameter(name = "_pkc") + private String ecommerceProductCategory; + + /** + * The price of the product being viewed. Used for ecommerce product page tracking. + * + *

Requires {@code idgoal=0} and {@code _pks} to be set. + */ + @TrackingParameter(name = "_pkp", min = 0) + private Double ecommerceProductPrice; + /** * 32 character authorization key used to authenticate the API request. We recommend to create a * user specifically for accessing the Tracking API, and give the user only write permission on @@ -486,6 +530,34 @@ public class MatomoRequest { @TrackingParameter(name = "bots") private Boolean trackBotRequests; + /** + * When {@code bots=1} is set, this specifies the recording mode for bot requests. + * + *

Set to {@code 1} to record bot requests without triggering any goals, events or actions. + */ + @TrackingParameter(name = "recMode") + private Integer botRecordingMode; + + /** + * The HTTP status code of the tracked request. Used with bot tracking. + * + *

When tracking a bot visit, this can be set to the HTTP status code of the bot's request. + */ + @TrackingParameter(name = "http_status") + private Integer httpStatusCode; + + /** The bandwidth used for the tracked request in bytes. Used with bot tracking. */ + @TrackingParameter(name = "bw_bytes", min = 0) + private Long bandwidthBytes; + + /** + * Defines the source of the tracking request (e.g., {@code "backend"} or {@code "mobile-app"}). + * + *

Used to classify where the tracking hit originated. + */ + @TrackingParameter(name = "source") + private String sourceLabel; + /** * Meant to hold a random value that is generated before each request. Using it helps avoid the * tracking request being cached by the browser or a proxy. @@ -501,6 +573,99 @@ public class MatomoRequest { @TrackingParameter(name = "debug") private Boolean debug; + /** + * A unique ID used to identify the media. Part of the Media Analytics plugin. + */ + @TrackingParameter(name = "ma_id") + private String mediaId; + + /** + * The title of the media resource. Part of the Media Analytics plugin. + */ + @TrackingParameter(name = "ma_ti") + private String mediaTitle; + + /** + * The URL of the media resource. Part of the Media Analytics plugin. + */ + @TrackingParameter(name = "ma_re") + private String mediaResource; + + /** + * The type of media, e.g. {@code "video"} or {@code "audio"}. Part of the Media Analytics plugin. + */ + @TrackingParameter(name = "ma_mt") + private String mediaType; + + /** + * The name of the media player used to play the media, e.g. {@code "html5"}. Part of the Media Analytics plugin. + */ + @TrackingParameter(name = "ma_pn") + private String mediaPlayerName; + + /** + * The number of seconds the visitor has spent playing/watching the media resource so far. Part of + * the Media Analytics plugin. + */ + @TrackingParameter(name = "ma_st", min = 0) + private Integer mediaTimeSpent; + + /** + * The total duration / length of the media resource in seconds. Part of the Media Analytics plugin. + */ + @TrackingParameter(name = "ma_le", min = 0) + private Integer mediaLength; + + /** + * The current progress of the media in percent (0–100). Part of the Media Analytics plugin. + */ + @TrackingParameter(name = "ma_ps", min = 0, max = 100) + private Integer mediaProgressPercent; + + /** + * How many seconds it took before the media started playing. Part of the Media Analytics plugin. + */ + @TrackingParameter(name = "ma_ttp", min = 0) + private Integer mediaTimeToPlay; + + /** + * The width of the media player in pixels. Part of the Media Analytics plugin. + */ + @TrackingParameter(name = "ma_w", min = 0) + private Integer mediaWidth; + + /** + * The height of the media player in pixels. Part of the Media Analytics plugin. + */ + @TrackingParameter(name = "ma_h", min = 0) + private Integer mediaHeight; + + /** + * Whether the media is currently displayed in fullscreen. Part of the Media Analytics plugin. + */ + @TrackingParameter(name = "ma_fs") + private Boolean mediaFullscreen; + + /** + * A JSON-encoded array of which positions in the media were viewed by the visitor. Part of the Media Analytics plugin. + * + *

Example: {@code [[0,15],[30,44]]} means the visitor watched segments 0–15s and 30–44s. + */ + @TrackingParameter(name = "ma_se") + private String mediaSegmentsViewed; + /** * Contains an error message describing the error that occurred during the last tracking request. * diff --git a/core/src/test/java/org/matomo/java/tracking/QueryCreatorTest.java b/core/src/test/java/org/matomo/java/tracking/QueryCreatorTest.java index 6201562c..0d5a18b5 100644 --- a/core/src/test/java/org/matomo/java/tracking/QueryCreatorTest.java +++ b/core/src/test/java/org/matomo/java/tracking/QueryCreatorTest.java @@ -618,4 +618,205 @@ void allowsZeroForEcommerceValues() { + "send_image=0&" + "rand=random-value"); } + + @Test + void includesClientHints() { + matomoRequestBuilder.clientHints( + "{\"brands\":[{\"brand\":\"Chromium\",\"version\":\"110\"}],\"mobile\":false}"); + + whenCreatesQuery(); + + assertThat(query) + .contains( + "uadata=%7B%22brands%22%3A%5B%7B%22brand%22%3A%22Chromium%22%2C%22version%22%3A%22110%22%7D%5D%2C%22mobile%22%3Afalse%7D"); + } + + @Test + void includesEcommerceProductView() { + matomoRequestBuilder + .ecommerceProductSku("SKU-123") + .ecommerceProductName("Blue Widget") + .ecommerceProductCategory("Widgets") + .ecommerceProductPrice(9.99); + + whenCreatesQuery(); + + assertThat(query) + .contains("_pks=SKU-123") + .contains("_pkn=Blue+Widget") + .contains("_pkc=Widgets") + .contains("_pkp=9.99"); + } + + @Test + void allowsZeroForEcommerceProductPrice() { + matomoRequestBuilder.ecommerceProductSku("SKU-FREE").ecommerceProductPrice(0.0); + + whenCreatesQuery(); + + assertThat(query).contains("_pks=SKU-FREE").contains("_pkp=0.0"); + } + + @Test + void failsIfEcommerceProductPriceIsNegative() { + matomoRequestBuilder.ecommerceProductPrice(-1.0); + + assertThatThrownBy(this::whenCreatesQuery) + .isInstanceOf(MatomoException.class) + .hasMessage("Could not append parameter") + .hasRootCauseMessage("Invalid value for _pkp. Must be greater or equal than 0"); + } + + @Test + void includesBotTrackingParameters() { + matomoRequestBuilder + .trackBotRequests(true) + .botRecordingMode(1) + .httpStatusCode(200) + .bandwidthBytes(1024L) + .sourceLabel("backend"); + + whenCreatesQuery(); + + assertThat(query) + .contains("bots=1") + .contains("recMode=1") + .contains("http_status=200") + .contains("bw_bytes=1024") + .contains("source=backend"); + } + + @Test + void allowsZeroForBandwidthBytes() { + matomoRequestBuilder.bandwidthBytes(0L); + + whenCreatesQuery(); + + assertThat(query).contains("bw_bytes=0"); + } + + @Test + void failsIfBandwidthBytesIsNegative() { + matomoRequestBuilder.bandwidthBytes(-1L); + + assertThatThrownBy(this::whenCreatesQuery) + .isInstanceOf(MatomoException.class) + .hasMessage("Could not append parameter") + .hasRootCauseMessage("Invalid value for bw_bytes. Must be greater or equal than 0"); + } + + @Test + void includesMediaAnalyticsParameters() { + matomoRequestBuilder + .mediaId("media-abc123") + .mediaTitle("My Video") + .mediaResource("https://example.com/video.mp4") + .mediaType("video") + .mediaPlayerName("html5") + .mediaTimeSpent(42) + .mediaLength(120) + .mediaProgressPercent(35) + .mediaTimeToPlay(3) + .mediaWidth(1280) + .mediaHeight(720) + .mediaFullscreen(false) + .mediaSegmentsViewed("[[0,42]]"); + + whenCreatesQuery(); + + assertThat(query) + .contains("ma_id=media-abc123") + .contains("ma_ti=My+Video") + .contains("ma_re=https%3A%2F%2Fexample.com%2Fvideo.mp4") + .contains("ma_mt=video") + .contains("ma_pn=html5") + .contains("ma_st=42") + .contains("ma_le=120") + .contains("ma_ps=35") + .contains("ma_ttp=3") + .contains("ma_w=1280") + .contains("ma_h=720") + .contains("ma_fs=0") + .contains("ma_se=%5B%5B0%2C42%5D%5D"); + } + + @Test + void allowsZeroForMediaTimeValues() { + matomoRequestBuilder.mediaTimeSpent(0).mediaLength(0).mediaTimeToPlay(0); + + whenCreatesQuery(); + + assertThat(query).contains("ma_st=0").contains("ma_le=0").contains("ma_ttp=0"); + } + + @Test + void failsIfMediaTimeSpentIsNegative() { + matomoRequestBuilder.mediaTimeSpent(-1); + + assertThatThrownBy(this::whenCreatesQuery) + .isInstanceOf(MatomoException.class) + .hasMessage("Could not append parameter") + .hasRootCauseMessage("Invalid value for ma_st. Must be greater or equal than 0"); + } + + @Test + void failsIfMediaLengthIsNegative() { + matomoRequestBuilder.mediaLength(-1); + + assertThatThrownBy(this::whenCreatesQuery) + .isInstanceOf(MatomoException.class) + .hasMessage("Could not append parameter") + .hasRootCauseMessage("Invalid value for ma_le. Must be greater or equal than 0"); + } + + @Test + void failsIfMediaProgressPercentIsNegative() { + matomoRequestBuilder.mediaProgressPercent(-1); + + assertThatThrownBy(this::whenCreatesQuery) + .isInstanceOf(MatomoException.class) + .hasMessage("Could not append parameter") + .hasRootCauseMessage("Invalid value for ma_ps. Must be greater or equal than 0"); + } + + @Test + void failsIfMediaProgressPercentExceeds100() { + matomoRequestBuilder.mediaProgressPercent(101); + + assertThatThrownBy(this::whenCreatesQuery) + .isInstanceOf(MatomoException.class) + .hasMessage("Could not append parameter") + .hasRootCauseMessage("Invalid value for ma_ps. Must be less or equal than 100"); + } + + @Test + void allowsZeroAndMaxForMediaProgressPercent() { + matomoRequestBuilder.mediaProgressPercent(0); + whenCreatesQuery(); + assertThat(query).contains("ma_ps=0"); + + matomoRequestBuilder.mediaProgressPercent(100); + whenCreatesQuery(); + assertThat(query).contains("ma_ps=100"); + } + + @Test + void failsIfMediaWidthIsNegative() { + matomoRequestBuilder.mediaWidth(-1); + + assertThatThrownBy(this::whenCreatesQuery) + .isInstanceOf(MatomoException.class) + .hasMessage("Could not append parameter") + .hasRootCauseMessage("Invalid value for ma_w. Must be greater or equal than 0"); + } + + @Test + void failsIfMediaHeightIsNegative() { + matomoRequestBuilder.mediaHeight(-1); + + assertThatThrownBy(this::whenCreatesQuery) + .isInstanceOf(MatomoException.class) + .hasMessage("Could not append parameter") + .hasRootCauseMessage("Invalid value for ma_h. Must be greater or equal than 0"); + } } From 0a969da2025e81d185313df3fc26fe93c8192098 Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Thu, 16 Apr 2026 21:05:03 +0200 Subject: [PATCH 45/71] Add dependabot automerge --- .github/workflows/dependabot-automerge.yml | 28 ++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 .github/workflows/dependabot-automerge.yml diff --git a/.github/workflows/dependabot-automerge.yml b/.github/workflows/dependabot-automerge.yml new file mode 100644 index 00000000..8580f46f --- /dev/null +++ b/.github/workflows/dependabot-automerge.yml @@ -0,0 +1,28 @@ +name: Dependabot auto-merge + +on: pull_request + +permissions: + contents: write + pull-requests: write + +jobs: + dependabot: + runs-on: ubuntu-latest + if: github.actor == 'dependabot[bot]' + steps: + - name: Fetch Dependabot metadata + id: metadata + uses: dependabot/fetch-metadata@v3.0.0 + with: + github-token: "${{ secrets.GITHUB_TOKEN }}" + - name: Approve pull request + run: gh pr review --approve "$PR_URL" + env: + PR_URL: ${{ github.event.pull_request.html_url }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Enable auto-merge + run: gh pr merge --auto --squash "$PR_URL" + env: + PR_URL: ${{ github.event.pull_request.html_url }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} From 119e965835ec7a33ab0390ac881406076aee8829 Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Sat, 18 Apr 2026 10:47:19 +0200 Subject: [PATCH 46/71] Add personal access token to release workflow --- .github/workflows/release.yml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3ab20fb0..85398fcc 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -6,6 +6,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 + with: + token: ${{ secrets.RELEASE_PAT }} + persist-credentials: true - uses: actions/setup-java@v5 with: java-version: '17' @@ -22,7 +25,7 @@ jobs: - id: version run: | VERSION=$( mvn -B help:evaluate -Dexpression=project.version -q -DforceStdout ) - echo "::set-output name=version::${VERSION%-SNAPSHOT}" + echo "version=${VERSION%-SNAPSHOT}" >> "$GITHUB_OUTPUT" - run: mvn -B release:prepare release:perform env: OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }} @@ -33,4 +36,4 @@ jobs: version: ${{ steps.version.outputs.version }} publish: true env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From a6702e4ea5a21130ffa5c493cd4a7fe1b43309db Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Sun, 19 Apr 2026 15:23:40 +0200 Subject: [PATCH 47/71] Update release workflow and improve documentation publishing --- .github/workflows/build.yml | 42 +++++++++++++++++++++++++-- .github/workflows/gh-pages.yml | 32 -------------------- .github/workflows/release-drafter.yml | 32 ++++++++++++++++++++ .github/workflows/release.yml | 13 ++------- pom.xml | 22 +++++--------- 5 files changed, 82 insertions(+), 59 deletions(-) delete mode 100644 .github/workflows/gh-pages.yml create mode 100644 .github/workflows/release-drafter.yml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1711ae4b..48632fcf 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -2,9 +2,11 @@ name: Java CI with Maven on: push: - branches: [ main ] + branches: + - main pull_request: - branches: [ main ] + branches: + - main jobs: build: @@ -21,10 +23,44 @@ jobs: distribution: 'temurin' cache: maven - run: mvn -B verify + - uses: dorny/test-reporter@v3 + if: always() + with: + name: JUnit Tests + path: '**/target/surefire-reports/TEST-*.xml' + reporter: java-junit + fail-on-error: false - uses: madrapps/jacoco-report@v1.7.2 with: paths: ${{ github.workspace }}/target/site/jacoco/jacoco.xml token: ${{ secrets.GITHUB_TOKEN }} min-coverage-overall: 80 min-coverage-changed-files: 80 - - uses: scacap/action-surefire-report@v1.9.1 \ No newline at end of file + - uses: actions/configure-pages@v6 + if: github.ref == 'refs/heads/main' + - uses: actions/jekyll-build-pages@v1 + if: github.ref == 'refs/heads/main' + with: + destination: ./page + - if: github.ref == 'refs/heads/main' + run: | + mkdir -p _site/apidocs _site/coverage + cp -r page/. _site/ + cp -r target/reports/apidocs/. _site/apidocs/ + cp -r target/site/jacoco/. _site/coverage/ + - uses: actions/upload-pages-artifact@v5 + if: github.ref == 'refs/heads/main' + + publish-docs: + needs: build + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deploy.outputs.page_url }} + steps: + - id: deploy + uses: actions/deploy-pages@v4 diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml deleted file mode 100644 index 5cbcb16e..00000000 --- a/.github/workflows/gh-pages.yml +++ /dev/null @@ -1,32 +0,0 @@ -name: Deploy GitHub Pages -on: - push: - branches: ["main"] - workflow_dispatch: -permissions: - contents: read - pages: write - id-token: write -concurrency: - group: "pages" - cancel-in-progress: false -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v6 - - uses: actions/configure-pages@v6 - - uses: actions/jekyll-build-pages@v1 - with: - source: ./ - destination: ./_site - - uses: actions/upload-pages-artifact@v5 - deploy: - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} - runs-on: ubuntu-latest - needs: build - steps: - - id: deployment - uses: actions/deploy-pages@v5 diff --git a/.github/workflows/release-drafter.yml b/.github/workflows/release-drafter.yml new file mode 100644 index 00000000..5e9b1df6 --- /dev/null +++ b/.github/workflows/release-drafter.yml @@ -0,0 +1,32 @@ +name: Release Drafter + +on: + push: + branches: + - main + pull_request: + types: + - opened + - reopened + - synchronize + +permissions: + contents: read + +jobs: + update_release_draft: + if: github.event_name == 'push' + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: read + steps: + - uses: release-drafter/release-drafter@v7 + + autolabel: + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + permissions: + pull-requests: write + steps: + - uses: release-drafter/release-drafter/autolabeler@v7 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 85398fcc..6ef2406c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -6,27 +6,22 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - with: - token: ${{ secrets.RELEASE_PAT }} - persist-credentials: true - uses: actions/setup-java@v5 with: java-version: '17' distribution: 'temurin' cache: maven - server-id: ossrh + server-id: central server-username: OSSRH_USERNAME server-password: OSSRH_PASSWORD gpg-private-key: ${{ secrets.GPG_PRIVATE_KEY }} gpg-passphrase: GPG_PASSPHRASE - - run: | - git config user.email "matomo-java-tracker@daniel-heid.de" - git config user.name "Matomo Java Tracker" - id: version run: | VERSION=$( mvn -B help:evaluate -Dexpression=project.version -q -DforceStdout ) echo "version=${VERSION%-SNAPSHOT}" >> "$GITHUB_OUTPUT" - - run: mvn -B release:prepare release:perform + - run: mvn -B versions:set -DnewVersion=${{ steps.version.outputs.version }} -DgenerateBackupPoms=false + - run: mvn -B deploy -Prelease env: OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }} OSSRH_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} @@ -35,5 +30,3 @@ jobs: with: version: ${{ steps.version.outputs.version }} publish: true - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/pom.xml b/pom.xml index c6d85c65..a17f5a8d 100644 --- a/pom.xml +++ b/pom.xml @@ -57,13 +57,9 @@ - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ + central + https://central.sonatype.com/ - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - @@ -197,14 +193,12 @@ - org.sonatype.plugins - nexus-staging-maven-plugin - 1.7.0 + org.sonatype.central + central-publishing-maven-plugin + 0.10.0 true - ossrh - https://oss.sonatype.org/ - true + true @@ -428,8 +422,8 @@ maven-gpg-plugin - org.sonatype.plugins - nexus-staging-maven-plugin + org.sonatype.central + central-publishing-maven-plugin From b64a576e318fbf47850c0293ae8e843e7c396d8d Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Sun, 19 Apr 2026 16:10:12 +0200 Subject: [PATCH 48/71] Adapt pages artifact --- .github/workflows/build.yml | 3 +-- pom.xml | 38 ++++++++++++++++++++----------------- 2 files changed, 22 insertions(+), 19 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 48632fcf..24c99532 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -44,9 +44,8 @@ jobs: destination: ./page - if: github.ref == 'refs/heads/main' run: | - mkdir -p _site/apidocs _site/coverage cp -r page/. _site/ - cp -r target/reports/apidocs/. _site/apidocs/ + mkdir -p _site/coverage cp -r target/site/jacoco/. _site/coverage/ - uses: actions/upload-pages-artifact@v5 if: github.ref == 'refs/heads/main' diff --git a/pom.xml b/pom.xml index a17f5a8d..9a879859 100644 --- a/pom.xml +++ b/pom.xml @@ -201,6 +201,23 @@ true + + org.apache.maven.plugins + maven-javadoc-plugin + 3.12.0 + + ${delombok.output} + none + + + + attach-javadocs + + jar + + + + @@ -255,23 +272,6 @@ - - org.apache.maven.plugins - maven-javadoc-plugin - 3.11.2 - - ${delombok.output} - none - - - - attach-javadocs - - jar - - - - org.apache.maven.plugins maven-enforcer-plugin @@ -421,6 +421,10 @@ org.apache.maven.plugins maven-gpg-plugin + + org.apache.maven.plugins + maven-javadoc-plugin + org.sonatype.central central-publishing-maven-plugin From dd26ae503710b76bac6c10b20fe3574680185820 Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Sun, 19 Apr 2026 19:20:37 +0200 Subject: [PATCH 49/71] Remove coverage report from website --- .github/workflows/build.yml | 9 +-------- pom.xml | 24 ++++++++++++++++++++---- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 24c99532..17f0f585 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -32,7 +32,7 @@ jobs: fail-on-error: false - uses: madrapps/jacoco-report@v1.7.2 with: - paths: ${{ github.workspace }}/target/site/jacoco/jacoco.xml + paths: ${{ github.workspace }}/**/target/site/jacoco/jacoco.xml token: ${{ secrets.GITHUB_TOKEN }} min-coverage-overall: 80 min-coverage-changed-files: 80 @@ -40,13 +40,6 @@ jobs: if: github.ref == 'refs/heads/main' - uses: actions/jekyll-build-pages@v1 if: github.ref == 'refs/heads/main' - with: - destination: ./page - - if: github.ref == 'refs/heads/main' - run: | - cp -r page/. _site/ - mkdir -p _site/coverage - cp -r target/site/jacoco/. _site/coverage/ - uses: actions/upload-pages-artifact@v5 if: github.ref == 'refs/heads/main' diff --git a/pom.xml b/pom.xml index 9a879859..a5b136ce 100644 --- a/pom.xml +++ b/pom.xml @@ -298,26 +298,42 @@ 0.8.14 - prepare-agent + prepare-agents prepare-agent + prepare-agent-integration + - report + merge - report + merge + post-integration-test + + + + ${project.build.directory} + + *.exec + + + + + check + report check + verify - CLASS + BUNDLE LINE From 42427f744722120723add204982f6ee493d05eee Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Sun, 19 Apr 2026 19:23:54 +0200 Subject: [PATCH 50/71] Split GH pages to separate workflow --- .github/workflows/build.yml | 20 ------------------ .github/workflows/gh-pages.yaml | 36 +++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 20 deletions(-) create mode 100644 .github/workflows/gh-pages.yaml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 17f0f585..ca29d2df 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -36,23 +36,3 @@ jobs: token: ${{ secrets.GITHUB_TOKEN }} min-coverage-overall: 80 min-coverage-changed-files: 80 - - uses: actions/configure-pages@v6 - if: github.ref == 'refs/heads/main' - - uses: actions/jekyll-build-pages@v1 - if: github.ref == 'refs/heads/main' - - uses: actions/upload-pages-artifact@v5 - if: github.ref == 'refs/heads/main' - - publish-docs: - needs: build - if: github.ref == 'refs/heads/main' - runs-on: ubuntu-latest - permissions: - pages: write - id-token: write - environment: - name: github-pages - url: ${{ steps.deploy.outputs.page_url }} - steps: - - id: deploy - uses: actions/deploy-pages@v4 diff --git a/.github/workflows/gh-pages.yaml b/.github/workflows/gh-pages.yaml new file mode 100644 index 00000000..9876fb61 --- /dev/null +++ b/.github/workflows/gh-pages.yaml @@ -0,0 +1,36 @@ +name: Deploy GitHub Pages + +on: + push: + branches: + - main + +permissions: + contents: read + pages: write + id-token: write + +concurrency: + group: pages + cancel-in-progress: false + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: actions/configure-pages@v6 + - uses: actions/jekyll-build-pages@v1 + with: + source: ./ + destination: ./_site + - uses: actions/upload-pages-artifact@v5 + deploy: + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + needs: build + steps: + - id: deployment + uses: actions/deploy-pages@v5 From 1fea1a7156a2c1456105c2d37688bfd3e5619965 Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Sun, 19 Apr 2026 19:36:44 +0200 Subject: [PATCH 51/71] #394 Add more tracking parameters --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 9d13f6c4..a300c58e 100644 --- a/README.md +++ b/README.md @@ -265,7 +265,7 @@ The following properties are supported: | matomo.tracker.log-failed-tracking | Will send errors to the log if the Matomo Tracking API responds with an erroneous HTTP code | | matomo.tracker.connect-timeout | allows you to change the default connection timeout of 10 seconds. 0 is interpreted as infinite, null uses the system default | | matomo.tracker.socket-timeout | allows you to change the default socket timeout of 10 seconds. 0 is interpreted as infinite, null uses the system default | -| matomo.tracker.user-agent | used by the request made to the endpoint is `MatomoJavaClient` per default. You can change it by using this builder method. | +| matomo.tracker.user-agent | The user agent used by the request made to the endpoint. Default: `MatomoJavaClient` | | matomo.tracker.proxy-host | The hostname or IP address of an optional HTTP proxy. `proxyPort` must be configured as well | | matomo.tracker.proxy-port | The port of an HTTP proxy. `proxyHost` must be configured as well. | | matomo.tracker.proxy-username | If the HTTP proxy requires a username for basic authentication, it can be configured with this method. Proxy host, port and password must also be set. | @@ -412,7 +412,7 @@ public class ConsumerExample { ``` -If you have multiple requests to wish to track, it may be more efficient to send them in a single HTTP call. To do this, +If you have multiple requests you wish to track, it may be more efficient to send them in a single HTTP call. To do this, send a bulk request. Place your requests in an _Iterable_ data structure and call ```java @@ -474,7 +474,7 @@ Per default every request has the following default parameters: | apiVersion | 1 | | responseAsImage | false | -Overwrite these properties as desired. We strongly recommend your to determine the visitor id for every user using +Overwrite these properties as desired. We strongly recommend you to determine the visitor id for every user using a unique identifier, e.g. an email address. If you do not provide a visitor id, a random visitor id will be generated. Ecommerce requests contain ecommerce items, that can be fluently build: @@ -667,9 +667,9 @@ following breaking changes: * `setEcommerceLastOrderTimestamp` requires an `Instant` parameter * `headerAcceptLanguage` is of type `AcceptLanguage`. You can build it easily using `AcceptLanguage.fromHeader("de")` -* `visitorCountry` is of type `Country`. You can build it easily using `AcceptLanguage.fromCode("fr")` +* `visitorCountry` is of type `Country`. You can build it easily using `Country.fromCode("fr")` * `deviceResolution` is of type `DeviceResolution`. You can build it easily - using `DeviceResolution.builder.width(...).height(...).build()`. To easy the migration, we added a constructor + using `DeviceResolution.builder.width(...).height(...).build()`. To ease the migration, we added a constructor method `DeviceResolution.fromString()` that accepts inputs of kind _width_x_height_, e.g. `100x200` * `pageViewId` is of type `UniqueId`. You can build it easily using `UniqueId.random()` * `randomValue` is of type `RandomValue`. You can build it easily using `RandomValue.random()`. However, if you @@ -713,7 +713,7 @@ mvn install ``` The built jars and javadoc can be found in `target`. By using -the Maven goal `install, a snapshot +the Maven goal `install`, a snapshot version can be used in your local Maven repository for testing purposes, e.g. ```xml @@ -757,7 +757,7 @@ docker-compose exec matomo sh -c 'echo -e "\n\n[Tracker]\ndebug = 1\n" >> /var/w To test the servlet integration, run `MatomoServletTester` in your favorite IDE. It starts an embedded Jetty server that serves a simple servlet. The servlet sends a request to the local Matomo instance if you call the URL http://localhost:8090/track.html. Maybe you need to disable support for the Do Not Track preference in Matomo to get the -request tracked: Go to _Administration > Privacy > Do Not Track_ and disable the checkbox _Respect Do Not Track. +request tracked: Go to _Administration > Privacy > Do Not Track_ and disable the checkbox _Respect Do Not Track_. We also recommend to install the Custom Variables plugin from Marketplace to the test custom variables feature and setup some dimensions. @@ -774,7 +774,7 @@ free to: * Fork this project * Create a feature branch from the _master_ branch * Write awesome code that does awesome things -* Write awesome test to test your awesome code +* Write awesome tests to test your awesome code * Verify that everything is working as it should by running _mvn test_. If everything passes, you may want to make sure that your tests are covering everything you think they are! Run `mvn verify` to find out! From d887ab61c3455fb7fbbf6fa663c2f918bc5c779f Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Sun, 19 Apr 2026 19:54:37 +0200 Subject: [PATCH 52/71] Use Nexus staging plugin --- pom.xml | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/pom.xml b/pom.xml index a5b136ce..ca3e5ac5 100644 --- a/pom.xml +++ b/pom.xml @@ -57,8 +57,8 @@ - central - https://central.sonatype.com/ + ossrh + https://oss.sonatype.org/service/local/staging/deploy/maven2/ @@ -193,12 +193,14 @@ - org.sonatype.central - central-publishing-maven-plugin - 0.10.0 + org.sonatype.plugins + nexus-staging-maven-plugin + 1.7.0 true - true + ossrh + https://oss.sonatype.org/ + true From cad950058790bfe8f0f6fd2434806a07a2e351d8 Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Sun, 19 Apr 2026 19:56:38 +0200 Subject: [PATCH 53/71] Revert "Use Nexus staging plugin" This reverts commit d887ab61c3455fb7fbbf6fa663c2f918bc5c779f. --- pom.xml | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/pom.xml b/pom.xml index ca3e5ac5..a5b136ce 100644 --- a/pom.xml +++ b/pom.xml @@ -57,8 +57,8 @@ - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ + central + https://central.sonatype.com/ @@ -193,14 +193,12 @@ - org.sonatype.plugins - nexus-staging-maven-plugin - 1.7.0 + org.sonatype.central + central-publishing-maven-plugin + 0.10.0 true - ossrh - https://oss.sonatype.org/ - true + true From a8d398910f07bea2a69469f669952f87d2ebd600 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 7 May 2026 12:23:29 +0200 Subject: [PATCH 54/71] build(deps-dev): bump org.owasp:dependency-check-maven from 12.2.1 to 12.2.2 (#402) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index a5b136ce..cb43f8b0 100644 --- a/pom.xml +++ b/pom.xml @@ -378,7 +378,7 @@ org.owasp dependency-check-maven - 12.2.1 + 12.2.2 true From b14d1675953c426f1b98309b8af7e9675121d584 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 7 May 2026 12:23:37 +0200 Subject: [PATCH 55/71] build(deps): bump org.springframework.boot:spring-boot-dependencies from 4.0.5 to 4.0.6 (#401) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- spring/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring/pom.xml b/spring/pom.xml index 7ef22e49..93399ae3 100644 --- a/spring/pom.xml +++ b/spring/pom.xml @@ -18,7 +18,7 @@ 17 17 - 4.0.5 + 4.0.6 From f9136bc5b09f22452482c01ed3c12da1773c2a92 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 7 May 2026 12:23:47 +0200 Subject: [PATCH 56/71] build(deps): bump org.projectlombok:lombok from 1.18.36 to 1.18.46 (#400) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index cb43f8b0..1fcb689b 100644 --- a/pom.xml +++ b/pom.xml @@ -69,7 +69,7 @@ 1.8 1.8 ${project.build.outputDirectory}/delombok - 1.18.36 + 1.18.46 2.0.17 From 49f41cca3726572dc4f21c6ec8daf025c17df5b9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 7 May 2026 12:23:56 +0200 Subject: [PATCH 57/71] build(deps): bump dependabot/fetch-metadata from 3.0.0 to 3.1.0 (#399) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/dependabot-automerge.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dependabot-automerge.yml b/.github/workflows/dependabot-automerge.yml index 8580f46f..57750289 100644 --- a/.github/workflows/dependabot-automerge.yml +++ b/.github/workflows/dependabot-automerge.yml @@ -13,7 +13,7 @@ jobs: steps: - name: Fetch Dependabot metadata id: metadata - uses: dependabot/fetch-metadata@v3.0.0 + uses: dependabot/fetch-metadata@v3.1.0 with: github-token: "${{ secrets.GITHUB_TOKEN }}" - name: Approve pull request From a138951451c16fb2f611640f0ed96183ee0787ed Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 7 May 2026 12:24:06 +0200 Subject: [PATCH 58/71] build(deps-dev): bump org.apache.maven.plugins:maven-enforcer-plugin from 3.5.0 to 3.6.2 (#397) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 1fcb689b..f0d25007 100644 --- a/pom.xml +++ b/pom.xml @@ -275,7 +275,7 @@ org.apache.maven.plugins maven-enforcer-plugin - 3.5.0 + 3.6.2 enforce-maven From 7d8210f1fd9c593002a8a762e5842fe0d59915de Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 7 May 2026 12:24:14 +0200 Subject: [PATCH 59/71] build(deps-dev): bump com.diffplug.spotless:spotless-maven-plugin from 2.44.3 to 3.4.0 (#396) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index f0d25007..2cb43608 100644 --- a/pom.xml +++ b/pom.xml @@ -386,7 +386,7 @@ com.diffplug.spotless spotless-maven-plugin - 2.44.3 + 3.4.0 From 86d0dac26ec454c9a539356a68df1b6b434c835b Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Thu, 7 May 2026 12:24:45 +0200 Subject: [PATCH 60/71] Remove dheid from dependabot assignees --- .github/dependabot.yml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 9334a827..0e775aff 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -4,17 +4,11 @@ updates: directory: / schedule: interval: weekly - assignees: - - dheid - package-ecosystem: github-actions directory: / schedule: interval: weekly - assignees: - - dheid - package-ecosystem: docker directory: / schedule: interval: weekly - assignees: - - dheid From a308abac57b0a92e4354babbb4807bcb249fdeb6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 7 May 2026 10:29:25 +0000 Subject: [PATCH 61/71] build(deps-dev): bump org.eclipse.jetty.ee10:jetty-ee10-servlet from 12.1.8 to 12.1.9 (#403) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- servlet-jakarta/pom.xml | 2 +- test/pom.xml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 2cb43608..e85b4033 100644 --- a/pom.xml +++ b/pom.xml @@ -113,7 +113,7 @@ org.eclipse.jetty.ee10 jetty-ee10-servlet - 12.1.8 + 12.1.9 diff --git a/servlet-jakarta/pom.xml b/servlet-jakarta/pom.xml index 35257c65..e4c38c81 100644 --- a/servlet-jakarta/pom.xml +++ b/servlet-jakarta/pom.xml @@ -54,7 +54,7 @@ org.eclipse.jetty.ee10 jetty-ee10-servlet - 12.1.8 + 12.1.9 test diff --git a/test/pom.xml b/test/pom.xml index d02fa589..dfe914f2 100644 --- a/test/pom.xml +++ b/test/pom.xml @@ -47,7 +47,7 @@ org.eclipse.jetty.ee10 jetty-ee10-servlet - 12.1.8 + 12.1.9 From 42c1db43f6e7331d232e74ad632122db9f2b532f Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Thu, 7 May 2026 14:51:47 +0200 Subject: [PATCH 62/71] Upgrade to major 4 and remove deprecations --- README.md | 70 +- core/pom.xml | 4 +- .../org/matomo/java/tracking/AuthToken.java | 4 - .../matomo/java/tracking/CustomVariable.java | 30 - .../matomo/java/tracking/EcommerceItem.java | 31 - .../org/matomo/java/tracking/MatomoDate.java | 66 -- .../matomo/java/tracking/MatomoLocale.java | 39 - .../matomo/java/tracking/MatomoRequest.java | 404 --------- .../java/tracking/MatomoRequestBuilder.java | 47 - .../matomo/java/tracking/MatomoTracker.java | 177 +--- .../java/org/matomo/java/tracking/Sender.java | 7 +- .../java/tracking/parameters/Country.java | 40 - .../piwik/java/tracking/CustomVariable.java | 32 - .../piwik/java/tracking/EcommerceItem.java | 33 - .../org/piwik/java/tracking/PiwikDate.java | 56 -- .../org/piwik/java/tracking/PiwikLocale.java | 33 - .../org/piwik/java/tracking/PiwikRequest.java | 36 - .../org/piwik/java/tracking/PiwikTracker.java | 75 -- .../org/piwik/java/tracking/package-info.java | 2 - .../matomo/java/tracking/AuthTokenTest.java | 8 +- .../matomo/java/tracking/BulkRequestTest.java | 21 +- .../java/tracking/CustomVariableTest.java | 35 - .../java/tracking/MatomoLocaleTest.java | 23 - .../tracking/MatomoRequestBuilderTest.java | 84 -- .../java/tracking/MatomoRequestTest.java | 133 --- .../matomo/java/tracking/MatomoTrackerIT.java | 85 +- .../matomo/java/tracking/PiwikDateTest.java | 38 - .../matomo/java/tracking/PiwikLocaleTest.java | 25 - .../java/tracking/PiwikRequestTest.java | 809 ------------------ .../java/tracking/QueryCreatorTest.java | 6 +- .../java/tracking/RequestValidatorTest.java | 40 +- .../org/matomo/java/tracking/TestSender.java | 20 +- .../java/tracking/parameters/CountryTest.java | 35 - .../parameters/CustomVariableTest.java | 27 + .../parameters/DeviceResolutionTest.java | 8 + .../{ => parameters}/EcommerceItemTest.java | 2 +- .../tracking/parameters/RandomValueTest.java | 25 + .../tracking/parameters/VisitorIdTest.java | 16 + .../java/tracking/CustomVariableTest.java | 16 - .../java/tracking/EcommerceItemTest.java | 19 - .../piwik/java/tracking/PiwikTrackerIT.java | 42 - java11/pom.xml | 8 +- .../matomo/java/tracking/Java11Sender.java | 19 +- .../matomo/java/tracking/Java11SenderIT.java | 30 +- .../matomo/java/tracking/MatomoTrackerIT.java | 20 +- .../matomo/java/tracking/PiwikTrackerIT.java | 252 ------ java8/pom.xml | 8 +- .../org/matomo/java/tracking/Java8Sender.java | 14 +- .../matomo/java/tracking/Java8SenderIT.java | 8 +- .../matomo/java/tracking/MatomoTrackerIT.java | 25 +- .../matomo/java/tracking/PiwikTrackerIT.java | 254 ------ pom.xml | 4 +- servlet-jakarta/pom.xml | 8 +- .../org/matomo/java/tracking/TestSender.java | 6 +- servlet-javax/pom.xml | 8 +- .../org/matomo/java/tracking/TestSender.java | 6 +- spring/pom.xml | 8 +- test/pom.xml | 8 +- 58 files changed, 332 insertions(+), 3057 deletions(-) delete mode 100644 core/src/main/java/org/matomo/java/tracking/CustomVariable.java delete mode 100644 core/src/main/java/org/matomo/java/tracking/EcommerceItem.java delete mode 100644 core/src/main/java/org/matomo/java/tracking/MatomoDate.java delete mode 100644 core/src/main/java/org/matomo/java/tracking/MatomoLocale.java delete mode 100644 core/src/main/java/org/matomo/java/tracking/MatomoRequestBuilder.java delete mode 100644 core/src/main/java/org/piwik/java/tracking/CustomVariable.java delete mode 100644 core/src/main/java/org/piwik/java/tracking/EcommerceItem.java delete mode 100644 core/src/main/java/org/piwik/java/tracking/PiwikDate.java delete mode 100644 core/src/main/java/org/piwik/java/tracking/PiwikLocale.java delete mode 100644 core/src/main/java/org/piwik/java/tracking/PiwikRequest.java delete mode 100644 core/src/main/java/org/piwik/java/tracking/PiwikTracker.java delete mode 100644 core/src/main/java/org/piwik/java/tracking/package-info.java delete mode 100644 core/src/test/java/org/matomo/java/tracking/CustomVariableTest.java delete mode 100644 core/src/test/java/org/matomo/java/tracking/MatomoLocaleTest.java delete mode 100644 core/src/test/java/org/matomo/java/tracking/MatomoRequestBuilderTest.java delete mode 100644 core/src/test/java/org/matomo/java/tracking/MatomoRequestTest.java delete mode 100644 core/src/test/java/org/matomo/java/tracking/PiwikDateTest.java delete mode 100644 core/src/test/java/org/matomo/java/tracking/PiwikLocaleTest.java delete mode 100644 core/src/test/java/org/matomo/java/tracking/PiwikRequestTest.java rename core/src/test/java/org/matomo/java/tracking/{ => parameters}/EcommerceItemTest.java (97%) create mode 100644 core/src/test/java/org/matomo/java/tracking/parameters/RandomValueTest.java delete mode 100644 core/src/test/java/org/piwik/java/tracking/CustomVariableTest.java delete mode 100644 core/src/test/java/org/piwik/java/tracking/EcommerceItemTest.java delete mode 100644 core/src/test/java/org/piwik/java/tracking/PiwikTrackerIT.java delete mode 100644 java11/src/test/java/org/matomo/java/tracking/PiwikTrackerIT.java delete mode 100644 java8/src/test/java/org/matomo/java/tracking/PiwikTrackerIT.java diff --git a/README.md b/README.md index a300c58e..36e3fa44 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Official Matomo Java Tracker -![Maven Central Version](https://img.shields.io/maven-central/v/org.piwik.java.tracking/matomo-java-tracker-core) +![Maven Central Version](https://img.shields.io/maven-central/v/org.matomo.java/matomo-java-tracker-core) [![Build Status](https://github.com/matomo-org/matomo-java-tracker/actions/workflows/build.yml/badge.svg)](https://github.com/matomo-org/matomo-java-tracker/actions/workflows/build.yml) [![Average time to resolve an issue](https://isitmaintained.com/badge/resolution/matomo-org/matomo-java-tracker.svg)](https://isitmaintained.com/project/matomo-org/matomo-java-tracker "Average time to resolve an issue") [![Percentage of issues still open](https://isitmaintained.com/badge/open/matomo-org/matomo-java-tracker.svg)](https://isitmaintained.com/project/matomo-org/matomo-java-tracker "Percentage of issues still open") @@ -69,7 +69,7 @@ Projects that use Matomo Java Tracker: ## What Is New? -### Version 3.5.x +### Version 4.0.x Added more tracking parameters for user agent data, ecommerce product, bot recording mode, HTTP status, bandwidth, source label and media attributes. @@ -103,6 +103,40 @@ Jetty EE10 12.0.16 → 12.1.8, Jetty (javax) 10.0.24 → 10.0.26. The local testing Docker setup now uses MariaDB 12 and Matomo 5. +The Maven groupId has changed from `org.piwik.java.tracking` to `org.matomo.java`. Update your +dependency declarations accordingly. + +All previously deprecated API has been removed as part of this major release. The following is a +summary of the breaking changes and the recommended replacements: + +- The `org.piwik.java.tracking` compatibility package has been removed entirely (`PiwikRequest`, + `PiwikTracker`, `PiwikDate`, `PiwikLocale`, `CustomVariable`, `EcommerceItem`). Use the + corresponding classes in `org.matomo.java.tracking` instead. +- The deprecated `MatomoDate` and `MatomoLocale` classes have been removed. Use `java.time.Instant` + and `org.matomo.java.tracking.parameters.Country` respectively. +- The top-level `MatomoRequestBuilder` class has been removed. Use `MatomoRequest.request()` or + `MatomoRequest.MatomoRequestBuilder` instead. +- The deprecated `MatomoRequest(int siteId, String actionUrl)` constructor has been removed. Use + `MatomoRequest.request()` builder instead. +- Deprecated mutator methods on `MatomoRequest` have been removed: `setCustomTrackingParameter`, + `addCustomTrackingParameter`, `clearCustomTrackingParameter`, `enableEcommerce`, + `getEcommerceItem`, `addEcommerceItem`, `clearEcommerceItems`, `getPageCustomVariable`, + `setPageCustomVariable`, `getUserCustomVariable`, `getVisitCustomVariable`, + `setUserCustomVariable`, `setVisitCustomVariable`, `getRequestDatetime`, `setRequestDatetime`, + `setParameter`, `builder()`, and `setDeviceResolution(String)`. Use the builder API + (`MatomoRequest.request()...build()`) instead. +- Deprecated constructors on `MatomoTracker` taking `hostUrl`, `proxyHost`, `proxyPort`, and + `timeout` as individual arguments have been removed. Use + `MatomoTracker(TrackerConfiguration)` instead. +- The `sendRequestAsync(MatomoRequest, Function)` overload has been removed. Chain + `CompletableFuture.thenApply()` on `sendRequestAsync(MatomoRequest)` instead. +- The `sendBulkRequest(Iterable, String authToken)` and + `sendBulkRequestAsync(Collection, String, Consumer)` / `sendBulkRequestAsync(Collection, String)` + overloads have been removed. Set the auth token in `TrackerConfiguration` or on the requests + directly, and chain `CompletableFuture.thenAccept()` for callbacks. +- Deprecated `Country(Locale)` constructor and `Country.getLocale()` / `Country.setLocale(Locale)` + methods have been removed. Construct `Country` from a country code string instead. + ### Version 3.4.x We fixed a synchronization issue in the Java 8 sender (https://github.com/matomo-org/matomo-java-tracker/issues/168). @@ -129,7 +163,7 @@ See also the [Developer Guide here](https://developer.matomo.org/api-reference/t ## Javadoc The Javadoc for all versions can be found -[at javadoc.io](https://javadoc.io/doc/org.piwik.java.tracking/matomo-java-tracker-core/latest/index.html). Thanks to +[at javadoc.io](https://javadoc.io/doc/org.matomo.java/matomo-java-tracker-core/latest/index.html). Thanks to [javadoc.io](https://javadoc.io) for hosting it. ## Need help? @@ -181,9 +215,9 @@ Add a dependency on Matomo Java Tracker using Maven. For Java 8: ```xml - org.piwik.java.tracking + org.matomo.java matomo-java-tracker - 3.5.0 + 4.0.0 ``` @@ -192,9 +226,9 @@ For Java 11 or newer: ```xml - org.piwik.java.tracking + org.matomo.java matomo-java-tracker-java11 - 3.5.0 + 4.0.0 ``` @@ -202,7 +236,7 @@ or Gradle (Java 8): ```groovy dependencies { - implementation("org.piwik.java.tracking:matomo-java-tracker:3.5.0") + implementation("org.matomo.java:matomo-java-tracker:4.0.0") } ``` @@ -210,20 +244,20 @@ or Gradle (Java 11 or newer): ```groovy dependencies { - implementation("org.piwik.java.tracking:matomo-java-tracker-java11:3.5.0") + implementation("org.matomo.java:matomo-java-tracker-java11:4.0.0") } ``` or Gradle with Kotlin DSL (Java 8) ```kotlin -implementation("org.piwik.java.tracking:matomo-java-tracker:3.5.0") +implementation("org.matomo.java:matomo-java-tracker:4.0.0") ``` or Gradle with Kotlin DSL (Java 11 or newer) ```kotlin -implementation("org.piwik.java.tracking:matomo-java-tracker-java11:3.5.0") +implementation("org.matomo.java:matomo-java-tracker-java11:4.0.0") ``` ### Spring Boot Module @@ -234,9 +268,9 @@ and allows you to configure the tracker via application properties. Add the foll ```xml - org.piwik.java.tracking + org.matomo.java matomo-java-tracker-spring-boot-starter - 3.5.0 + 4.0.0 ``` @@ -244,14 +278,14 @@ or Gradle: ```groovy dependencies { - implementation("org.piwik.java.tracking:matomo-java-tracker-spring-boot-starter:3.5.0") + implementation("org.matomo.java:matomo-java-tracker-spring-boot-starter:4.0.0") } ``` or Gradle with Kotlin DSL ```kotlin -implementation("org.piwik.java.tracking:matomo-java-tracker-spring-boot-starter:3.5.0") +implementation("org.matomo.java:matomo-java-tracker-spring-boot-starter:4.0.0") ``` The following properties are supported: @@ -265,7 +299,7 @@ The following properties are supported: | matomo.tracker.log-failed-tracking | Will send errors to the log if the Matomo Tracking API responds with an erroneous HTTP code | | matomo.tracker.connect-timeout | allows you to change the default connection timeout of 10 seconds. 0 is interpreted as infinite, null uses the system default | | matomo.tracker.socket-timeout | allows you to change the default socket timeout of 10 seconds. 0 is interpreted as infinite, null uses the system default | -| matomo.tracker.user-agent | The user agent used by the request made to the endpoint. Default: `MatomoJavaClient` | +| matomo.tracker.user-agent | The user agent used by the request made to the endpoint. Default: `MatomoJavaClient` | | matomo.tracker.proxy-host | The hostname or IP address of an optional HTTP proxy. `proxyPort` must be configured as well | | matomo.tracker.proxy-port | The port of an HTTP proxy. `proxyHost` must be configured as well. | | matomo.tracker.proxy-username | If the HTTP proxy requires a username for basic authentication, it can be configured with this method. Proxy host, port and password must also be set. | @@ -718,9 +752,9 @@ version can be used in your local Maven repository for testing purposes, e.g. ```xml - org.piwik.java.tracking + org.matomo.java matomo-java-tracker - 3.5.0-SNAPSHOT + 4.0.0-SNAPSHOT ``` diff --git a/core/pom.xml b/core/pom.xml index e5949bd8..9507cb60 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -3,9 +3,9 @@ 4.0.0 - org.piwik.java.tracking + org.matomo.java matomo-java-tracker-parent - 3.5.0-SNAPSHOT + 4.0.0-SNAPSHOT ../pom.xml diff --git a/core/src/main/java/org/matomo/java/tracking/AuthToken.java b/core/src/main/java/org/matomo/java/tracking/AuthToken.java index af8c62bb..5a90f026 100644 --- a/core/src/main/java/org/matomo/java/tracking/AuthToken.java +++ b/core/src/main/java/org/matomo/java/tracking/AuthToken.java @@ -17,12 +17,8 @@ private AuthToken() { @Nullable static String determineAuthToken( - @Nullable String overrideAuthToken, @Nullable Iterable requests, @Nullable TrackerConfiguration trackerConfiguration) { - if (isNotBlank(overrideAuthToken)) { - return overrideAuthToken; - } if (requests != null) { for (MatomoRequest request : requests) { if (request != null && isNotBlank(request.getAuthToken())) { diff --git a/core/src/main/java/org/matomo/java/tracking/CustomVariable.java b/core/src/main/java/org/matomo/java/tracking/CustomVariable.java deleted file mode 100644 index ad148b46..00000000 --- a/core/src/main/java/org/matomo/java/tracking/CustomVariable.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Matomo Java Tracker - * - * @link https://github.com/matomo/matomo-java-tracker - * @license https://github.com/matomo/matomo-java-tracker/blob/master/LICENSE BSD-3 Clause - */ - -package org.matomo.java.tracking; - -import lombok.NonNull; - -/** - * A user defined custom variable. - * - * @author brettcsorba - * @deprecated Use {@link org.matomo.java.tracking.parameters.EcommerceItem} instead. - */ -@Deprecated -public class CustomVariable extends org.matomo.java.tracking.parameters.CustomVariable { - - /** - * Instantiates a new custom variable. - * - * @param key the key of the custom variable (required) - * @param value the value of the custom variable (required) - */ - public CustomVariable(@NonNull String key, @NonNull String value) { - super(key, value); - } -} diff --git a/core/src/main/java/org/matomo/java/tracking/EcommerceItem.java b/core/src/main/java/org/matomo/java/tracking/EcommerceItem.java deleted file mode 100644 index 96f32379..00000000 --- a/core/src/main/java/org/matomo/java/tracking/EcommerceItem.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Matomo Java Tracker - * - * @link https://github.com/matomo/matomo-java-tracker - * @license https://github.com/matomo/matomo-java-tracker/blob/master/LICENSE BSD-3 Clause - */ - -package org.matomo.java.tracking; - -/** - * A user defined custom variable. - * - * @author brettcsorba - * @deprecated Use {@link org.matomo.java.tracking.parameters.EcommerceItem} instead. - */ -@Deprecated -public class EcommerceItem extends org.matomo.java.tracking.parameters.EcommerceItem { - - /** - * Instantiates a new ecommerce item. - * - * @param sku the sku (Stock Keeping Unit) of the item - * @param name the name of the item - * @param category the category of the item - * @param price the price of the item - * @param quantity the quantity of the item - */ - public EcommerceItem(String sku, String name, String category, Double price, Integer quantity) { - super(sku, name, category, price, quantity); - } -} diff --git a/core/src/main/java/org/matomo/java/tracking/MatomoDate.java b/core/src/main/java/org/matomo/java/tracking/MatomoDate.java deleted file mode 100644 index 3927dc2b..00000000 --- a/core/src/main/java/org/matomo/java/tracking/MatomoDate.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Matomo Java Tracker - * - * @link https://github.com/matomo/matomo-java-tracker - * @license https://github.com/matomo/matomo-java-tracker/blob/master/LICENSE BSD-3 Clause - */ - -package org.matomo.java.tracking; - -import java.time.Instant; -import java.time.ZoneId; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import lombok.Getter; - -/** - * A datetime object that will return the datetime in the format {@code yyyy-MM-dd hh:mm:ss}. - * - * @author brettcsorba - * @deprecated Please use {@link Instant} - */ -@Deprecated -@Getter -public class MatomoDate { - - private ZonedDateTime zonedDateTime; - - /** - * Allocates a Date object and initializes it so that it represents the time at which it was - * allocated, measured to the nearest millisecond. - */ - @Deprecated - public MatomoDate() { - zonedDateTime = ZonedDateTime.now(ZoneOffset.UTC); - } - - /** - * Allocates a Date object and initializes it to represent the specified number of milliseconds - * since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT. - * - * @param epochMilli the milliseconds since January 1, 1970, 00:00:00 GMT. - */ - @Deprecated - public MatomoDate(long epochMilli) { - zonedDateTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(epochMilli), ZoneOffset.UTC); - } - - /** - * Sets the time zone of the String that will be returned by {@link #toString()}. Defaults to UTC. - * - * @param zone the TimeZone to set - */ - public void setTimeZone(ZoneId zone) { - zonedDateTime = zonedDateTime.withZoneSameInstant(zone); - } - - /** - * Converts this datetime to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z. - * - * @return the number of milliseconds since the epoch of 1970-01-01T00:00:00Z - * @throws ArithmeticException if numeric overflow occurs - */ - public long getTime() { - return zonedDateTime.toInstant().toEpochMilli(); - } -} diff --git a/core/src/main/java/org/matomo/java/tracking/MatomoLocale.java b/core/src/main/java/org/matomo/java/tracking/MatomoLocale.java deleted file mode 100644 index d7340351..00000000 --- a/core/src/main/java/org/matomo/java/tracking/MatomoLocale.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Matomo Java Tracker - * - * @link https://github.com/matomo/matomo-java-tracker - * @license https://github.com/matomo/matomo-java-tracker/blob/master/LICENSE BSD-3 Clause - */ - -package org.matomo.java.tracking; - -import static java.util.Objects.requireNonNull; - -import edu.umd.cs.findbugs.annotations.NonNull; -import java.util.Locale; -import lombok.Getter; -import lombok.Setter; -import org.matomo.java.tracking.parameters.Country; - -/** - * Object representing a locale required by some Matomo query parameters. - * - * @author brettcsorba - * @deprecated Use {@link Country} instead - */ -@Setter -@Getter -@Deprecated -public class MatomoLocale extends Country { - - /** - * Constructs a new MatomoLocale. - * - * @param locale The locale to get the country code from - * @deprecated Please use {@link Country} - */ - @Deprecated - public MatomoLocale(@NonNull Locale locale) { - super(requireNonNull(locale, "Locale must not be null")); - } -} diff --git a/core/src/main/java/org/matomo/java/tracking/MatomoRequest.java b/core/src/main/java/org/matomo/java/tracking/MatomoRequest.java index 7a71bc86..da1097bd 100644 --- a/core/src/main/java/org/matomo/java/tracking/MatomoRequest.java +++ b/core/src/main/java/org/matomo/java/tracking/MatomoRequest.java @@ -7,10 +7,8 @@ package org.matomo.java.tracking; -import edu.umd.cs.findbugs.annotations.Nullable; import java.nio.charset.Charset; import java.time.Instant; -import java.util.LinkedHashMap; import java.util.Map; import java.util.UUID; import lombok.AllArgsConstructor; @@ -18,16 +16,12 @@ import lombok.Builder.Default; import lombok.Getter; import lombok.NoArgsConstructor; -import lombok.NonNull; import lombok.Setter; import lombok.ToString; -import lombok.experimental.Tolerate; import org.matomo.java.tracking.parameters.AcceptLanguage; import org.matomo.java.tracking.parameters.Country; -import org.matomo.java.tracking.parameters.CustomVariable; import org.matomo.java.tracking.parameters.CustomVariables; import org.matomo.java.tracking.parameters.DeviceResolution; -import org.matomo.java.tracking.parameters.EcommerceItem; import org.matomo.java.tracking.parameters.EcommerceItems; import org.matomo.java.tracking.parameters.RandomValue; import org.matomo.java.tracking.parameters.UniqueId; @@ -779,402 +773,4 @@ public class MatomoRequest { * coming from Matomo responses to the request. */ private Map cookies; - - /** - * Create a new request from the id of the site being tracked and the full url for the current - * action. This constructor also sets: - * - *

{@code Required = true Visior Id = random 16 character hex string Random Value = random 20 - * character hex string API version = 1 Response as Image = false } - * - *

Overwrite these values yourself as desired. - * - * @param siteId the id of the website we're tracking a visit/action for - * @param actionUrl the full URL for the current action - * @deprecated Please use {@link MatomoRequest#request()} - */ - @Deprecated - public MatomoRequest(int siteId, String actionUrl) { - this.siteId = siteId; - this.actionUrl = actionUrl; - required = true; - visitorId = VisitorId.random(); - randomValue = RandomValue.random(); - apiVersion = "1"; - responseAsImage = false; - } - - /** - * Gets the list of objects currently stored at the specified custom tracking parameter. An empty - * list will be returned if there are no objects set at that key. - * - * @param key the key of the parameter whose list of objects to get. Cannot be null - * @return the parameter at the specified key, null if nothing at this key - */ - @Nullable - public Object getCustomTrackingParameter(@NonNull String key) { - if (additionalParameters == null || additionalParameters.isEmpty()) { - return null; - } - return additionalParameters.get(key); - } - - /** - * Set a custom tracking parameter whose toString() value will be sent to the Matomo server. These - * parameters are stored separately from named Matomo parameters, meaning it is not possible to - * overwrite or clear named Matomo parameters with this method. A custom parameter that has the - * same name as a named Matomo parameter will be sent in addition to that named parameter. - * - * @param key the parameter's key. Cannot be null - * @param value the parameter's value. Removes the parameter if null - * @deprecated Use {@link MatomoRequest.MatomoRequestBuilder#additionalParameters(Map)} instead. - */ - @Deprecated - public void setCustomTrackingParameter(@NonNull String key, @Nullable Object value) { - - if (value == null) { - if (additionalParameters != null) { - additionalParameters.remove(key); - } - } else { - if (additionalParameters == null) { - additionalParameters = new LinkedHashMap<>(); - } - additionalParameters.put(key, value); - } - } - - /** - * Add a custom tracking parameter to the specified key. If there is already a parameter at this - * key, the new value replaces the old value. - * - * @param key the parameter's key. Cannot be null - * @param value the parameter's value. May be null - * @deprecated Use {@link MatomoRequest.MatomoRequestBuilder#additionalParameters(Map)} instead. - */ - @Deprecated - public void addCustomTrackingParameter(@NonNull String key, @Nullable Object value) { - if (additionalParameters == null) { - additionalParameters = new LinkedHashMap<>(); - } - additionalParameters.put(key, value); - } - - /** - * Removes all custom tracking parameters. - * - * @deprecated Please use {@link MatomoRequest.MatomoRequestBuilder#additionalParameters(Map)} - * instead so that you can manage the map yourself. - */ - @Deprecated - public void clearCustomTrackingParameter() { - additionalParameters.clear(); - } - - /** - * Sets idgoal=0 in the request to track an ecommerce interaction: cart update or an - * ecommerce order. - * - * @deprecated Please use {@link MatomoRequest#setGoalId(Integer)} instead - */ - @Deprecated - public void enableEcommerce() { - setGoalId(0); - } - - /** - * Get the {@link EcommerceItem} at the specified index. - * - * @param index the index of the {@link EcommerceItem} to return - * @return the {@link EcommerceItem} at the specified index - * @deprecated Use @link {@link MatomoRequest.MatomoRequestBuilder#ecommerceItems(EcommerceItems)} - * instead - */ - @Nullable - @Deprecated - public EcommerceItem getEcommerceItem(int index) { - if (ecommerceItems == null || ecommerceItems.isEmpty()) { - return null; - } - return ecommerceItems.get(index); - } - - /** - * Add an {@link EcommerceItem} to this order. Ecommerce must be enabled, and EcommerceId and - * EcommerceRevenue must first be set. - * - * @param item the {@link EcommerceItem} to add. Cannot be null - * @deprecated Use @link {@link MatomoRequest.MatomoRequestBuilder#ecommerceItems(EcommerceItems)} - * instead - */ - @Deprecated - public void addEcommerceItem(@NonNull EcommerceItem item) { - if (ecommerceItems == null) { - ecommerceItems = new EcommerceItems(); - } - ecommerceItems.add(item); - } - - /** - * Clears all {@link EcommerceItem} from this order. - * - * @deprecated Use @link {@link MatomoRequest.MatomoRequestBuilder#ecommerceItems(EcommerceItems)} - * instead - */ - @Deprecated - public void clearEcommerceItems() { - ecommerceItems.clear(); - } - - /** - * Get the page custom variable at the specified key. - * - * @param key the key of the variable to get - * @return the variable at the specified key, null if key is not present - * @deprecated Use the {@link #getPageCustomVariables()} method instead. - */ - @Nullable - @Deprecated - public String getPageCustomVariable(String key) { - if (pageCustomVariables == null) { - return null; - } - return pageCustomVariables.get(key); - } - - /** - * Get the page custom variable at the specified index. - * - * @param index the index of the variable to get. Must be greater than 0 - * @return the variable at the specified key, null if nothing at this index - * @deprecated Use {@link MatomoRequest#getPageCustomVariables()} instead - */ - @Deprecated - @Nullable - public CustomVariable getPageCustomVariable(int index) { - return getCustomVariable(pageCustomVariables, index); - } - - @Nullable - @Deprecated - private static CustomVariable getCustomVariable(CustomVariables customVariables, int index) { - if (customVariables == null) { - return null; - } - return customVariables.get(index); - } - - /** - * Set a page custom variable with the specified key and value at the first available index. All - * page custom variables with this key will be overwritten or deleted - * - * @param key the key of the variable to set - * @param value the value of the variable to set at the specified key. A null value will remove - * this custom variable - * @deprecated Use {@link MatomoRequest#getPageCustomVariables()} instead - */ - @Deprecated - public void setPageCustomVariable(@NonNull String key, @Nullable String value) { - if (value == null) { - if (pageCustomVariables == null) { - return; - } - pageCustomVariables.remove(key); - } else { - CustomVariable variable = new CustomVariable(key, value); - if (pageCustomVariables == null) { - pageCustomVariables = new CustomVariables(); - } - pageCustomVariables.add(variable); - } - } - - /** - * Set a page custom variable at the specified index. - * - * @param customVariable the CustomVariable to set. A null value will remove the CustomVariable at - * the specified index - * @param index the index of he CustomVariable to set - * @deprecated Use {@link #getPageCustomVariables()} instead - */ - @Deprecated - public void setPageCustomVariable(@Nullable CustomVariable customVariable, int index) { - if (pageCustomVariables == null) { - if (customVariable == null) { - return; - } - pageCustomVariables = new CustomVariables(); - } - setCustomVariable(pageCustomVariables, customVariable, index); - } - - @Deprecated - private static void setCustomVariable( - CustomVariables customVariables, @Nullable CustomVariable customVariable, int index) { - if (customVariable == null) { - customVariables.remove(index); - } else { - customVariables.add(customVariable, index); - } - } - - /** - * Get the datetime of the request. - * - * @return the datetime of the request - * @deprecated Use {@link #getRequestTimestamp()} instead - */ - @Deprecated - @Nullable - public MatomoDate getRequestDatetime() { - return requestTimestamp == null ? null : new MatomoDate(requestTimestamp.toEpochMilli()); - } - - /** - * Set the datetime of the request (normally the current time is used). This can be used to record - * visits and page views in the past. The datetime must be sent in UTC timezone. Note: if you - * record data in the past, you will need to force - * Matomo to re-process reports for the past dates. If you set the Request - * Datetime to a datetime older than four hours then Auth Token must be set. If you - * set Request Datetime with a datetime in the last four hours then you don't need to - * pass Auth Token. - * - * @param matomoDate the datetime of the request to set. A null value will remove this parameter - * @deprecated Use {@link #setRequestTimestamp(Instant)} instead - */ - @Deprecated - public void setRequestDatetime(MatomoDate matomoDate) { - if (matomoDate == null) { - requestTimestamp = null; - } else { - setRequestTimestamp(matomoDate.getZonedDateTime().toInstant()); - } - } - - /** - * Get the visit custom variable at the specified key. - * - * @param key the key of the variable to get - * @return the variable at the specified key, null if key is not present - * @deprecated Use the {@link #getVisitCustomVariables()} method instead. - */ - @Nullable - @Deprecated - public String getUserCustomVariable(String key) { - if (visitCustomVariables == null) { - return null; - } - return visitCustomVariables.get(key); - } - - /** - * Get the visit custom variable at the specified index. - * - * @param index the index of the variable to get - * @return the variable at the specified index, null if nothing at this index - * @deprecated Use {@link #getVisitCustomVariables()} instead - */ - @Nullable - @Deprecated - public CustomVariable getVisitCustomVariable(int index) { - return getCustomVariable(visitCustomVariables, index); - } - - /** - * Set a visit custom variable with the specified key and value at the first available index. All - * visit custom variables with this key will be overwritten or deleted - * - * @param key the key of the variable to set - * @param value the value of the variable to set at the specified key. A null value will remove - * this parameter - * @deprecated Use {@link #setVisitCustomVariables(CustomVariables)} instead - */ - @Deprecated - public void setUserCustomVariable(@NonNull String key, @Nullable String value) { - if (value == null) { - if (visitCustomVariables == null) { - return; - } - visitCustomVariables.remove(key); - } else { - CustomVariable variable = new CustomVariable(key, value); - if (visitCustomVariables == null) { - visitCustomVariables = new CustomVariables(); - } - visitCustomVariables.add(variable); - } - } - - /** - * Set a user custom variable at the specified key. - * - * @param customVariable the CustomVariable to set. A null value will remove the custom variable - * at the specified index - * @param index the index to set the customVariable at. - * @deprecated Use {@link #setVisitCustomVariables(CustomVariables)} instead - */ - @Deprecated - public void setVisitCustomVariable(@Nullable CustomVariable customVariable, int index) { - if (visitCustomVariables == null) { - if (customVariable == null) { - return; - } - visitCustomVariables = new CustomVariables(); - } - setCustomVariable(visitCustomVariables, customVariable, index); - } - - /** - * Sets a custom parameter to append to the Matomo tracking parameters. - * - *

Attention: If a parameter with the same name already exists, it will be appended twice! - * - * @param parameterName The name of the query parameter to append. Must not be null or empty. - * @param value The value of the query parameter to append. To remove the parameter, pass null. - * @deprecated Use @link {@link MatomoRequest.MatomoRequestBuilder#additionalParameters(Map)} - * instead - */ - @Deprecated - public void setParameter(@NonNull String parameterName, Object value) { - if (parameterName.trim().isEmpty()) { - throw new IllegalArgumentException("Parameter name must not be empty"); - } - if (additionalParameters == null) { - if (value == null) { - return; - } - additionalParameters = new LinkedHashMap<>(); - } - if (value == null) { - additionalParameters.remove(parameterName); - } else { - additionalParameters.put(parameterName, value); - } - } - - /** - * Creates a new {@link MatomoRequestBuilder} instance. Only here for backwards compatibility. - * - * @deprecated Use {@link MatomoRequest#request()} instead. - */ - @Deprecated - public static org.matomo.java.tracking.MatomoRequestBuilder builder() { - return new org.matomo.java.tracking.MatomoRequestBuilder(); - } - - /** - * Parses the given device resolution string and sets the {@link #deviceResolution} field. - * - * @param deviceResolution the device resolution string to parse. Format: "WIDTHxHEIGHT" - * @deprecated Use {@link #setDeviceResolution(DeviceResolution)} instead. - */ - @Tolerate - @Deprecated - public void setDeviceResolution(@Nullable String deviceResolution) { - if (deviceResolution == null || deviceResolution.trim().isEmpty()) { - this.deviceResolution = null; - } else { - this.deviceResolution = DeviceResolution.fromString(deviceResolution); - } - } } diff --git a/core/src/main/java/org/matomo/java/tracking/MatomoRequestBuilder.java b/core/src/main/java/org/matomo/java/tracking/MatomoRequestBuilder.java deleted file mode 100644 index 963e6916..00000000 --- a/core/src/main/java/org/matomo/java/tracking/MatomoRequestBuilder.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.matomo.java.tracking; - -import edu.umd.cs.findbugs.annotations.Nullable; -import java.util.Map; -import org.matomo.java.tracking.parameters.AcceptLanguage; - -/** - * The former MatomoRequestBuilder class has been moved to MatomoRequest.MatomoRequestBuilder. This - * class is only here for backwards compatibility. - * - * @deprecated Use {@link MatomoRequest.MatomoRequestBuilder} instead. - */ -@Deprecated -public class MatomoRequestBuilder extends MatomoRequest.MatomoRequestBuilder { - - /** - * Sets the tracking parameter for the accept languages of a user. Only here for backwards - * compatibility. - * - * @param headerAcceptLanguage The accept language header of a user. Must be in the format - * specified in RFC 2616. - * @return This builder - * @deprecated Use {@link MatomoRequest.MatomoRequestBuilder#headerAcceptLanguage(AcceptLanguage)} - * in combination with {@link AcceptLanguage#fromHeader(String)} instead. - */ - @Deprecated - public MatomoRequestBuilder headerAcceptLanguage(@Nullable String headerAcceptLanguage) { - headerAcceptLanguage(AcceptLanguage.fromHeader(headerAcceptLanguage)); - return this; - } - - /** - * Sets the custom tracking parameters to the given parameters. - * - *

This converts the given map to a map of collections. Only included for backwards - * compatibility. - * - * @param parameters The custom tracking parameters to set - * @return This builder - * @deprecated Use {@link MatomoRequest.MatomoRequestBuilder#additionalParameters(Map)}} - */ - @Deprecated - public MatomoRequestBuilder customTrackingParameters(@Nullable Map parameters) { - additionalParameters(parameters); - return this; - } -} diff --git a/core/src/main/java/org/matomo/java/tracking/MatomoTracker.java b/core/src/main/java/org/matomo/java/tracking/MatomoTracker.java index 0b382ecc..2d9c0cad 100644 --- a/core/src/main/java/org/matomo/java/tracking/MatomoTracker.java +++ b/core/src/main/java/org/matomo/java/tracking/MatomoTracker.java @@ -7,14 +7,9 @@ package org.matomo.java.tracking; -import edu.umd.cs.findbugs.annotations.Nullable; -import java.net.URI; -import java.time.Duration; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.CompletableFuture; -import java.util.function.Consumer; -import java.util.function.Function; import lombok.AccessLevel; import lombok.NonNull; import lombok.Setter; @@ -46,58 +41,6 @@ public class MatomoTracker implements AutoCloseable { private Sender sender; - /** - * Creates a tracker that will send {@link MatomoRequest}s to the specified Tracking HTTP API - * endpoint. - * - * @param hostUrl url endpoint to send requests to. Usually in the format - * https://your-matomo-domain.tld/matomo.php. Must not be null - * @deprecated Please use {@link MatomoTracker#MatomoTracker(TrackerConfiguration)} - */ - @Deprecated - public MatomoTracker(@NonNull String hostUrl) { - this(hostUrl, 0); - } - - /** - * Creates a tracker that will send {@link MatomoRequest}s to the specified Tracking HTTP API - * endpoint. - * - * @param hostUrl url endpoint to send requests to. Usually in the format - * https://your-matomo-domain.tld/matomo.php. - * @param timeout the timeout of the sent request in milliseconds or -1 if not set - * @deprecated Please use {@link MatomoTracker#MatomoTracker(TrackerConfiguration)} - */ - @Deprecated - public MatomoTracker(@NonNull String hostUrl, int timeout) { - this(hostUrl, null, 0, timeout); - } - - /** - * Creates a tracker that will send {@link MatomoRequest}s to the specified Tracking HTTP API - * endpoint. - * - * @param hostUrl url endpoint to send requests to. Usually in the format - * https://your-matomo-domain.tld/matomo.php. - * @param proxyHost The hostname or IP address of an optional HTTP proxy, null allowed - * @param proxyPort The port of an HTTP proxy or -1 if not set - * @param timeout the timeout of the request in milliseconds or -1 if not set - * @deprecated Please use {@link MatomoTracker#MatomoTracker(TrackerConfiguration)} - */ - @Deprecated - public MatomoTracker( - @NonNull String hostUrl, @Nullable String proxyHost, int proxyPort, int timeout) { - this( - TrackerConfiguration.builder() - .enabled(true) - .apiEndpoint(URI.create(hostUrl)) - .proxyHost(proxyHost) - .proxyPort(proxyPort) - .connectTimeout(timeout == -1 ? Duration.ofSeconds(5L) : Duration.ofSeconds(timeout)) - .socketTimeout(timeout == -1 ? Duration.ofSeconds(5L) : Duration.ofSeconds(timeout)) - .build()); - } - /** * Creates a new Matomo Tracker instance. * @@ -108,21 +51,6 @@ public MatomoTracker(@NonNull TrackerConfiguration trackerConfiguration) { this.trackerConfiguration = trackerConfiguration; } - /** - * Creates a tracker that will send {@link MatomoRequest}s to the specified Tracking HTTP API - * endpoint via the provided proxy. - * - * @param hostUrl url endpoint to send requests to. Usually in the format - * https://your-matomo-domain.tld/matomo.php. - * @param proxyHost url endpoint for the proxy, null allowed - * @param proxyPort proxy server port number or -1 if not set - * @deprecated Please use {@link MatomoTracker#MatomoTracker(TrackerConfiguration)} - */ - @Deprecated - public MatomoTracker(@NonNull String hostUrl, @Nullable String proxyHost, int proxyPort) { - this(hostUrl, proxyHost, proxyPort, -1); - } - /** * Sends a tracking request to Matomo using the HTTP GET method. * @@ -163,34 +91,11 @@ private void initializeSender() { * @return completable future to let you know when the request is done. Contains the request. */ public CompletableFuture sendRequestAsync(@NonNull MatomoRequest request) { - return sendRequestAsync(request, Function.identity()); - } - - /** - * Send a request asynchronously via HTTP GET and specify a callback that gets executed when the - * response arrives. - * - *

Use this method if you want to send a single request. If you want to send multiple requests - * at once, use {@link #sendBulkRequestAsync(Collection, Consumer)} instead. If you want to send - * multiple requests synchronously, use {@link #sendRequest(MatomoRequest)} or {@link - * #sendBulkRequest(Iterable)} instead. - * - * @param request request to send - * @param callback callback that gets executed when response arrives, must not be null - * @return a completable future to let you know when the request is done. The future contains the - * callback result. - * @deprecated Please use {@link MatomoTracker#sendRequestAsync(MatomoRequest)} in combination - * with {@link CompletableFuture#thenAccept(Consumer)} instead - */ - @Deprecated - public CompletableFuture sendRequestAsync( - @NonNull MatomoRequest request, @NonNull Function callback) { if (trackerConfiguration.isEnabled()) { applyGoalIdAndCheckSiteId(request); log.debug("Sending async request via GET: {}", request); initializeSender(); - CompletableFuture future = sender.sendSingleAsync(request); - return future.thenApply(callback); + return sender.sendSingleAsync(request); } log.warn("Not sending request, because tracker is disabled"); return CompletableFuture.completedFuture(null); @@ -223,7 +128,7 @@ private void applyGoalIdAndCheckSiteId(@NonNull MatomoRequest request) { * @param requests the requests to send */ public void sendBulkRequest(MatomoRequest... requests) { - sendBulkRequest(Arrays.asList(requests), null); + sendBulkRequest(Arrays.asList(requests)); } /** @@ -236,33 +141,13 @@ public void sendBulkRequest(MatomoRequest... requests) { * @param requests the requests to send */ public void sendBulkRequest(@NonNull Iterable requests) { - sendBulkRequest(requests, null); - } - - /** - * Send multiple requests in a single HTTP POST call. More efficient than sending several - * individual requests. - * - *

Specify the AuthToken if parameters that require an auth token is used. If you want to send - * a single request, use {@link #sendRequest(MatomoRequest)} instead. If you want to send multiple - * requests asynchronously, use {@link #sendBulkRequestAsync(Collection)} instead. - * - * @param requests the requests to send - * @param authToken specify if any of the parameters use require AuthToken, if null the default - * auth token from the request or the tracker configuration is used. - * @deprecated use {@link #sendBulkRequest(Iterable)} instead and set the auth token in the - * tracker configuration or the requests directly. - */ - @Deprecated - public void sendBulkRequest( - @NonNull Iterable requests, @Nullable String authToken) { if (trackerConfiguration.isEnabled()) { for (MatomoRequest request : requests) { applyGoalIdAndCheckSiteId(request); } log.debug("Sending requests via POST: {}", requests); initializeSender(); - sender.sendBulk(requests, authToken); + sender.sendBulk(requests); } else { log.warn("Not sending request, because tracker is disabled"); } @@ -276,7 +161,7 @@ public void sendBulkRequest( * @return completable future to let you know when the request is done */ public CompletableFuture sendBulkRequestAsync(MatomoRequest... requests) { - return sendBulkRequestAsync(Arrays.asList(requests), null, null); + return sendBulkRequestAsync(Arrays.asList(requests)); } /** @@ -288,70 +173,18 @@ public CompletableFuture sendBulkRequestAsync(MatomoRequest... requests) { */ public CompletableFuture sendBulkRequestAsync( @NonNull Collection requests) { - return sendBulkRequestAsync(requests, null, null); - } - - /** - * Send multiple requests in a single HTTP call. More efficient than sending several individual - * requests. Specify the AuthToken if parameters that require an auth token is used. - * - * @param requests the requests to send - * @param authToken specify if any of the parameters use require AuthToken, if null the default - * auth token from the request or the tracker configuration is used - * @param callback callback that gets executed when response arrives, null allowed - * @return a completable future to let you know when the request is done - * @deprecated Please set the auth token in the tracker configuration or the requests directly and - * use {@link CompletableFuture#thenAccept(Consumer)} instead for the callback. - */ - @Deprecated - public CompletableFuture sendBulkRequestAsync( - @NonNull Collection requests, - @Nullable String authToken, - @Nullable Consumer callback) { if (trackerConfiguration.isEnabled()) { for (MatomoRequest request : requests) { applyGoalIdAndCheckSiteId(request); } log.debug("Sending async requests via POST: {}", requests); initializeSender(); - CompletableFuture future = sender.sendBulkAsync(requests, authToken); - if (callback != null) { - return future.thenAccept(callback); - } - return future; + return sender.sendBulkAsync(requests); } log.warn("Tracker is disabled"); return CompletableFuture.completedFuture(null); } - /** - * Send multiple requests in a single HTTP call. More efficient than sending several individual - * requests. - * - * @param requests the requests to send - * @param callback callback that gets executed when response arrives, null allowed - * @return completable future to let you know when the request is done - */ - public CompletableFuture sendBulkRequestAsync( - @NonNull Collection requests, @Nullable Consumer callback) { - return sendBulkRequestAsync(requests, null, callback); - } - - /** - * Send multiple requests in a single HTTP call. More efficient than sending several individual - * requests. Specify the AuthToken if parameters that require an auth token is used. - * - * @param requests the requests to send - * @param authToken specify if any of the parameters use require AuthToken, null allowed - * @return completable future to let you know when the request is done - * @deprecated Please set the auth token in the tracker configuration or the requests directly and - * use {@link #sendBulkRequestAsync(Collection)} instead. - */ - public CompletableFuture sendBulkRequestAsync( - @NonNull Collection requests, @Nullable String authToken) { - return sendBulkRequestAsync(requests, authToken, null); - } - @Override public void close() throws Exception { if (sender != null) { diff --git a/core/src/main/java/org/matomo/java/tracking/Sender.java b/core/src/main/java/org/matomo/java/tracking/Sender.java index 24d40564..75c2243b 100644 --- a/core/src/main/java/org/matomo/java/tracking/Sender.java +++ b/core/src/main/java/org/matomo/java/tracking/Sender.java @@ -1,7 +1,6 @@ package org.matomo.java.tracking; import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.Nullable; import java.util.Collection; import java.util.concurrent.CompletableFuture; @@ -11,10 +10,8 @@ interface Sender extends AutoCloseable { void sendSingle(@NonNull MatomoRequest request); - void sendBulk( - @NonNull Iterable requests, @Nullable String overrideAuthToken); + void sendBulk(@NonNull Iterable requests); @NonNull - CompletableFuture sendBulkAsync( - @NonNull Collection requests, @Nullable String overrideAuthToken); + CompletableFuture sendBulkAsync(@NonNull Collection requests); } diff --git a/core/src/main/java/org/matomo/java/tracking/parameters/Country.java b/core/src/main/java/org/matomo/java/tracking/parameters/Country.java index aff24465..a86090cb 100644 --- a/core/src/main/java/org/matomo/java/tracking/parameters/Country.java +++ b/core/src/main/java/org/matomo/java/tracking/parameters/Country.java @@ -26,17 +26,6 @@ public class Country { @NonNull private String code; - /** - * Only for internal use to grant downwards compatibility to {@link - * org.matomo.java.tracking.MatomoLocale}. - * - * @param locale A locale that must contain a country code - */ - @Deprecated - protected Country(@edu.umd.cs.findbugs.annotations.NonNull Locale locale) { - setLocale(locale); - } - /** * Creates a country from a given code. * @@ -76,35 +65,6 @@ public static Country fromLanguageRanges(@Nullable String ranges) { throw new IllegalArgumentException("Invalid country code"); } - /** - * Returns the locale for this country. - * - * @return The locale for this country - * @see Locale#forLanguageTag(String) - * @deprecated Since you instantiate this class, you can determine the language on your own using - * {@link Locale#forLanguageTag(String)} - */ - @Deprecated - public Locale getLocale() { - return Locale.forLanguageTag(code); - } - - /** - * Sets the locale for this country. - * - * @param locale A locale that must contain a country code - * @see Locale#getCountry() - * @deprecated Since you instantiate this class, you can determine the language on your own using - * {@link Locale#getCountry()} - */ - @Deprecated - public final void setLocale(Locale locale) { - if (locale == null || locale.getCountry() == null || locale.getCountry().isEmpty()) { - throw new IllegalArgumentException("Invalid locale"); - } - code = locale.getCountry().toLowerCase(Locale.ENGLISH); - } - @Override public String toString() { return code; diff --git a/core/src/main/java/org/piwik/java/tracking/CustomVariable.java b/core/src/main/java/org/piwik/java/tracking/CustomVariable.java deleted file mode 100644 index e12cdae4..00000000 --- a/core/src/main/java/org/piwik/java/tracking/CustomVariable.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Matomo Java Tracker - * - * @link https://github.com/matomo/matomo-java-tracker - * @license https://github.com/matomo/matomo-java-tracker/blob/master/LICENSE BSD-3 Clause - */ - -package org.piwik.java.tracking; - -/** - * A user defined custom variable. - * - *

Renamed to {@link org.matomo.java.tracking.parameters.CustomVariable} in 3.0.0. - * - * @author brettcsorba - * @deprecated Use {@link org.matomo.java.tracking.parameters.CustomVariable} instead. - */ -@Deprecated -public class CustomVariable extends org.matomo.java.tracking.parameters.CustomVariable { - - /** - * Instantiates a new custom variable. - * - * @param key the key of the custom variable (required) - * @param value the value of the custom variable (required) - * @deprecated Use {@link org.matomo.java.tracking.parameters.CustomVariable} instead. - */ - @Deprecated - public CustomVariable(String key, String value) { - super(key, value); - } -} diff --git a/core/src/main/java/org/piwik/java/tracking/EcommerceItem.java b/core/src/main/java/org/piwik/java/tracking/EcommerceItem.java deleted file mode 100644 index e9b4ce6c..00000000 --- a/core/src/main/java/org/piwik/java/tracking/EcommerceItem.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Matomo Java Tracker - * - * @link https://github.com/matomo/matomo-java-tracker - * @license https://github.com/matomo/matomo-java-tracker/blob/master/LICENSE BSD-3 Clause - */ - -package org.piwik.java.tracking; - -/** - * Describes an item in an ecommerce transaction. - * - * @author brettcsorba - * @deprecated Use {@link org.matomo.java.tracking.parameters.EcommerceItem} instead. - */ -@Deprecated -public class EcommerceItem extends org.matomo.java.tracking.parameters.EcommerceItem { - - /** - * Creates a new ecommerce item. - * - * @param sku the sku (Stock Keeping Unit) of the item. - * @param name the name of the item. - * @param category the category of the item. - * @param price the price of the item. - * @param quantity the quantity of the item. - * @deprecated Use {@link org.matomo.java.tracking.parameters.EcommerceItem} instead. - */ - @Deprecated - public EcommerceItem(String sku, String name, String category, Double price, Integer quantity) { - super(sku, name, category, price, quantity); - } -} diff --git a/core/src/main/java/org/piwik/java/tracking/PiwikDate.java b/core/src/main/java/org/piwik/java/tracking/PiwikDate.java deleted file mode 100644 index 501ea8ac..00000000 --- a/core/src/main/java/org/piwik/java/tracking/PiwikDate.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Matomo Java Tracker - * - * @link https://github.com/matomo/matomo-java-tracker - * @license https://github.com/matomo/matomo-java-tracker/blob/master/LICENSE BSD-3 Clause - */ - -package org.piwik.java.tracking; - -import java.time.Instant; -import java.time.ZonedDateTime; -import java.util.TimeZone; -import org.matomo.java.tracking.MatomoDate; - -/** - * A date object that can be used to send dates to Matomo. This class is deprecated and will be - * removed in a future. - * - * @author brettcsorba - * @deprecated Please use {@link Instant} - */ -@Deprecated -public class PiwikDate extends MatomoDate { - - /** - * Creates a new date object with the current time. - * - * @deprecated Use {@link Instant} instead. - */ - @Deprecated - public PiwikDate() {} - - /** - * Creates a new date object with the specified time. The time is specified in milliseconds since - * the epoch. - * - * @param epochMilli The time in milliseconds since the epoch - * @deprecated Use {@link Instant} instead. - */ - @Deprecated - public PiwikDate(long epochMilli) { - super(epochMilli); - } - - /** - * Sets the time zone for this date object. This is used to convert the date to UTC before sending - * it to Matomo. - * - * @param zone the time zone to use - * @deprecated Use {@link ZonedDateTime#toInstant()} instead. - */ - @Deprecated - public void setTimeZone(TimeZone zone) { - setTimeZone(zone.toZoneId()); - } -} diff --git a/core/src/main/java/org/piwik/java/tracking/PiwikLocale.java b/core/src/main/java/org/piwik/java/tracking/PiwikLocale.java deleted file mode 100644 index 21f31cf7..00000000 --- a/core/src/main/java/org/piwik/java/tracking/PiwikLocale.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Matomo Java Tracker - * - * @link https://github.com/matomo/matomo-java-tracker - * @license https://github.com/matomo/matomo-java-tracker/blob/master/LICENSE BSD-3 Clause - */ - -package org.piwik.java.tracking; - -import java.util.Locale; -import org.matomo.java.tracking.parameters.Country; - -/** - * A locale object that can be used to send visitor country to Matomo. This class is deprecated and - * will be removed in the future. - * - * @author brettcsorba - * @deprecated Use {@link Country} instead. - */ -@Deprecated -public class PiwikLocale extends Country { - - /** - * Creates a new Piwik locale object with the specified locale. - * - * @param locale the locale to use - * @deprecated Use {@link Country} instead. - */ - @Deprecated - public PiwikLocale(Locale locale) { - super(locale); - } -} diff --git a/core/src/main/java/org/piwik/java/tracking/PiwikRequest.java b/core/src/main/java/org/piwik/java/tracking/PiwikRequest.java deleted file mode 100644 index 341cf1aa..00000000 --- a/core/src/main/java/org/piwik/java/tracking/PiwikRequest.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Matomo Java Tracker - * - * @link https://github.com/matomo/matomo-java-tracker - * @license https://github.com/matomo/matomo-java-tracker/blob/master/LICENSE BSD-3 Clause - */ - -package org.piwik.java.tracking; - -import static java.util.Objects.requireNonNull; - -import java.net.URL; -import org.matomo.java.tracking.MatomoRequest; - -/** - * A request object that can be used to send requests to Matomo. This class is deprecated and will - * be removed in the future. - * - * @author brettcsorba - * @deprecated Use {@link MatomoRequest} instead. - */ -@Deprecated -public class PiwikRequest extends MatomoRequest { - - /** - * Creates a new request object with the specified site ID and action URL. - * - * @param siteId the site ID - * @param actionUrl the action URL. Must not be null. - * @deprecated Use {@link MatomoRequest} instead. - */ - @Deprecated - public PiwikRequest(int siteId, URL actionUrl) { - super(siteId, requireNonNull(actionUrl, "Action URL must not be null").toString()); - } -} diff --git a/core/src/main/java/org/piwik/java/tracking/PiwikTracker.java b/core/src/main/java/org/piwik/java/tracking/PiwikTracker.java deleted file mode 100644 index 89caf0d3..00000000 --- a/core/src/main/java/org/piwik/java/tracking/PiwikTracker.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Matomo Java Tracker - * - * @link https://github.com/matomo/matomo-java-tracker - * @license https://github.com/matomo/matomo-java-tracker/blob/master/LICENSE BSD-3 Clause - */ - -package org.piwik.java.tracking; - -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.Nullable; -import org.matomo.java.tracking.MatomoTracker; - -/** - * Creates a new PiwikTracker instance. This class is deprecated and will be removed in the future. - * - * @author brettcsorba - * @deprecated Use {@link MatomoTracker} instead. - */ -@Deprecated -public class PiwikTracker extends MatomoTracker { - - /** - * Creates a new PiwikTracker instance with the given host URL. - * - * @param hostUrl the host URL of the Matomo server - * @deprecated Use {@link MatomoTracker} instead. - */ - @Deprecated - public PiwikTracker(@NonNull String hostUrl) { - super(hostUrl); - } - - /** - * Creates a new PiwikTracker instance with the given host URL and timeout in milliseconds. Use -1 - * for no timeout. - * - * @param hostUrl the host URL of the Matomo server - * @param timeout the timeout in milliseconds or -1 for no timeout - * @deprecated Use {@link MatomoTracker} instead. - */ - @Deprecated - public PiwikTracker(@NonNull String hostUrl, int timeout) { - super(hostUrl, timeout); - } - - /** - * Creates a new PiwikTracker instance with the given host URL and proxy settings. - * - * @param hostUrl the host URL of the Matomo server - * @param proxyHost the proxy host - * @param proxyPort the proxy port - * @deprecated Use {@link MatomoTracker} instead. - */ - @Deprecated - public PiwikTracker(@NonNull String hostUrl, @Nullable String proxyHost, int proxyPort) { - super(hostUrl, proxyHost, proxyPort); - } - - /** - * Creates a new PiwikTracker instance with the given host URL, proxy settings and timeout in - * milliseconds. Use -1 for no timeout. - * - * @param hostUrl the host URL of the Matomo server - * @param proxyHost the proxy host - * @param proxyPort the proxy port - * @param timeout the timeout in milliseconds or -1 for no timeout - * @deprecated Use {@link MatomoTracker} instead. - */ - @Deprecated - public PiwikTracker( - @NonNull String hostUrl, @Nullable String proxyHost, int proxyPort, int timeout) { - super(hostUrl, proxyHost, proxyPort, timeout); - } -} diff --git a/core/src/main/java/org/piwik/java/tracking/package-info.java b/core/src/main/java/org/piwik/java/tracking/package-info.java deleted file mode 100644 index 39f46a23..00000000 --- a/core/src/main/java/org/piwik/java/tracking/package-info.java +++ /dev/null @@ -1,2 +0,0 @@ -/** Piwik Java Tracking API. Renamed to {@link org.matomo.java.tracking} in 3.0.0. */ -package org.piwik.java.tracking; diff --git a/core/src/test/java/org/matomo/java/tracking/AuthTokenTest.java b/core/src/test/java/org/matomo/java/tracking/AuthTokenTest.java index cac2ba1e..bdafba71 100644 --- a/core/src/test/java/org/matomo/java/tracking/AuthTokenTest.java +++ b/core/src/test/java/org/matomo/java/tracking/AuthTokenTest.java @@ -16,7 +16,7 @@ void determineAuthTokenReturnsAuthTokenFromRequest() { .authToken("bdeca231a312ab12cde124131bedfa23") .build(); - String authToken = AuthToken.determineAuthToken(null, singleton(request), null); + String authToken = AuthToken.determineAuthToken(singleton(request), null); assertThat(authToken).isEqualTo("bdeca231a312ab12cde124131bedfa23"); } @@ -30,7 +30,7 @@ void determineAuthTokenReturnsAuthTokenFromTrackerConfiguration() { .defaultAuthToken("bdeca231a312ab12cde124131bedfa23") .build(); - String authToken = AuthToken.determineAuthToken(null, null, trackerConfiguration); + String authToken = AuthToken.determineAuthToken(null, trackerConfiguration); assertThat(authToken).isEqualTo("bdeca231a312ab12cde124131bedfa23"); } @@ -46,7 +46,7 @@ void determineAuthTokenFromTrackerConfigurationIfRequestTokenIsEmpty() { .defaultAuthToken("bdeca231a312ab12cde124131bedfa23") .build(); - String authToken = AuthToken.determineAuthToken(null, singleton(request), trackerConfiguration); + String authToken = AuthToken.determineAuthToken(singleton(request), trackerConfiguration); assertThat(authToken).isEqualTo("bdeca231a312ab12cde124131bedfa23"); } @@ -62,7 +62,7 @@ void determineAuthTokenFromTrackerConfigurationIfRequestTokenIsBlank() { .defaultAuthToken("bdeca231a312ab12cde124131bedfa23") .build(); - String authToken = AuthToken.determineAuthToken(null, singleton(request), trackerConfiguration); + String authToken = AuthToken.determineAuthToken(singleton(request), trackerConfiguration); assertThat(authToken).isEqualTo("bdeca231a312ab12cde124131bedfa23"); } diff --git a/core/src/test/java/org/matomo/java/tracking/BulkRequestTest.java b/core/src/test/java/org/matomo/java/tracking/BulkRequestTest.java index a78aac9b..87a6c382 100644 --- a/core/src/test/java/org/matomo/java/tracking/BulkRequestTest.java +++ b/core/src/test/java/org/matomo/java/tracking/BulkRequestTest.java @@ -5,12 +5,13 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.util.Arrays; import org.junit.jupiter.api.Test; class BulkRequestTest { @Test - void formatsQueriesAsJson() { + void formatsQueryAsJson() { BulkRequest bulkRequest = BulkRequest.builder() .queries(singleton("idsite=1&rec=1&action_name=TestBulkRequest")) @@ -24,6 +25,24 @@ void formatsQueriesAsJson() { "{\"requests\":[\"?idsite=1&rec=1&action_name=TestBulkRequest\"],\"token_auth\":\"token\"}"); } + @Test + void formatsQueriesAsJson() { + BulkRequest bulkRequest = + BulkRequest.builder() + .queries( + Arrays.asList( + "idsite=1&rec=1&action_name=TestBulkRequest1", + "idsite=1&rec=1" + "&action_name=TestBulkRequest2")) + .authToken("token") + .build(); + + byte[] bytes = bulkRequest.toBytes(); + + assertThat(new String(bytes)) + .isEqualTo( + "{\"requests\":[\"?idsite=1&rec=1&action_name=TestBulkRequest1\",\"?idsite=1&rec=1&action_name=TestBulkRequest2\"],\"token_auth\":\"token\"}"); + } + @Test void failsIfQueriesAreEmpty() { diff --git a/core/src/test/java/org/matomo/java/tracking/CustomVariableTest.java b/core/src/test/java/org/matomo/java/tracking/CustomVariableTest.java deleted file mode 100644 index 8f1cb0bd..00000000 --- a/core/src/test/java/org/matomo/java/tracking/CustomVariableTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.matomo.java.tracking; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import org.junit.jupiter.api.Test; - -class CustomVariableTest { - - @Test - void createsCustomVariable() { - CustomVariable customVariable = new CustomVariable("key", "value"); - - assertThat(customVariable.getKey()).isEqualTo("key"); - assertThat(customVariable.getValue()).isEqualTo("value"); - } - - @Test - void failsOnNullKey() { - assertThatThrownBy(() -> new CustomVariable(null, "value")) - .isInstanceOf(NullPointerException.class); - } - - @Test - void failsOnNullValue() { - assertThatThrownBy(() -> new CustomVariable("key", null)) - .isInstanceOf(NullPointerException.class); - } - - @Test - void failsOnNullKeyAndValue() { - assertThatThrownBy(() -> new CustomVariable(null, null)) - .isInstanceOf(NullPointerException.class); - } -} diff --git a/core/src/test/java/org/matomo/java/tracking/MatomoLocaleTest.java b/core/src/test/java/org/matomo/java/tracking/MatomoLocaleTest.java deleted file mode 100644 index c4d1f5ba..00000000 --- a/core/src/test/java/org/matomo/java/tracking/MatomoLocaleTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.matomo.java.tracking; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.Locale; -import org.junit.jupiter.api.Test; - -class MatomoLocaleTest { - - @Test - void createsMatomoLocaleFromLocale() { - MatomoLocale locale = new MatomoLocale(Locale.US); - assertThat(locale.toString()).isEqualTo("us"); - } - - @Test - void failsIfLocaleIsNull() { - assertThatThrownBy(() -> new MatomoLocale(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("Locale must not be null"); - } -} diff --git a/core/src/test/java/org/matomo/java/tracking/MatomoRequestBuilderTest.java b/core/src/test/java/org/matomo/java/tracking/MatomoRequestBuilderTest.java deleted file mode 100644 index d46403d2..00000000 --- a/core/src/test/java/org/matomo/java/tracking/MatomoRequestBuilderTest.java +++ /dev/null @@ -1,84 +0,0 @@ -package org.matomo.java.tracking; - -import static java.util.Collections.singletonMap; -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.Test; -import org.matomo.java.tracking.parameters.CustomVariables; - -class MatomoRequestBuilderTest { - - @Test - void buildsRequest() { - CustomVariable pageCustomVariable = - new CustomVariable("pageCustomVariableName", "pageCustomVariableValue"); - CustomVariable visitCustomVariable = - new CustomVariable("visitCustomVariableName", "visitCustomVariableValue"); - - MatomoRequest matomoRequest = - new MatomoRequestBuilder() - .siteId(42) - .actionName("ACTION_NAME") - .actionUrl("https://www.your-domain.tld/some/page?query=foo") - .referrerUrl("https://referrer.com") - .additionalParameters(singletonMap("trackingParameterName", "trackingParameterValue")) - .pageCustomVariables(new CustomVariables().add(pageCustomVariable, 2)) - .visitCustomVariables(new CustomVariables().add(visitCustomVariable, 3)) - .customAction(true) - .build(); - - assertThat(matomoRequest.getSiteId()).isEqualTo(42); - assertThat(matomoRequest.getActionName()).isEqualTo("ACTION_NAME"); - assertThat(matomoRequest.getApiVersion()).isEqualTo("1"); - assertThat(matomoRequest.getActionUrl()) - .isEqualTo("https://www.your-domain.tld/some/page?query=foo"); - assertThat(matomoRequest.getVisitorId().toString()).hasSize(16).isHexadecimal(); - assertThat(matomoRequest.getRandomValue().toString()).hasSize(20).isHexadecimal(); - assertThat(matomoRequest.getResponseAsImage()).isFalse(); - assertThat(matomoRequest.getRequired()).isTrue(); - assertThat(matomoRequest.getReferrerUrl()).isEqualTo("https://referrer.com"); - assertThat(matomoRequest.getCustomTrackingParameter("trackingParameterName")) - .isEqualTo("trackingParameterValue"); - assertThat(matomoRequest.getPageCustomVariables()) - .hasToString("{\"2\":[\"pageCustomVariableName\",\"pageCustomVariableValue\"]}"); - assertThat(matomoRequest.getVisitCustomVariables()) - .hasToString("{\"3\":[\"visitCustomVariableName\",\"visitCustomVariableValue\"]}"); - assertThat(matomoRequest.getCustomAction()).isTrue(); - } - - @Test - void setCustomTrackingParameters() { - MatomoRequest matomoRequest = - new MatomoRequestBuilder() - .customTrackingParameters(singletonMap("foo", "bar")) - .siteId(42) - .actionName("ACTION_NAME") - .actionUrl("https://www.your-domain.tld/some/page?query=foo") - .referrerUrl("https://referrer.com") - .build(); - - assertThat(matomoRequest.getCustomTrackingParameter("foo")).isEqualTo("bar"); - } - - @Test - void setCustomTrackingParametersWithCollectopm() { - MatomoRequest matomoRequest = - new MatomoRequestBuilder() - .customTrackingParameters(singletonMap("foo", "bar")) - .siteId(42) - .actionName("ACTION_NAME") - .actionUrl("https://www.your-domain.tld/some/page?query=foo") - .referrerUrl("https://referrer.com") - .build(); - - assertThat(matomoRequest.getCustomTrackingParameter("foo")).isEqualTo("bar"); - } - - @Test - void acceptsNullAsHeaderAcceptLanguage() { - MatomoRequest matomoRequest = - new MatomoRequestBuilder().headerAcceptLanguage((String) null).build(); - - assertThat(matomoRequest.getHeaderAcceptLanguage()).isNull(); - } -} diff --git a/core/src/test/java/org/matomo/java/tracking/MatomoRequestTest.java b/core/src/test/java/org/matomo/java/tracking/MatomoRequestTest.java deleted file mode 100644 index 20d2c2f5..00000000 --- a/core/src/test/java/org/matomo/java/tracking/MatomoRequestTest.java +++ /dev/null @@ -1,133 +0,0 @@ -package org.matomo.java.tracking; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; - -import org.junit.jupiter.api.Test; - -class MatomoRequestTest { - - private MatomoRequest request = new MatomoRequest(); - - @Test - void returnsEmptyListWhenCustomTrackingParametersDoesNotContainKey() { - - request.setCustomTrackingParameter("foo", "bar"); - - assertThat(request.getCustomTrackingParameter("baz")).isNull(); - assertThat(request.getAdditionalParameters()).isNotEmpty(); - assertThat(request.getCustomTrackingParameter("foo")).isEqualTo("bar"); - } - - @Test - void getPageCustomVariableReturnsNullIfPageCustomVariablesIsNull() { - assertThat(request.getPageCustomVariable("foo")).isNull(); - } - - @Test - void getPageCustomVariableReturnsValueIfPageCustomVariablesIsNotNull() { - request.setPageCustomVariable("foo", "bar"); - assertThat(request.getPageCustomVariable("foo")).isEqualTo("bar"); - } - - @Test - void setPageCustomVariableRequiresNonNullKey() { - assertThatThrownBy(() -> request.setPageCustomVariable(null, "bar")) - .isInstanceOf(NullPointerException.class); - } - - @Test - void setPageCustomVariableDoesNothingIfValueIsNull() { - request.setPageCustomVariable("foo", null); - assertThat(request.getPageCustomVariable("foo")).isNull(); - } - - @Test - void setPageCustomVariableRemovesValueIfValueIsNull() { - request.setPageCustomVariable("foo", "bar"); - request.setPageCustomVariable("foo", null); - assertThat(request.getPageCustomVariable("foo")).isNull(); - } - - @Test - void setPageCustomVariableAddsCustomVariableIfValueIsNotNull() { - request.setPageCustomVariable("foo", "bar"); - assertThat(request.getPageCustomVariable("foo")).isEqualTo("bar"); - } - - @Test - void setPageCustomVariableDoesNothingIfCustomVariableParameterIsNullAndIndexIsPositive() { - request.setPageCustomVariable(null, 1); - assertThat(request.getPageCustomVariable(1)).isNull(); - } - - @Test - void - setPageCustomVariableInitializesPageCustomVariablesIfCustomVariableParameterIsNullAndIndexIsPositive() { - request.setPageCustomVariable(new CustomVariable("key", "value"), 1); - assertThat(request.getPageCustomVariables()).isNotNull(); - } - - @Test - void setUserCustomVariableDoesNothingIfValueIsNull() { - request.setUserCustomVariable("foo", null); - assertThat(request.getUserCustomVariable("foo")).isNull(); - } - - @Test - void setUserCustomVariableRemovesValueIfValueIsNull() { - request.setUserCustomVariable("foo", "bar"); - request.setUserCustomVariable("foo", null); - assertThat(request.getUserCustomVariable("foo")).isNull(); - } - - @Test - void setVisitCustomVariableDoesNothingIfCustomVariableParameterIsNullAndIndexIsPositive() { - request.setVisitCustomVariable(null, 1); - assertThat(request.getVisitCustomVariable(1)).isNull(); - } - - @Test - void - setVisitCustomVariableInitializesVisitCustomVariablesIfCustomVariableParameterIsNullAndIndexIsPositive() { - request.setVisitCustomVariable(new CustomVariable("key", "value"), 1); - assertThat(request.getVisitCustomVariables()).isNotNull(); - } - - @Test - void setsCustomParameter() { - request.setParameter("foo", 1); - assertThat(request.getCustomTrackingParameter("foo")).isEqualTo(1); - } - - @Test - void failsToSetCustomParameterIfKeyIsNull() { - assertThatThrownBy(() -> request.setParameter(null, 1)) - .isInstanceOf(NullPointerException.class); - } - - @Test - void doesNothingWhenSettingCustomParameterIfValueIsNull() { - request.setParameter("foo", null); - assertThat(request.getAdditionalParameters()).isNull(); - } - - @Test - void removesCustomParameter() { - request.setParameter("foo", 1); - request.setParameter("foo", null); - assertThat(request.getAdditionalParameters()).isEmpty(); - } - - @Test - void setsDeviceResolutionString() { - request.setDeviceResolution("1920x1080"); - assertThat(request.getDeviceResolution().toString()).isEqualTo("1920x1080"); - } - - @Test - void failsIfSetParameterParameterNameIsBlank() { - assertThatThrownBy(() -> request.setParameter(" ", "bar")) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/core/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java b/core/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java index efbdb067..6171bd52 100644 --- a/core/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java +++ b/core/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java @@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.net.URI; +import java.time.Duration; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.Test; import org.matomo.java.tracking.parameters.RandomValue; @@ -28,7 +29,8 @@ class MatomoTrackerIT { @Test void sendsRequest() { - matomoTracker = new MatomoTracker(HOST_URL); + matomoTracker = + new MatomoTracker(TrackerConfiguration.builder().apiEndpoint(URI.create(HOST_URL)).build()); matomoTracker.setSenderFactory(senderFactory); matomoTracker.sendRequest(request); @@ -41,7 +43,8 @@ void sendsRequest() { @Test void validatesRequest() { - matomoTracker = new MatomoTracker(HOST_URL); + matomoTracker = + new MatomoTracker(TrackerConfiguration.builder().apiEndpoint(URI.create(HOST_URL)).build()); matomoTracker.setSenderFactory(senderFactory); request.setSiteId(null); @@ -71,7 +74,13 @@ void doesNotSendRequestIfNotEnabled() { @Test void sendsRequestUsingProxy() { - matomoTracker = new MatomoTracker(HOST_URL, "localhost", 8081); + matomoTracker = + new MatomoTracker( + TrackerConfiguration.builder() + .apiEndpoint(URI.create(HOST_URL)) + .proxyHost("localhost") + .proxyPort(8081) + .build()); matomoTracker.setSenderFactory(senderFactory); matomoTracker.sendRequest(request); @@ -86,7 +95,13 @@ void sendsRequestUsingProxy() { @Test void sendsRequestAsync() { - matomoTracker = new MatomoTracker(HOST_URL, 1000); + matomoTracker = + new MatomoTracker( + TrackerConfiguration.builder() + .apiEndpoint(URI.create(HOST_URL)) + .connectTimeout(Duration.ofSeconds(1L)) + .socketTimeout(Duration.ofSeconds(1L)) + .build()); matomoTracker.setSenderFactory(senderFactory); matomoTracker.sendRequestAsync(request); @@ -99,16 +114,22 @@ void sendsRequestAsync() { @Test void sendsRequestAsyncWithCallback() { - matomoTracker = new MatomoTracker(HOST_URL, 1000); + matomoTracker = + new MatomoTracker( + TrackerConfiguration.builder() + .apiEndpoint(URI.create(HOST_URL)) + .connectTimeout(Duration.ofSeconds(1L)) + .socketTimeout(Duration.ofSeconds(1L)) + .build()); matomoTracker.setSenderFactory(senderFactory); AtomicBoolean callbackCalled = new AtomicBoolean(); - matomoTracker.sendRequestAsync( - request, - request -> { - assertThat(request).isEqualTo(request); - callbackCalled.set(true); - return null; - }); + matomoTracker + .sendRequestAsync(request) + .thenAccept( + request -> { + assertThat(request).isEqualTo(this.request); + callbackCalled.set(true); + }); TestSender testSender = senderFactory.getTestSender(); thenContainsRequest(testSender, QUERY); @@ -135,7 +156,8 @@ void doesNotSendRequestAsyncIfNotEnabled() { @Test void sendsBulkRequests() { - matomoTracker = new MatomoTracker(HOST_URL); + matomoTracker = + new MatomoTracker(TrackerConfiguration.builder().apiEndpoint(URI.create(HOST_URL)).build()); matomoTracker.setSenderFactory(senderFactory); matomoTracker.sendBulkRequest(request); @@ -164,7 +186,13 @@ void doesNotSendBulkRequestsIfNotEnabled() { @Test void sendsBulkRequestsAsync() { - matomoTracker = new MatomoTracker(HOST_URL, 1000); + matomoTracker = + new MatomoTracker( + TrackerConfiguration.builder() + .apiEndpoint(URI.create(HOST_URL)) + .connectTimeout(Duration.ofSeconds(1L)) + .socketTimeout(Duration.ofSeconds(1L)) + .build()); matomoTracker.setSenderFactory(senderFactory); matomoTracker.sendBulkRequestAsync(request); @@ -193,10 +221,18 @@ void doesNotSendBulkRequestsAsyncIfNotEnabled() { @Test void sendsBulkRequestAsyncWithCallback() { - matomoTracker = new MatomoTracker(HOST_URL, 1000); + matomoTracker = + new MatomoTracker( + TrackerConfiguration.builder() + .apiEndpoint(URI.create(HOST_URL)) + .connectTimeout(Duration.ofSeconds(1L)) + .socketTimeout(Duration.ofSeconds(1L)) + .build()); matomoTracker.setSenderFactory(senderFactory); AtomicBoolean callbackCalled = new AtomicBoolean(); - matomoTracker.sendBulkRequestAsync(singleton(request), v -> callbackCalled.set(true)); + matomoTracker + .sendBulkRequestAsync(singleton(request)) + .thenAccept(request -> callbackCalled.set(true)); TestSender testSender = senderFactory.getTestSender(); thenContainsRequest(testSender, QUERY); @@ -204,24 +240,11 @@ void sendsBulkRequestAsyncWithCallback() { assertThat(callbackCalled).isTrue(); } - @Test - void sendsBulkRequestAsyncWithAuthToken() { - - matomoTracker = new MatomoTracker(HOST_URL, 1000); - matomoTracker.setSenderFactory(senderFactory); - matomoTracker.sendBulkRequestAsync(singleton(request), "abc123def456abc123def456abc123de"); - - TestSender testSender = senderFactory.getTestSender(); - thenContainsRequest( - testSender, - "token_auth=abc123def456abc123def456abc123de&rec=1&idsite=1&action_name=test&apiv=1&_id=00000000343efaf5&send_image=0&rand=test-random"); - assertThat(testSender.getTrackerConfiguration().getApiEndpoint()).hasToString(HOST_URL); - } - @Test void appliesGoalId() { - matomoTracker = new MatomoTracker(HOST_URL); + matomoTracker = + new MatomoTracker(TrackerConfiguration.builder().apiEndpoint(URI.create(HOST_URL)).build()); matomoTracker.setSenderFactory(senderFactory); request.setEcommerceId("some-id"); diff --git a/core/src/test/java/org/matomo/java/tracking/PiwikDateTest.java b/core/src/test/java/org/matomo/java/tracking/PiwikDateTest.java deleted file mode 100644 index c5d99795..00000000 --- a/core/src/test/java/org/matomo/java/tracking/PiwikDateTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.matomo.java.tracking; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.TimeZone; -import org.junit.jupiter.api.Test; -import org.piwik.java.tracking.PiwikDate; - -class PiwikDateTest { - - /** Test of constructor, of class PiwikDate. */ - @Test - void testConstructor0() { - PiwikDate date = new PiwikDate(); - assertThat(date).isNotNull(); - } - - @Test - void testConstructor1() { - PiwikDate date = new PiwikDate(1433186085092L); - assertThat(date).isNotNull(); - assertThat(date.getTime()).isEqualTo(1433186085092L); - } - - @Test - void testConstructor2() { - PiwikDate date = new PiwikDate(1467437553000L); - assertThat(date.getTime()).isEqualTo(1467437553000L); - } - - /** Test of setTimeZone method, of class PiwikDate. */ - @Test - void testSetTimeZone() { - PiwikDate date = new PiwikDate(1433186085092L); - date.setTimeZone(TimeZone.getTimeZone("America/New_York")); - assertThat(date.getTime()).isEqualTo(1433186085092L); - } -} diff --git a/core/src/test/java/org/matomo/java/tracking/PiwikLocaleTest.java b/core/src/test/java/org/matomo/java/tracking/PiwikLocaleTest.java deleted file mode 100644 index a03b97c9..00000000 --- a/core/src/test/java/org/matomo/java/tracking/PiwikLocaleTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.matomo.java.tracking; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Locale; -import org.junit.jupiter.api.Test; -import org.piwik.java.tracking.PiwikLocale; - -class PiwikLocaleTest { - - private final PiwikLocale locale = new PiwikLocale(Locale.US); - - /** Test of setLocale method, of class PiwikLocale. */ - @Test - void testLocale() { - locale.setLocale(Locale.GERMANY); - assertThat(locale.getLocale()).isEqualTo(Locale.GERMAN); - } - - /** Test of toString method, of class PiwikLocale. */ - @Test - void testToString() { - assertThat(locale).hasToString("us"); - } -} diff --git a/core/src/test/java/org/matomo/java/tracking/PiwikRequestTest.java b/core/src/test/java/org/matomo/java/tracking/PiwikRequestTest.java deleted file mode 100644 index 6f11c1e7..00000000 --- a/core/src/test/java/org/matomo/java/tracking/PiwikRequestTest.java +++ /dev/null @@ -1,809 +0,0 @@ -package org.matomo.java.tracking; - -import static java.time.temporal.ChronoUnit.MINUTES; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.fail; -import static org.assertj.core.api.Assertions.within; - -import java.net.URL; -import java.nio.charset.Charset; -import java.time.Instant; -import java.time.ZonedDateTime; -import java.util.Locale; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.matomo.java.tracking.parameters.AcceptLanguage; -import org.matomo.java.tracking.parameters.DeviceResolution; -import org.matomo.java.tracking.parameters.RandomValue; -import org.matomo.java.tracking.parameters.VisitorId; -import org.piwik.java.tracking.PiwikDate; -import org.piwik.java.tracking.PiwikLocale; -import org.piwik.java.tracking.PiwikRequest; - -class PiwikRequestTest { - - private PiwikRequest request; - - @BeforeEach - void setUp() throws Exception { - request = new PiwikRequest(3, new URL("https://test.com")); - } - - @Test - void testConstructor() throws Exception { - request = new PiwikRequest(3, new URL("https://test.com")); - assertThat(request.getSiteId()).isEqualTo(Integer.valueOf(3)); - assertThat(request.getRequired()).isTrue(); - assertThat(request.getActionUrl()).isEqualTo("https://test.com"); - assertThat(request.getVisitorId()).isNotNull(); - assertThat(request.getRandomValue()).isNotNull(); - assertThat(request.getApiVersion()).isEqualTo("1"); - assertThat(request.getResponseAsImage()).isFalse(); - } - - /** Test of getActionName method, of class PiwikRequest. */ - @Test - void testActionName() { - request.setActionName("action"); - assertThat(request.getActionName()).isEqualTo("action"); - request.setActionName(null); - assertThat(request.getActionName()).isNull(); - } - - /** Test of getActionUrl method, of class PiwikRequest. */ - @Test - void testActionUrl() { - request.setActionUrl(null); - assertThat(request.getActionUrl()).isNull(); - request.setActionUrl("https://action.com"); - assertThat(request.getActionUrl()).isEqualTo("https://action.com"); - } - - /** Test of getApiVersion method, of class PiwikRequest. */ - @Test - void testApiVersion() { - request.setApiVersion("2"); - assertThat(request.getApiVersion()).isEqualTo("2"); - } - - @Test - void testAuthTokenTF() { - request.setAuthToken("12345678901234567890123456789012"); - assertThat(request.getAuthToken()).isEqualTo("12345678901234567890123456789012"); - } - - @Test - void testAuthTokenF() { - request.setAuthToken("12345678901234567890123456789012"); - request.setAuthToken(null); - assertThat(request.getAuthToken()).isNull(); - } - - /** Test of getCampaignKeyword method, of class PiwikRequest. */ - @Test - void testCampaignKeyword() { - request.setCampaignKeyword("keyword"); - assertThat(request.getCampaignKeyword()).isEqualTo("keyword"); - } - - /** Test of getCampaignName method, of class PiwikRequest. */ - @Test - void testCampaignName() { - request.setCampaignName("name"); - assertThat(request.getCampaignName()).isEqualTo("name"); - } - - /** Test of getCharacterSet method, of class PiwikRequest. */ - @Test - void testCharacterSet() { - Charset charset = Charset.defaultCharset(); - request.setCharacterSet(charset); - assertThat(request.getCharacterSet()).isEqualTo(charset); - } - - /** Test of getContentInteraction method, of class PiwikRequest. */ - @Test - void testContentInteraction() { - request.setContentInteraction("interaction"); - assertThat(request.getContentInteraction()).isEqualTo("interaction"); - } - - /** Test of getContentName method, of class PiwikRequest. */ - @Test - void testContentName() { - request.setContentName("name"); - assertThat(request.getContentName()).isEqualTo("name"); - } - - /** Test of getContentPiece method, of class PiwikRequest. */ - @Test - void testContentPiece() { - request.setContentPiece("piece"); - assertThat(request.getContentPiece()).isEqualTo("piece"); - } - - /** Test of getContentTarget method, of class PiwikRequest. */ - @Test - void testContentTarget() { - request.setContentTarget("https://target.com"); - assertThat(request.getContentTarget()).isEqualTo("https://target.com"); - } - - /** Test of getCurrentHour method, of class PiwikRequest. */ - @Test - void testCurrentHour() { - request.setCurrentHour(1); - assertThat(request.getCurrentHour()).isEqualTo(Integer.valueOf(1)); - } - - /** Test of getCurrentMinute method, of class PiwikRequest. */ - @Test - void testCurrentMinute() { - request.setCurrentMinute(2); - assertThat(request.getCurrentMinute()).isEqualTo(Integer.valueOf(2)); - } - - /** Test of getCurrentSecond method, of class PiwikRequest. */ - @Test - void testCurrentSecond() { - request.setCurrentSecond(3); - assertThat(request.getCurrentSecond()).isEqualTo(Integer.valueOf(3)); - } - - /** Test of getCustomTrackingParameter method, of class PiwikRequest. */ - @Test - void testGetCustomTrackingParameter_T() { - try { - request.getCustomTrackingParameter(null); - fail("Exception should have been thrown."); - } catch (NullPointerException e) { - assertThat(e.getLocalizedMessage()).isEqualTo("key is marked non-null but is null"); - } - } - - @Test - void testGetCustomTrackingParameter_FT() { - assertThat(request.getCustomTrackingParameter("key")).isNull(); - } - - @Test - void testSetCustomTrackingParameter_T() { - try { - request.setCustomTrackingParameter(null, null); - fail("Exception should have been thrown."); - } catch (NullPointerException e) { - assertThat(e.getLocalizedMessage()).isEqualTo("key is marked non-null but is null"); - } - } - - @Test - void testSetCustomTrackingParameter1() { - request.setCustomTrackingParameter("key", "value"); - Object l = request.getCustomTrackingParameter("key"); - assertThat(l).isEqualTo("value"); - request.setCustomTrackingParameter("key", "value2"); - } - - @Test - void testSetCustomTrackingParameter2() { - request.setCustomTrackingParameter("key", "value2"); - Object l = request.getCustomTrackingParameter("key"); - assertThat(l).isEqualTo("value2"); - request.setCustomTrackingParameter("key", null); - l = request.getCustomTrackingParameter("key"); - assertThat(l).isNull(); - } - - @Test - void testSetCustomTrackingParameter3() { - request.setCustomTrackingParameter("key", null); - Object l = request.getCustomTrackingParameter("key"); - assertThat(l).isNull(); - } - - @Test - void testAddCustomTrackingParameter_T() { - try { - request.addCustomTrackingParameter(null, null); - fail("Exception should have been thrown."); - } catch (NullPointerException e) { - assertThat(e.getLocalizedMessage()).isEqualTo("key is marked non-null but is null"); - } - } - - @Test - void testAddCustomTrackingParameter1() { - request.addCustomTrackingParameter("key", "value"); - Object l = request.getCustomTrackingParameter("key"); - assertThat(l).isEqualTo("value"); - } - - @Test - void testAddCustomTrackingParameter2() { - request.addCustomTrackingParameter("key", "value"); - request.addCustomTrackingParameter("key", "value2"); - Object l = request.getCustomTrackingParameter("key"); - assertThat(l).isEqualTo("value2"); - } - - @Test - void testClearCustomTrackingParameter() { - request.setCustomTrackingParameter("key", "value"); - request.clearCustomTrackingParameter(); - Object l = request.getCustomTrackingParameter("key"); - assertThat(l).isNull(); - } - - /** Test of getDeviceResolution method, of class PiwikRequest. */ - @Test - void testDeviceResolution() { - request.setDeviceResolution(DeviceResolution.fromString("100x200")); - assertThat(request.getDeviceResolution()).hasToString("100x200"); - } - - /** Test of getDownloadUrl method, of class PiwikRequest. */ - @Test - void testDownloadUrl() { - - request.setDownloadUrl("https://download.com"); - assertThat(request.getDownloadUrl()).isEqualTo("https://download.com"); - } - - /** Test of enableEcommerce method, of class PiwikRequest. */ - @Test - void testEnableEcommerce() { - request.enableEcommerce(); - assertThat(request.getGoalId()).isEqualTo(Integer.valueOf(0)); - } - - /** Test of getEcommerceDiscount method, of class PiwikRequest. */ - @Test - void testEcommerceDiscountT() { - request.enableEcommerce(); - request.setEcommerceId("1"); - request.setEcommerceRevenue(2.0); - request.setEcommerceDiscount(1.0); - assertThat(request.getEcommerceDiscount()).isEqualTo(Double.valueOf(1.0)); - } - - @Test - void testEcommerceDiscountF() { - request.setEcommerceDiscount(null); - assertThat(request.getEcommerceDiscount()).isNull(); - } - - /** Test of getEcommerceId method, of class PiwikRequest. */ - @Test - void testEcommerceIdT() { - request.enableEcommerce(); - request.setEcommerceId("1"); - assertThat(request.getEcommerceId()).isEqualTo("1"); - } - - @Test - void testEcommerceIdF() { - request.setEcommerceId(null); - assertThat(request.getEcommerceId()).isNull(); - } - - @Test - void testEcommerceItemE2() { - try { - request.enableEcommerce(); - request.setEcommerceId("1"); - request.setEcommerceRevenue(2.0); - request.addEcommerceItem(null); - fail("Exception should have been thrown."); - } catch (NullPointerException e) { - assertThat(e.getLocalizedMessage()).isEqualTo("item is marked non-null but is null"); - } - } - - @Test - void testEcommerceItem() { - assertThat(request.getEcommerceItem(0)).isNull(); - EcommerceItem item = new EcommerceItem("sku", "name", "category", 1.0, 2); - request.enableEcommerce(); - request.setEcommerceId("1"); - request.setEcommerceRevenue(2.0); - request.addEcommerceItem(item); - assertThat(request.getEcommerceItem(0)).isEqualTo(item); - request.clearEcommerceItems(); - assertThat(request.getEcommerceItem(0)).isNull(); - } - - /** Test of getEcommerceLastOrderTimestamp method, of class PiwikRequest. */ - @Test - void testEcommerceLastOrderTimestampT() { - request.enableEcommerce(); - request.setEcommerceId("1"); - request.setEcommerceRevenue(2.0); - request.setEcommerceLastOrderTimestamp(Instant.ofEpochSecond(1000L)); - assertThat(request.getEcommerceLastOrderTimestamp()).isEqualTo("1970-01-01T00:16:40Z"); - } - - @Test - void testEcommerceLastOrderTimestampF() { - request.setEcommerceLastOrderTimestamp(null); - assertThat(request.getEcommerceLastOrderTimestamp()).isNull(); - } - - /** Test of getEcommerceRevenue method, of class PiwikRequest. */ - @Test - void testEcommerceRevenueT() { - request.enableEcommerce(); - request.setEcommerceId("1"); - request.setEcommerceRevenue(20.0); - assertThat(request.getEcommerceRevenue()).isEqualTo(Double.valueOf(20.0)); - } - - @Test - void testEcommerceRevenueF() { - request.setEcommerceRevenue(null); - assertThat(request.getEcommerceRevenue()).isNull(); - } - - /** Test of getEcommerceShippingCost method, of class PiwikRequest. */ - @Test - void testEcommerceShippingCostT() { - request.enableEcommerce(); - request.setEcommerceId("1"); - request.setEcommerceRevenue(2.0); - request.setEcommerceShippingCost(20.0); - assertThat(request.getEcommerceShippingCost()).isEqualTo(Double.valueOf(20.0)); - } - - @Test - void testEcommerceShippingCostF() { - request.setEcommerceShippingCost(null); - assertThat(request.getEcommerceShippingCost()).isNull(); - } - - /** Test of getEcommerceSubtotal method, of class PiwikRequest. */ - @Test - void testEcommerceSubtotalT() { - request.enableEcommerce(); - request.setEcommerceId("1"); - request.setEcommerceRevenue(2.0); - request.setEcommerceSubtotal(20.0); - assertThat(request.getEcommerceSubtotal()).isEqualTo(Double.valueOf(20.0)); - } - - @Test - void testEcommerceSubtotalF() { - request.setEcommerceSubtotal(null); - assertThat(request.getEcommerceSubtotal()).isNull(); - } - - /** Test of getEcommerceTax method, of class PiwikRequest. */ - @Test - void testEcommerceTaxT() { - request.enableEcommerce(); - request.setEcommerceId("1"); - request.setEcommerceRevenue(2.0); - request.setEcommerceTax(20.0); - assertThat(request.getEcommerceTax()).isEqualTo(Double.valueOf(20.0)); - } - - @Test - void testEcommerceTaxF() { - request.setEcommerceTax(null); - assertThat(request.getEcommerceTax()).isNull(); - } - - /** Test of getEventAction method, of class PiwikRequest. */ - @Test - void testEventAction() { - request.setEventAction("action"); - assertThat(request.getEventAction()).isEqualTo("action"); - request.setEventAction(null); - assertThat(request.getEventAction()).isNull(); - } - - /** Test of getEventCategory method, of class PiwikRequest. */ - @Test - void testEventCategory() { - request.setEventCategory("category"); - assertThat(request.getEventCategory()).isEqualTo("category"); - } - - /** Test of getEventName method, of class PiwikRequest. */ - @Test - void testEventName() { - request.setEventName("name"); - assertThat(request.getEventName()).isEqualTo("name"); - } - - /** Test of getEventValue method, of class PiwikRequest. */ - @Test - void testEventValue() { - request.setEventValue(1.0); - assertThat(request.getEventValue()).isOne(); - } - - /** Test of getGoalId method, of class PiwikRequest. */ - @Test - void testGoalId() { - request.setGoalId(1); - assertThat(request.getGoalId()).isEqualTo(Integer.valueOf(1)); - } - - /** Test of getHeaderAcceptLanguage method, of class PiwikRequest. */ - @Test - void testHeaderAcceptLanguage() { - request.setHeaderAcceptLanguage(AcceptLanguage.fromHeader("en")); - assertThat(request.getHeaderAcceptLanguage()).hasToString("en"); - } - - /** Test of getHeaderUserAgent method, of class PiwikRequest. */ - @Test - void testHeaderUserAgent() { - request.setHeaderUserAgent("agent"); - assertThat(request.getHeaderUserAgent()).isEqualTo("agent"); - } - - /** Test of getNewVisit method, of class PiwikRequest. */ - @Test - void testNewVisit() { - request.setNewVisit(true); - assertThat(request.getNewVisit()).isTrue(); - request.setNewVisit(null); - assertThat(request.getNewVisit()).isNull(); - } - - /** Test of getOutlinkUrl method, of class PiwikRequest. */ - @Test - void testOutlinkUrl() { - request.setOutlinkUrl("https://outlink.com"); - assertThat(request.getOutlinkUrl()).isEqualTo("https://outlink.com"); - } - - /** Test of getPageCustomVariable method, of class PiwikRequest. */ - @Test - void testPageCustomVariableStringStringE() { - assertThatThrownBy(() -> request.setPageCustomVariable(null, null)); - } - - @Test - void testPageCustomVariableStringStringE2() { - assertThatThrownBy(() -> request.setPageCustomVariable(null, "pageVal")); - } - - @Test - void testPageCustomVariableCustomVariable() { - assertThat(request.getPageCustomVariable(1)).isNull(); - CustomVariable cv = new CustomVariable("pageKey", "pageVal"); - request.setPageCustomVariable(cv, 1); - assertThat(request.getPageCustomVariable(1)).isEqualTo(cv); - request.setPageCustomVariable(null, 1); - assertThat(request.getPageCustomVariable(1)).isNull(); - request.setPageCustomVariable(cv, 2); - assertThat(request.getPageCustomVariable(2)).isEqualTo(cv); - } - - /** Test of getPluginDirector method, of class PiwikRequest. */ - @Test - void testPluginDirector() { - request.setPluginDirector(true); - assertThat(request.getPluginDirector()).isTrue(); - } - - /** Test of getPluginFlash method, of class PiwikRequest. */ - @Test - void testPluginFlash() { - request.setPluginFlash(true); - assertThat(request.getPluginFlash()).isTrue(); - } - - /** Test of getPluginGears method, of class PiwikRequest. */ - @Test - void testPluginGears() { - request.setPluginGears(true); - assertThat(request.getPluginGears()).isTrue(); - } - - /** Test of getPluginJava method, of class PiwikRequest. */ - @Test - void testPluginJava() { - request.setPluginJava(true); - assertThat(request.getPluginJava()).isTrue(); - } - - /** Test of getPluginPDF method, of class PiwikRequest. */ - @Test - void testPluginPDF() { - request.setPluginPDF(true); - assertThat(request.getPluginPDF()).isTrue(); - } - - /** Test of getPluginQuicktime method, of class PiwikRequest. */ - @Test - void testPluginQuicktime() { - request.setPluginQuicktime(true); - assertThat(request.getPluginQuicktime()).isTrue(); - } - - /** Test of getPluginRealPlayer method, of class PiwikRequest. */ - @Test - void testPluginRealPlayer() { - request.setPluginRealPlayer(true); - assertThat(request.getPluginRealPlayer()).isTrue(); - } - - /** Test of getPluginSilverlight method, of class PiwikRequest. */ - @Test - void testPluginSilverlight() { - request.setPluginSilverlight(true); - assertThat(request.getPluginSilverlight()).isTrue(); - } - - /** Test of getPluginWindowsMedia method, of class PiwikRequest. */ - @Test - void testPluginWindowsMedia() { - request.setPluginWindowsMedia(true); - assertThat(request.getPluginWindowsMedia()).isTrue(); - } - - /** Test of getRandomValue method, of class PiwikRequest. */ - @Test - void testRandomValue() { - request.setRandomValue(RandomValue.fromString("value")); - assertThat(request.getRandomValue()).hasToString("value"); - } - - /** Test of setReferrerUrl method, of class PiwikRequest. */ - @Test - void testReferrerUrl() { - request.setReferrerUrl("https://referrer.com"); - assertThat(request.getReferrerUrl()).isEqualTo("https://referrer.com"); - } - - /** Test of getRequestDatetime method, of class PiwikRequest. */ - @Test - void testRequestDatetimeTTT() { - request.setAuthToken("12345678901234567890123456789012"); - PiwikDate date = new PiwikDate(1000L); - request.setRequestDatetime(date); - assertThat(request.getRequestDatetime().getTime()).isEqualTo(1000L); - } - - @Test - void testRequestDatetimeTF() { - request.setRequestDatetime(new PiwikDate()); - assertThat(request.getRequestDatetime().getZonedDateTime()) - .isCloseTo(ZonedDateTime.now(), within(2, MINUTES)); - } - - @Test - void testRequestDatetimeF() { - PiwikDate date = new PiwikDate(); - request.setRequestDatetime(date); - request.setRequestDatetime(null); - assertThat(request.getRequestDatetime()).isNull(); - } - - /** Test of getRequired method, of class PiwikRequest. */ - @Test - void testRequired() { - request.setRequired(false); - assertThat(request.getRequired()).isFalse(); - } - - /** Test of getResponseAsImage method, of class PiwikRequest. */ - @Test - void testResponseAsImage() { - request.setResponseAsImage(true); - assertThat(request.getResponseAsImage()).isTrue(); - } - - @Test - void testSearchCategoryTF() { - request.setSearchQuery("query"); - request.setSearchCategory("category"); - assertThat(request.getSearchCategory()).isEqualTo("category"); - } - - @Test - void testSearchCategoryF() { - request.setSearchCategory(null); - assertThat(request.getSearchCategory()).isNull(); - } - - /** Test of getSearchQuery method, of class PiwikRequest. */ - @Test - void testSearchQuery() { - request.setSearchQuery("query"); - assertThat(request.getSearchQuery()).isEqualTo("query"); - } - - @Test - void testSearchResultsCountTF() { - request.setSearchQuery("query"); - request.setSearchResultsCount(100L); - assertThat(request.getSearchResultsCount()).isEqualTo(Long.valueOf(100L)); - } - - @Test - void testSearchResultsCountF() { - request.setSearchResultsCount(null); - assertThat(request.getSearchResultsCount()).isNull(); - } - - /** Test of getSiteId method, of class PiwikRequest. */ - @Test - void testSiteId() { - request.setSiteId(2); - assertThat(request.getSiteId()).isEqualTo(Integer.valueOf(2)); - } - - /** Test of setTrackBotRequest method, of class PiwikRequest. */ - @Test - void testTrackBotRequests() { - request.setTrackBotRequests(true); - assertThat(request.getTrackBotRequests()).isTrue(); - } - - /** Test of getUserCustomVariable method, of class PiwikRequest. */ - @Test - void testUserCustomVariableStringString() { - request.setUserCustomVariable("userKey", "userValue"); - assertThat(request.getUserCustomVariable("userKey")).isEqualTo("userValue"); - } - - /** Test of getUserId method, of class PiwikRequest. */ - @Test - void testUserId() { - request.setUserId("id"); - assertThat(request.getUserId()).isEqualTo("id"); - } - - /** Test of getVisitorCity method, of class PiwikRequest. */ - @Test - void testVisitorCityT() { - request.setAuthToken("12345678901234567890123456789012"); - request.setVisitorCity("city"); - assertThat(request.getVisitorCity()).isEqualTo("city"); - } - - @Test - void testVisitorCityF() { - request.setVisitorCity(null); - assertThat(request.getVisitorCity()).isNull(); - } - - /** Test of getVisitorCountry method, of class PiwikRequest. */ - @Test - void testVisitorCountryT() { - PiwikLocale country = new PiwikLocale(Locale.US); - request.setAuthToken("12345678901234567890123456789012"); - request.setVisitorCountry(country); - assertThat(request.getVisitorCountry()).isEqualTo(country); - } - - @Test - void testVisitorCountryF() { - request.setVisitorCountry(null); - assertThat(request.getVisitorCountry()).isNull(); - } - - @Test - void testVisitorCustomTF() { - request.setVisitorCustomId(VisitorId.fromHex("1234567890abcdef")); - assertThat(request.getVisitorCustomId()).hasToString("1234567890abcdef"); - } - - @Test - void testVisitorCustomIdF() { - request.setVisitorCustomId(VisitorId.fromHex("1234567890abcdef")); - request.setVisitorCustomId(null); - assertThat(request.getVisitorCustomId()).isNull(); - } - - /** Test of getVisitorFirstVisitTimestamp method, of class PiwikRequest. */ - @Test - void testVisitorFirstVisitTimestamp() { - request.setVisitorFirstVisitTimestamp(Instant.parse("2021-03-10T10:22:22.123Z")); - assertThat(request.getVisitorFirstVisitTimestamp()).isEqualTo("2021-03-10T10:22:22.123Z"); - } - - @Test - void testVisitorIdTFT() { - try { - request.setVisitorId(VisitorId.fromHex("1234567890abcdeg")); - fail("Exception should have been thrown."); - } catch (IllegalArgumentException e) { - assertThat(e.getLocalizedMessage()).isEqualTo("Input must be a valid hex string"); - } - } - - @Test - void testVisitorIdTFF() { - request.setVisitorId(VisitorId.fromHex("1234567890abcdef")); - assertThat(request.getVisitorId()).hasToString("1234567890abcdef"); - } - - @Test - void testVisitorIdF() { - request.setVisitorId(VisitorId.fromHex("1234567890abcdef")); - request.setVisitorId(null); - assertThat(request.getVisitorId()).isNull(); - } - - /** Test of getVisitorIp method, of class PiwikRequest. */ - @Test - void testVisitorIpT() { - request.setAuthToken("12345678901234567890123456789012"); - request.setVisitorIp("ip"); - assertThat(request.getVisitorIp()).isEqualTo("ip"); - } - - @Test - void testVisitorIpF() { - request.setVisitorIp(null); - assertThat(request.getVisitorIp()).isNull(); - } - - /** Test of getVisitorLatitude method, of class PiwikRequest. */ - @Test - void testVisitorLatitudeT() { - request.setAuthToken("12345678901234567890123456789012"); - request.setVisitorLatitude(10.5); - assertThat(request.getVisitorLatitude()).isEqualTo(Double.valueOf(10.5)); - } - - @Test - void testVisitorLatitudeF() { - request.setVisitorLatitude(null); - assertThat(request.getVisitorLatitude()).isNull(); - } - - /** Test of getVisitorLongitude method, of class PiwikRequest. */ - @Test - void testVisitorLongitudeT() { - request.setAuthToken("12345678901234567890123456789012"); - request.setVisitorLongitude(20.5); - assertThat(request.getVisitorLongitude()).isEqualTo(Double.valueOf(20.5)); - } - - @Test - void testVisitorLongitudeF() { - request.setVisitorLongitude(null); - assertThat(request.getVisitorLongitude()).isNull(); - } - - /** Test of getVisitorPreviousVisitTimestamp method, of class PiwikRequest. */ - @Test - void testVisitorPreviousVisitTimestamp() { - request.setVisitorPreviousVisitTimestamp(Instant.ofEpochSecond(1000L)); - assertThat(request.getVisitorPreviousVisitTimestamp()).isEqualTo("1970-01-01T00:16:40Z"); - } - - /** Test of getVisitorRegion method, of class PiwikRequest. */ - @Test - void testVisitorRegionT() { - request.setAuthToken("12345678901234567890123456789012"); - request.setVisitorRegion("region"); - assertThat(request.getVisitorRegion()).isEqualTo("region"); - } - - @Test - void testVisitorRegionF() { - request.setVisitorRegion(null); - assertThat(request.getVisitorRegion()).isNull(); - } - - /** Test of getVisitorVisitCount method, of class PiwikRequest. */ - @Test - void testVisitorVisitCount() { - request.setVisitorVisitCount(100); - assertThat(request.getVisitorVisitCount()).isEqualTo(Integer.valueOf(100)); - } - - @Test - void failsIfActionUrlIsNull() { - assertThatThrownBy(() -> new PiwikRequest(3, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("Action URL must not be null"); - } -} diff --git a/core/src/test/java/org/matomo/java/tracking/QueryCreatorTest.java b/core/src/test/java/org/matomo/java/tracking/QueryCreatorTest.java index 0d5a18b5..1bcac9eb 100644 --- a/core/src/test/java/org/matomo/java/tracking/QueryCreatorTest.java +++ b/core/src/test/java/org/matomo/java/tracking/QueryCreatorTest.java @@ -56,7 +56,7 @@ private void whenCreatesQuery() { .defaultSiteId(42) .defaultAuthToken(defaultAuthToken) .build(); - String authToken = AuthToken.determineAuthToken(null, singleton(request), trackerConfiguration); + String authToken = AuthToken.determineAuthToken(singleton(request), trackerConfiguration); query = new QueryCreator(trackerConfiguration).createQuery(request, authToken); } @@ -362,14 +362,12 @@ void testVisitCustomVariableCustomVariable() { .randomValue(RandomValue.fromString("random")) .visitorId(VisitorId.fromHex("1234567890123456")) .siteId(3); - org.matomo.java.tracking.CustomVariable cv = - new org.matomo.java.tracking.CustomVariable("visitKey", "visitVal"); + CustomVariable cv = new CustomVariable("visitKey", "visitVal"); matomoRequestBuilder.visitCustomVariables(new CustomVariables().add(cv, 8)); defaultAuthToken = null; whenCreatesQuery(); - assertThat(request.getVisitCustomVariable(1)).isNull(); assertThat(query) .isEqualTo( "rec=1&idsite=3&apiv=1&_id=1234567890123456&_cvar=%7B%228%22%3A%5B%22visitKey%22%2C%22visitVal%22%5D%7D&send_image=0&rand=random"); diff --git a/core/src/test/java/org/matomo/java/tracking/RequestValidatorTest.java b/core/src/test/java/org/matomo/java/tracking/RequestValidatorTest.java index d223f688..e5b09177 100644 --- a/core/src/test/java/org/matomo/java/tracking/RequestValidatorTest.java +++ b/core/src/test/java/org/matomo/java/tracking/RequestValidatorTest.java @@ -1,11 +1,12 @@ package org.matomo.java.tracking; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import java.util.Locale; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import org.junit.jupiter.api.Test; -import org.piwik.java.tracking.PiwikDate; -import org.piwik.java.tracking.PiwikLocale; +import org.matomo.java.tracking.parameters.Country; class RequestValidatorTest { @@ -66,9 +67,8 @@ void testVisitorRegion() { } @Test - void testVisitorCountryTE() { - PiwikLocale country = new PiwikLocale(Locale.US); - request.setVisitorCountry(country); + void testVisitorCountry() { + request.setVisitorCountry(Country.fromCode("us")); assertThatThrownBy(() -> RequestValidator.validate(request, null)) .isInstanceOf(MatomoException.class) @@ -78,16 +78,38 @@ void testVisitorCountryTE() { } @Test - void testRequestDatetime() { + void testVisitorIp() { + request.setVisitorIp("192.168.0.1"); - PiwikDate date = new PiwikDate(1000L); - request.setRequestDatetime(date); + assertThatThrownBy(() -> RequestValidator.validate(request, null)) + .isInstanceOf(MatomoException.class) + .hasMessage( + "Auth token must be present if visitor longitude, latitude, region, city, country or IP" + + " are set"); + } + + @Test + void testRequestTimestampOlderThanFourHours() { + request.setRequestTimestamp(Instant.now().minus(5, ChronoUnit.HOURS)); assertThatThrownBy(() -> RequestValidator.validate(request, null)) .isInstanceOf(MatomoException.class) .hasMessage("Auth token must be present if request timestamp is more than four hours ago"); } + @Test + void doesNotFailIfRequestTimestampIsWithinFourHours() { + request.setRequestTimestamp(Instant.now().minus(1, ChronoUnit.HOURS)); + + assertThatCode(() -> RequestValidator.validate(request, null)).doesNotThrowAnyException(); + } + + @Test + void doesNotFailWithValid32CharAuthToken() { + assertThatCode(() -> RequestValidator.validate(request, "12345678901234567890123456789012")) + .doesNotThrowAnyException(); + } + @Test void failsIfAuthTokenIsNot32CharactersLong() { assertThatThrownBy(() -> RequestValidator.validate(request, "123456789012345678901234567890")) diff --git a/core/src/test/java/org/matomo/java/tracking/TestSender.java b/core/src/test/java/org/matomo/java/tracking/TestSender.java index 30f0395c..0cbc0729 100644 --- a/core/src/test/java/org/matomo/java/tracking/TestSender.java +++ b/core/src/test/java/org/matomo/java/tracking/TestSender.java @@ -3,7 +3,6 @@ import static java.util.Collections.singleton; import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.CompletableFuture; @@ -32,37 +31,34 @@ class TestSender implements Sender { @NonNull @Override public CompletableFuture sendSingleAsync(@NonNull MatomoRequest request) { - createQueryAndAddRequest(request, null); + createQueryAndAddRequest(request); return CompletableFuture.completedFuture(request); } @Override public void sendSingle(@NonNull MatomoRequest request) { - createQueryAndAddRequest(request, null); + createQueryAndAddRequest(request); } @Override - public void sendBulk( - @NonNull Iterable requests, @Nullable String overrideAuthToken) { + public void sendBulk(@NonNull Iterable requests) { for (MatomoRequest request : requests) { - createQueryAndAddRequest(request, overrideAuthToken); + createQueryAndAddRequest(request); } } @NonNull @Override public CompletableFuture sendBulkAsync( - @NonNull Collection requests, @Nullable String overrideAuthToken) { + @NonNull Collection requests) { for (MatomoRequest request : requests) { - createQueryAndAddRequest(request, overrideAuthToken); + createQueryAndAddRequest(request); } return CompletableFuture.completedFuture(null); } - private void createQueryAndAddRequest( - @lombok.NonNull MatomoRequest request, @Nullable String overrideAuthToken) { - String authToken = - AuthToken.determineAuthToken(overrideAuthToken, singleton(request), trackerConfiguration); + private void createQueryAndAddRequest(@lombok.NonNull MatomoRequest request) { + String authToken = AuthToken.determineAuthToken(singleton(request), trackerConfiguration); queries.add(queryCreator.createQuery(request, authToken)); requests.add(request); } diff --git a/core/src/test/java/org/matomo/java/tracking/parameters/CountryTest.java b/core/src/test/java/org/matomo/java/tracking/parameters/CountryTest.java index 03c6f1d4..2a5148e2 100644 --- a/core/src/test/java/org/matomo/java/tracking/parameters/CountryTest.java +++ b/core/src/test/java/org/matomo/java/tracking/parameters/CountryTest.java @@ -10,7 +10,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import java.util.Locale; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.NullAndEmptySource; @@ -105,38 +104,4 @@ void failsOnInvalidRanges() { .isInstanceOf(IllegalArgumentException.class) .hasMessage("Invalid country code"); } - - @Test - void failsOnLocaleWithoutCountryCode() { - - assertThatThrownBy(() -> new Country(Locale.forLanguageTag("de"))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Invalid locale"); - } - - @Test - void setLocaleFailsOnNullLocale() { - - assertThatThrownBy(() -> new Country(Locale.forLanguageTag("de")).setLocale(null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Invalid locale"); - } - - @Test - void setLocaleFailsOnNullCountryCode() { - - assertThatThrownBy( - () -> new Country(Locale.forLanguageTag("de")).setLocale(Locale.forLanguageTag("de"))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Invalid locale"); - } - - @Test - void setLocaleFailsOnEmptyCountryCode() { - - assertThatThrownBy( - () -> new Country(Locale.forLanguageTag("de")).setLocale(Locale.forLanguageTag("de"))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Invalid locale"); - } } diff --git a/core/src/test/java/org/matomo/java/tracking/parameters/CustomVariableTest.java b/core/src/test/java/org/matomo/java/tracking/parameters/CustomVariableTest.java index 26af6402..762c6c8e 100644 --- a/core/src/test/java/org/matomo/java/tracking/parameters/CustomVariableTest.java +++ b/core/src/test/java/org/matomo/java/tracking/parameters/CustomVariableTest.java @@ -8,6 +8,7 @@ package org.matomo.java.tracking.parameters; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import org.junit.jupiter.api.BeforeEach; @@ -65,4 +66,30 @@ void equalsCustomVariable() { assertThat(variableA).isNotEqualTo(d); assertThat(variableA.hashCode()).isNotEqualTo(d.hashCode()); } + + @Test + void createsCustomVariable() { + CustomVariable customVariable = new CustomVariable("key", "value"); + + assertThat(customVariable.getKey()).isEqualTo("key"); + assertThat(customVariable.getValue()).isEqualTo("value"); + } + + @Test + void failsOnNullKey() { + assertThatThrownBy(() -> new CustomVariable(null, "value")) + .isInstanceOf(NullPointerException.class); + } + + @Test + void failsOnNullValue() { + assertThatThrownBy(() -> new CustomVariable("key", null)) + .isInstanceOf(NullPointerException.class); + } + + @Test + void failsOnNullKeyAndValue() { + assertThatThrownBy(() -> new CustomVariable(null, null)) + .isInstanceOf(NullPointerException.class); + } } diff --git a/core/src/test/java/org/matomo/java/tracking/parameters/DeviceResolutionTest.java b/core/src/test/java/org/matomo/java/tracking/parameters/DeviceResolutionTest.java index 84254126..e708b6be 100644 --- a/core/src/test/java/org/matomo/java/tracking/parameters/DeviceResolutionTest.java +++ b/core/src/test/java/org/matomo/java/tracking/parameters/DeviceResolutionTest.java @@ -22,6 +22,14 @@ void formatsDeviceResolution() { assertThat(deviceResolution).hasToString("1280x1080"); } + @Test + void formatsDeviceResolutionFromString() { + + DeviceResolution deviceResolution = DeviceResolution.fromString("1280x1080"); + + assertThat(deviceResolution).hasToString("1280x1080"); + } + @Test void returnsNullOnNull() { diff --git a/core/src/test/java/org/matomo/java/tracking/EcommerceItemTest.java b/core/src/test/java/org/matomo/java/tracking/parameters/EcommerceItemTest.java similarity index 97% rename from core/src/test/java/org/matomo/java/tracking/EcommerceItemTest.java rename to core/src/test/java/org/matomo/java/tracking/parameters/EcommerceItemTest.java index b2d5ac8e..45d8d319 100644 --- a/core/src/test/java/org/matomo/java/tracking/EcommerceItemTest.java +++ b/core/src/test/java/org/matomo/java/tracking/parameters/EcommerceItemTest.java @@ -1,4 +1,4 @@ -package org.matomo.java.tracking; +package org.matomo.java.tracking.parameters; import static org.assertj.core.api.Assertions.assertThat; diff --git a/core/src/test/java/org/matomo/java/tracking/parameters/RandomValueTest.java b/core/src/test/java/org/matomo/java/tracking/parameters/RandomValueTest.java new file mode 100644 index 00000000..e533c95e --- /dev/null +++ b/core/src/test/java/org/matomo/java/tracking/parameters/RandomValueTest.java @@ -0,0 +1,25 @@ +package org.matomo.java.tracking.parameters; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; + +class RandomValueTest { + + @Test + void createsRandomValueWith20HexChars() { + + RandomValue random = RandomValue.random(); + + assertThat(random.toString()).matches("[0-9a-f]{20}"); + } + + @Test + void createsRandomValue() { + + RandomValue random1 = RandomValue.random(); + RandomValue random2 = RandomValue.random(); + + assertThat(random1.toString()).isNotEqualTo(random2.toString()); + } +} diff --git a/core/src/test/java/org/matomo/java/tracking/parameters/VisitorIdTest.java b/core/src/test/java/org/matomo/java/tracking/parameters/VisitorIdTest.java index 36a6c16a..592a1933 100644 --- a/core/src/test/java/org/matomo/java/tracking/parameters/VisitorIdTest.java +++ b/core/src/test/java/org/matomo/java/tracking/parameters/VisitorIdTest.java @@ -179,4 +179,20 @@ void createsVisitorIdFromString() { assertThat(visitorId).hasToString("0000000000364492"); } + + @Test + void fromStringReturnsNullForNull() { + + VisitorId visitorId = VisitorId.fromString(null); + + assertThat(visitorId).isNull(); + } + + @Test + void fromStringReturnsNullForEmpty() { + + VisitorId visitorId = VisitorId.fromString(""); + + assertThat(visitorId).isNull(); + } } diff --git a/core/src/test/java/org/piwik/java/tracking/CustomVariableTest.java b/core/src/test/java/org/piwik/java/tracking/CustomVariableTest.java deleted file mode 100644 index 9b1c4387..00000000 --- a/core/src/test/java/org/piwik/java/tracking/CustomVariableTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.piwik.java.tracking; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.Test; - -class CustomVariableTest { - - @Test - void createsCustomVariable() { - CustomVariable customVariable = new CustomVariable("key", "value"); - - assertThat(customVariable.getKey()).isEqualTo("key"); - assertThat(customVariable.getValue()).isEqualTo("value"); - } -} diff --git a/core/src/test/java/org/piwik/java/tracking/EcommerceItemTest.java b/core/src/test/java/org/piwik/java/tracking/EcommerceItemTest.java deleted file mode 100644 index 78a311f5..00000000 --- a/core/src/test/java/org/piwik/java/tracking/EcommerceItemTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.piwik.java.tracking; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.Test; - -class EcommerceItemTest { - - @Test - void createsEcItem() { - EcommerceItem item = new EcommerceItem("sku", "name", "category", 1.0, 1); - - assertThat(item.getSku()).isEqualTo("sku"); - assertThat(item.getName()).isEqualTo("name"); - assertThat(item.getCategory()).isEqualTo("category"); - assertThat(item.getPrice()).isEqualTo(1.0); - assertThat(item.getQuantity()).isEqualTo(1); - } -} diff --git a/core/src/test/java/org/piwik/java/tracking/PiwikTrackerIT.java b/core/src/test/java/org/piwik/java/tracking/PiwikTrackerIT.java deleted file mode 100644 index 00282d38..00000000 --- a/core/src/test/java/org/piwik/java/tracking/PiwikTrackerIT.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.piwik.java.tracking; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.Test; - -class PiwikTrackerIT { - - private PiwikTracker piwikTracker; - - @Test - void createsNewPiwikTrackerInstanceWithHostUrl() { - - piwikTracker = new PiwikTracker("http://localhost:8080"); - - assertThat(piwikTracker).isNotNull(); - } - - @Test - void createsNewPiwikTrackerInstanceWithHostUrlAndTimeout() { - - piwikTracker = new PiwikTracker("http://localhost:8080", 1000); - - assertThat(piwikTracker).isNotNull(); - } - - @Test - void createsNewPiwikTrackerInstanceWithHostUrlAndProxySettings() { - - piwikTracker = new PiwikTracker("http://localhost:8080", "localhost", 8080); - - assertThat(piwikTracker).isNotNull(); - } - - @Test - void createsNewPiwikTrackerInstanceWithHostUrlAndProxySettingsAndTimeout() { - - piwikTracker = new PiwikTracker("http://localhost:8080", "localhost", 8080, 1000); - - assertThat(piwikTracker).isNotNull(); - } -} diff --git a/java11/pom.xml b/java11/pom.xml index ae7d829c..d44014c0 100644 --- a/java11/pom.xml +++ b/java11/pom.xml @@ -3,14 +3,14 @@ 4.0.0 - org.piwik.java.tracking + org.matomo.java matomo-java-tracker-parent - 3.5.0-SNAPSHOT + 4.0.0-SNAPSHOT ../pom.xml matomo-java-tracker-java11 - 3.5.0-SNAPSHOT + 4.0.0-SNAPSHOT jar Matomo Java Tracker Java 11 @@ -23,7 +23,7 @@ - org.piwik.java.tracking + org.matomo.java matomo-java-tracker-core ${project.version} diff --git a/java11/src/main/java/org/matomo/java/tracking/Java11Sender.java b/java11/src/main/java/org/matomo/java/tracking/Java11Sender.java index 057c434b..9fd1e7b1 100644 --- a/java11/src/main/java/org/matomo/java/tracking/Java11Sender.java +++ b/java11/src/main/java/org/matomo/java/tracking/Java11Sender.java @@ -56,17 +56,13 @@ private void sendAndCheckResponse(@NonNull HttpRequest httpRequest) { } @Override - public void sendBulk( - @NonNull @lombok.NonNull Iterable requests, - @Nullable String overrideAuthToken) { - sendAndCheckResponse(buildHttpPostRequest(requests, overrideAuthToken)); + public void sendBulk(@NonNull @lombok.NonNull Iterable requests) { + sendAndCheckResponse(buildHttpPostRequest(requests)); } @NonNull - private HttpRequest buildHttpPostRequest( - @NonNull Iterable requests, @Nullable String overrideAuthToken) { - String authToken = - AuthToken.determineAuthToken(overrideAuthToken, requests, trackerConfiguration); + private HttpRequest buildHttpPostRequest(@NonNull Iterable requests) { + String authToken = AuthToken.determineAuthToken(requests, trackerConfiguration); Collection queries = new ArrayList<>(); Map headers = new LinkedHashMap<>(10); String headerUserAgent = null; @@ -99,9 +95,8 @@ private HttpRequest buildHttpPostRequest( @NonNull @Override public CompletableFuture sendBulkAsync( - @NonNull @lombok.NonNull Collection requests, - @Nullable String overrideAuthToken) { - return sendAsyncAndCheckResponse(buildHttpPostRequest(requests, overrideAuthToken), null); + @NonNull @lombok.NonNull Collection requests) { + return sendAsyncAndCheckResponse(buildHttpPostRequest(requests), null); } @NonNull @@ -121,7 +116,7 @@ private CompletableFuture sendAsyncAndCheckResponse( @NonNull private HttpRequest buildHttpGetRequest(@NonNull MatomoRequest request) { - String authToken = AuthToken.determineAuthToken(null, singleton(request), trackerConfiguration); + String authToken = AuthToken.determineAuthToken(singleton(request), trackerConfiguration); RequestValidator.validate(request, authToken); cookieStore.removeAll(); addCookies(request); diff --git a/java11/src/test/java/org/matomo/java/tracking/Java11SenderIT.java b/java11/src/test/java/org/matomo/java/tracking/Java11SenderIT.java index 18b86791..89c9da3c 100644 --- a/java11/src/test/java/org/matomo/java/tracking/Java11SenderIT.java +++ b/java11/src/test/java/org/matomo/java/tracking/Java11SenderIT.java @@ -295,8 +295,7 @@ void addsHeadersToBulkRequest(WireMockRuntimeInfo wireMockRuntimeInfo) { List.of( MatomoRequests.goal(1, 23.50) .headers(singletonMap("headerName", "headerValue")) - .build()), - null); + .build())); verify( postRequestedFor(urlPathEqualTo("/matomo.php")) @@ -313,7 +312,7 @@ void doesNotAddEmptyHeaders(WireMockRuntimeInfo wireMockRuntimeInfo) { givenSender(); - sender.sendBulk(List.of(MatomoRequests.pageView("Contact").headers(emptyMap()).build()), null); + sender.sendBulk(List.of(MatomoRequests.pageView("Contact").headers(emptyMap()).build())); verify(postRequestedFor(urlPathEqualTo("/matomo.php")).withoutHeader("headerName")); } @@ -331,8 +330,9 @@ void addsHeadersToBulkAsyncRequest(WireMockRuntimeInfo wireMockRuntimeInfo) { CompletableFuture future = sender.sendBulkAsync( List.of( - MatomoRequest.request().headers(singletonMap("headerName", "headerValue")).build()), - null); + MatomoRequest.request() + .headers(singletonMap("headerName", "headerValue")) + .build())); future.join(); verify( @@ -371,7 +371,7 @@ void failsOnSendBulkAsyncIfRequestsIsNull() { givenSender(); - assertThatThrownBy(() -> sender.sendBulkAsync(null, null)) + assertThatThrownBy(() -> sender.sendBulkAsync(null)) .isInstanceOf(NullPointerException.class) .hasMessage("requests is marked non-null but is null"); } @@ -383,24 +383,8 @@ void failsOnSendBulkAsyncIfRequestIsNull() { givenSender(); - assertThatThrownBy(() -> sender.sendBulk(null, null)) + assertThatThrownBy(() -> sender.sendBulk(null)) .isInstanceOf(NullPointerException.class) .hasMessage("requests is marked non-null but is null"); } - - @Test - void failsOnSendBulkAsyncIfOverrideAuthTokenIsMalformed() { - trackerConfiguration = - TrackerConfiguration.builder().apiEndpoint(URI.create("http://localhost:1234")).build(); - - givenSender(); - - assertThatThrownBy( - () -> - sender.sendBulkAsync( - List.of(MatomoRequests.siteSearch("Special offers", "Products", 5L).build()), - "telnet://localhost")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Auth token must be exactly 32 characters long"); - } } diff --git a/java11/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java b/java11/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java index 08468144..48682b5c 100644 --- a/java11/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java +++ b/java11/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java @@ -510,12 +510,12 @@ void sendsRequestAsyncAndAcceptsCallback(WireMockRuntimeInfo wireMockRuntimeInfo matomoTracker = new MatomoTracker(trackerConfigurationBuilder.build()); AtomicBoolean success = new AtomicBoolean(); future = - matomoTracker.sendRequestAsync( - requestBuilder.build(), - request -> { - success.set(true); - return null; - }); + matomoTracker + .sendRequestAsync(requestBuilder.build()) + .thenAccept( + request -> { + success.set(true); + }); assertThat(future) .succeedsWithin(1, MINUTES) .satisfies( @@ -531,11 +531,9 @@ void sendsRequestsAsyncAndAcceptsCallback(WireMockRuntimeInfo wireMockRuntimeInf matomoTracker = new MatomoTracker(trackerConfigurationBuilder.build()); AtomicBoolean success = new AtomicBoolean(); future = - matomoTracker.sendBulkRequestAsync( - singleton(requestBuilder.build()), - v -> { - success.set(true); - }); + matomoTracker + .sendBulkRequestAsync(singleton(requestBuilder.build())) + .thenAccept(v -> success.set(true)); assertThat(future) .succeedsWithin(1, MINUTES) .satisfies( diff --git a/java11/src/test/java/org/matomo/java/tracking/PiwikTrackerIT.java b/java11/src/test/java/org/matomo/java/tracking/PiwikTrackerIT.java deleted file mode 100644 index f812714e..00000000 --- a/java11/src/test/java/org/matomo/java/tracking/PiwikTrackerIT.java +++ /dev/null @@ -1,252 +0,0 @@ -package org.matomo.java.tracking; - -import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; -import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; -import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; -import static com.github.tomakehurst.wiremock.client.WireMock.resetAllRequests; -import static com.github.tomakehurst.wiremock.client.WireMock.status; -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; -import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; -import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; -import static com.github.tomakehurst.wiremock.client.WireMock.verify; -import static java.util.concurrent.TimeUnit.MINUTES; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; -import com.github.tomakehurst.wiremock.junit5.WireMockTest; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.matomo.java.tracking.parameters.RandomValue; -import org.matomo.java.tracking.parameters.VisitorId; -import org.piwik.java.tracking.PiwikRequest; -import org.piwik.java.tracking.PiwikTracker; - -@WireMockTest -class PiwikTrackerIT { - - private static final int SITE_ID = 42; - - private PiwikTracker piwikTracker; - - private PiwikRequest request; - - @BeforeEach - void setUp(WireMockRuntimeInfo wireMockRuntimeInfo) throws MalformedURLException { - piwikTracker = new PiwikTracker(wireMockRuntimeInfo.getHttpBaseUrl() + "/matomo.php", -1); - resetAllRequests(); - stubFor(post(urlPathEqualTo("/matomo.php")).willReturn(status(204))); - stubFor(get(urlPathEqualTo("/matomo.php")).willReturn(status(204))); - request = new PiwikRequest(SITE_ID, new URL("https://test.local/test/path?id=123")); - request.setRandomValue(RandomValue.fromString("rand")); - request.setVisitorId(VisitorId.fromHash(999999999999999999L)); - } - - /** Test of sendRequest method, of class PiwikTracker. */ - @Test - void testSendRequest() { - request.setCustomTrackingParameter("parameterName", "parameterValue"); - - piwikTracker.sendRequest(request); - - verify( - getRequestedFor( - urlEqualTo( - "/matomo.php?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue")) - .withHeader("User-Agent", equalTo("MatomoJavaClient"))); - } - - /** Test of sendRequestAsync method, of class PiwikTracker. */ - @Test - void testSendRequestAsync() { - request.setCustomTrackingParameter("parameterName", "parameterValue"); - - CompletableFuture future = piwikTracker.sendRequestAsync(request); - - assertThat(future).isNotCompletedExceptionally(); - assertThat(future) - .succeedsWithin(1, MINUTES) - .satisfies( - v -> { - verify( - getRequestedFor( - urlEqualTo( - "/matomo.php?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue")) - .withHeader("User-Agent", equalTo("MatomoJavaClient"))); - }); - } - - /** Test of sendBulkRequest method, of class PiwikTracker. */ - @Test - void testSendBulkRequest_Iterable() { - List requests = Collections.singletonList(request); - request.setCustomTrackingParameter("parameterName", "parameterValue"); - - piwikTracker.sendBulkRequest(requests); - - verify( - postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("167")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody( - equalToJson( - "{ \"requests\" : [" - + " \"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"" - + " ]}"))); - } - - /** Test of sendBulkRequest method, of class PiwikTracker. */ - @Test - void testSendBulkRequest_Iterable_StringTT() { - List requests = Collections.singletonList(request); - request.setCustomTrackingParameter("parameterName", "parameterValue"); - - assertThatThrownBy(() -> piwikTracker.sendBulkRequest(requests, "1")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Auth token must be exactly 32 characters long"); - } - - @Test - void testSendBulkRequest_Iterable_StringFF() { - List requests = Collections.singletonList(request); - request.setCustomTrackingParameter("parameterName", "parameterValue"); - - piwikTracker.sendBulkRequest(requests, null); - - verify( - postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("167")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody( - equalToJson( - "{\"requests\":[\"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"]}"))); - } - - @Test - void testSendBulkRequest_Iterable_StringFT() { - List requests = Collections.singletonList(request); - request.setCustomTrackingParameter("parameterName", "parameterValue"); - - piwikTracker.sendBulkRequest(requests, "12345678901234567890123456789012"); - - verify( - postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("215")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody( - equalToJson( - "{\"requests\":[\"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"" - + " ],\"token_auth\":\"12345678901234567890123456789012\"}"))); - } - - /** Test of sendBulkRequestAsync method, of class PiwikTracker. */ - @Test - void testSendBulkRequestAsync_Iterable() { - List requests = Collections.singletonList(request); - request.setCustomTrackingParameter("parameterName", "parameterValue"); - - CompletableFuture future = piwikTracker.sendBulkRequestAsync(requests); - - assertThat(future) - .succeedsWithin(1, MINUTES) - .satisfies( - v -> { - verify( - postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("167")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody( - equalToJson( - "{\"requests\" : [" - + " \"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"" - + " ]}"))); - }); - } - - /** Test of sendBulkRequestAsync method, of class PiwikTracker. */ - @Test - void testSendBulkRequestAsync_Iterable_StringTT() { - - List requests = Collections.singletonList(request); - request.setCustomTrackingParameter("parameterName", "parameterValue"); - - assertThatThrownBy(() -> piwikTracker.sendBulkRequestAsync(requests, "1").get()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Auth token must be exactly 32 characters long"); - } - - @Test - void testSendBulkRequestAsync_Iterable_String() { - - List requests = Collections.singletonList(request); - request.setCustomTrackingParameter("parameterName", "parameterValue"); - - CompletableFuture future = - piwikTracker.sendBulkRequestAsync(requests, "12345678901234567890123456789012"); - - assertThat(future).isNotCompletedExceptionally(); - assertThat(future) - .succeedsWithin(1, MINUTES) - .satisfies( - v -> { - verify( - postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("215")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody( - equalToJson( - "{\"requests\":[" - + " \"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"],\"token_auth\":\"12345678901234567890123456789012\"}"))); - }); - } - - @Test - void createsPiwikTrackerWithHostUrl(WireMockRuntimeInfo wireMockRuntimeInfo) { - PiwikTracker piwikTracker = - new PiwikTracker(wireMockRuntimeInfo.getHttpBaseUrl() + "/matomo.php"); - - piwikTracker.sendRequest(request); - - verify( - getRequestedFor( - urlEqualTo( - "/matomo.php?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand")) - .withHeader("User-Agent", equalTo("MatomoJavaClient"))); - } - - @Test - void createPiwikTrackerWithHostUrlAndProxyHostAndPort(WireMockRuntimeInfo wireMockRuntimeInfo) { - PiwikTracker piwikTracker = - new PiwikTracker(wireMockRuntimeInfo.getHttpBaseUrl() + "/matomo.php", "localhost", 8080); - - assertThatThrownBy(() -> piwikTracker.sendRequest(request)).isInstanceOf(MatomoException.class); - } - - @Test - void createPiwikTrackerWithHostUrlAndProxyHostAndPortAndTimeout( - WireMockRuntimeInfo wireMockRuntimeInfo) { - PiwikTracker piwikTracker = - new PiwikTracker( - wireMockRuntimeInfo.getHttpBaseUrl() + "/matomo.php", "localhost", 8080, 1000); - - assertThatThrownBy(() -> piwikTracker.sendRequest(request)).isInstanceOf(MatomoException.class); - } -} diff --git a/java8/pom.xml b/java8/pom.xml index fba1ad81..72c43550 100644 --- a/java8/pom.xml +++ b/java8/pom.xml @@ -3,14 +3,14 @@ 4.0.0 - org.piwik.java.tracking + org.matomo.java matomo-java-tracker-parent - 3.5.0-SNAPSHOT + 4.0.0-SNAPSHOT ../pom.xml matomo-java-tracker - 3.5.0-SNAPSHOT + 4.0.0-SNAPSHOT jar Matomo Java Tracker Java 8 @@ -18,7 +18,7 @@ - org.piwik.java.tracking + org.matomo.java matomo-java-tracker-core ${project.version} diff --git a/java8/src/main/java/org/matomo/java/tracking/Java8Sender.java b/java8/src/main/java/org/matomo/java/tracking/Java8Sender.java index d0a4cc85..c398bc51 100644 --- a/java8/src/main/java/org/matomo/java/tracking/Java8Sender.java +++ b/java8/src/main/java/org/matomo/java/tracking/Java8Sender.java @@ -76,7 +76,7 @@ public CompletableFuture sendSingleAsync(@NonNull MatomoRequest r @Override public void sendSingle(@NonNull MatomoRequest request) { - String authToken = AuthToken.determineAuthToken(null, singleton(request), trackerConfiguration); + String authToken = AuthToken.determineAuthToken(singleton(request), trackerConfiguration); RequestValidator.validate(request, authToken); HttpURLConnection connection; URI apiEndpoint = trackerConfiguration.getApiEndpoint(); @@ -241,11 +241,8 @@ private void applySslConfiguration(@NonNull @lombok.NonNull HttpsURLConnection c } @Override - public void sendBulk( - @NonNull @lombok.NonNull Iterable requests, - @Nullable String overrideAuthToken) { - String authToken = - AuthToken.determineAuthToken(overrideAuthToken, requests, trackerConfiguration); + public void sendBulk(@NonNull @lombok.NonNull Iterable requests) { + String authToken = AuthToken.determineAuthToken(requests, trackerConfiguration); Collection queries = new ArrayList<>(); Map headers = new LinkedHashMap<>(); String headerUserAgent = null; @@ -331,9 +328,8 @@ private static void preparePostConnection(HttpURLConnection connection) { @Override @NonNull public CompletableFuture sendBulkAsync( - @NonNull Collection requests, @Nullable String overrideAuthToken) { - String authToken = - AuthToken.determineAuthToken(overrideAuthToken, requests, trackerConfiguration); + @NonNull Collection requests) { + String authToken = AuthToken.determineAuthToken(requests, trackerConfiguration); Map headers = new LinkedHashMap<>(); String headerUserAgent = findHeaderUserAgent(requests); String sessionId = findSessionId(requests); diff --git a/java8/src/test/java/org/matomo/java/tracking/Java8SenderIT.java b/java8/src/test/java/org/matomo/java/tracking/Java8SenderIT.java index 56bd3eb1..05d38a72 100644 --- a/java8/src/test/java/org/matomo/java/tracking/Java8SenderIT.java +++ b/java8/src/test/java/org/matomo/java/tracking/Java8SenderIT.java @@ -189,8 +189,7 @@ void addsHeadersToBulkRequest() { MatomoRequests.ecommerceCartUpdate(50.0) .goalId(0) .headers(singletonMap("headerName", "headerValue")) - .build()), - null); + .build())); wireMockServer.verify( postRequestedFor(urlPathEqualTo("/matomo.php")) @@ -213,8 +212,9 @@ void addsHeadersToBulkAsyncRequest() { CompletableFuture future = sender.sendBulkAsync( singleton( - MatomoRequest.request().headers(singletonMap("headerName", "headerValue")).build()), - null); + MatomoRequest.request() + .headers(singletonMap("headerName", "headerValue")) + .build())); future.join(); wireMockServer.verify( diff --git a/java8/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java b/java8/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java index 3cedbebe..32ebe804 100644 --- a/java8/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java +++ b/java8/src/test/java/org/matomo/java/tracking/MatomoTrackerIT.java @@ -51,7 +51,7 @@ class MatomoTrackerIT { TrackerConfiguration.builder(); private final MatomoRequestBuilder requestBuilder = - MatomoRequest.builder() + MatomoRequest.request() .visitorId(VisitorId.fromHex("bbccddeeff1122")) .randomValue(RandomValue.fromString("someRandom")); @@ -532,12 +532,12 @@ void sendsRequestAsyncAndAcceptsCallback() { matomoTracker = new MatomoTracker(trackerConfigurationBuilder.build()); AtomicBoolean success = new AtomicBoolean(); future = - matomoTracker.sendRequestAsync( - requestBuilder.build(), - request -> { - success.set(true); - return null; - }); + matomoTracker + .sendRequestAsync(requestBuilder.build()) + .thenAccept( + request -> { + success.set(true); + }); assertThat(future) .succeedsWithin(1, MINUTES) .satisfies( @@ -553,11 +553,12 @@ void sendsRequestsAsyncAndAcceptsCallback() { matomoTracker = new MatomoTracker(trackerConfigurationBuilder.build()); AtomicBoolean success = new AtomicBoolean(); future = - matomoTracker.sendBulkRequestAsync( - singleton(requestBuilder.build()), - v -> { - success.set(true); - }); + matomoTracker + .sendBulkRequestAsync(singleton(requestBuilder.build())) + .thenAccept( + v -> { + success.set(true); + }); assertThat(future) .succeedsWithin(1, MINUTES) .satisfies( diff --git a/java8/src/test/java/org/matomo/java/tracking/PiwikTrackerIT.java b/java8/src/test/java/org/matomo/java/tracking/PiwikTrackerIT.java deleted file mode 100644 index 02c27b45..00000000 --- a/java8/src/test/java/org/matomo/java/tracking/PiwikTrackerIT.java +++ /dev/null @@ -1,254 +0,0 @@ -package org.matomo.java.tracking; - -import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; -import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; -import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; -import static com.github.tomakehurst.wiremock.client.WireMock.status; -import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; -import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; -import static java.util.concurrent.TimeUnit.MINUTES; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import com.github.tomakehurst.wiremock.WireMockServer; -import com.github.tomakehurst.wiremock.core.WireMockConfiguration; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.matomo.java.tracking.parameters.RandomValue; -import org.matomo.java.tracking.parameters.VisitorId; -import org.piwik.java.tracking.PiwikRequest; -import org.piwik.java.tracking.PiwikTracker; - -class PiwikTrackerIT { - - private static final WireMockServer wireMockServer = - new WireMockServer(WireMockConfiguration.options().dynamicPort()); - - private static final int SITE_ID = 42; - - private PiwikTracker piwikTracker; - - private PiwikRequest request; - - @BeforeAll - static void beforeAll() { - wireMockServer.start(); - } - - @BeforeEach - void setUp() throws MalformedURLException { - piwikTracker = new PiwikTracker(wireMockServer.baseUrl() + "/matomo.php", -1); - wireMockServer.resetRequests(); - wireMockServer.stubFor(post(urlPathEqualTo("/matomo.php")).willReturn(status(204))); - wireMockServer.stubFor(get(urlPathEqualTo("/matomo.php")).willReturn(status(204))); - request = new PiwikRequest(SITE_ID, new URL("https://test.local/test/path?id=123")); - request.setRandomValue(RandomValue.fromString("rand")); - request.setVisitorId(VisitorId.fromHash(999999999999999999L)); - } - - /** Test of sendRequest method, of class PiwikTracker. */ - @Test - void testSendRequest() { - request.setCustomTrackingParameter("parameterName", "parameterValue"); - - piwikTracker.sendRequest(request); - - wireMockServer.verify( - getRequestedFor( - urlEqualTo( - "/matomo.php?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue")) - .withHeader("User-Agent", equalTo("MatomoJavaClient"))); - } - - /** Test of sendRequestAsync method, of class PiwikTracker. */ - @Test - void testSendRequestAsync() { - request.setCustomTrackingParameter("parameterName", "parameterValue"); - - CompletableFuture future = piwikTracker.sendRequestAsync(request); - - assertThat(future).isNotCompletedExceptionally(); - assertThat(future) - .succeedsWithin(1, MINUTES) - .satisfies( - v -> { - wireMockServer.verify( - getRequestedFor( - urlEqualTo( - "/matomo.php?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue")) - .withHeader("User-Agent", equalTo("MatomoJavaClient"))); - }); - } - - /** Test of sendBulkRequest method, of class PiwikTracker. */ - @Test - void testSendBulkRequest_Iterable() { - List requests = Collections.singletonList(request); - request.setCustomTrackingParameter("parameterName", "parameterValue"); - - piwikTracker.sendBulkRequest(requests); - - wireMockServer.verify( - postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("167")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody( - equalToJson( - "{ \"requests\" : [" - + " \"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"" - + " ]}"))); - } - - /** Test of sendBulkRequest method, of class PiwikTracker. */ - @Test - void testSendBulkRequest_Iterable_StringTT() { - List requests = Collections.singletonList(request); - request.setCustomTrackingParameter("parameterName", "parameterValue"); - - assertThatThrownBy(() -> piwikTracker.sendBulkRequest(requests, "1")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Auth token must be exactly 32 characters long"); - } - - @Test - void testSendBulkRequest_Iterable_StringFF() { - List requests = Collections.singletonList(request); - request.setCustomTrackingParameter("parameterName", "parameterValue"); - - piwikTracker.sendBulkRequest(requests, null); - - wireMockServer.verify( - postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("167")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody( - equalToJson( - "{\"requests\":[\"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"]}"))); - } - - @Test - void testSendBulkRequest_Iterable_StringFT() { - List requests = Collections.singletonList(request); - request.setCustomTrackingParameter("parameterName", "parameterValue"); - - piwikTracker.sendBulkRequest(requests, "12345678901234567890123456789012"); - - wireMockServer.verify( - postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("215")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody( - equalToJson( - "{\"requests\":[\"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"" - + " ],\"token_auth\":\"12345678901234567890123456789012\"}"))); - } - - /** Test of sendBulkRequestAsync method, of class PiwikTracker. */ - @Test - void testSendBulkRequestAsync_Iterable() { - List requests = Collections.singletonList(request); - request.setCustomTrackingParameter("parameterName", "parameterValue"); - - CompletableFuture future = piwikTracker.sendBulkRequestAsync(requests); - - assertThat(future) - .succeedsWithin(1, MINUTES) - .satisfies( - v -> { - wireMockServer.verify( - postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("167")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody( - equalToJson( - "{\"requests\" : [" - + " \"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"" - + " ]}"))); - }); - } - - /** Test of sendBulkRequestAsync method, of class PiwikTracker. */ - @Test - void testSendBulkRequestAsync_Iterable_StringTT() { - - List requests = Collections.singletonList(request); - request.setCustomTrackingParameter("parameterName", "parameterValue"); - - assertThatThrownBy(() -> piwikTracker.sendBulkRequestAsync(requests, "1").get()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Auth token must be exactly 32 characters long"); - } - - @Test - void testSendBulkRequestAsync_Iterable_String() { - - List requests = Collections.singletonList(request); - request.setCustomTrackingParameter("parameterName", "parameterValue"); - - CompletableFuture future = - piwikTracker.sendBulkRequestAsync(requests, "12345678901234567890123456789012"); - - assertThat(future).isNotCompletedExceptionally(); - assertThat(future) - .succeedsWithin(1, MINUTES) - .satisfies( - v -> { - wireMockServer.verify( - postRequestedFor(urlEqualTo("/matomo.php")) - .withHeader("Content-Length", equalTo("215")) - .withHeader("Accept", equalTo("*/*")) - .withHeader("Content-Type", equalTo("application/json")) - .withHeader("User-Agent", equalTo("MatomoJavaClient")) - .withRequestBody( - equalToJson( - "{\"requests\":[" - + " \"?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand¶meterName=parameterValue\"],\"token_auth\":\"12345678901234567890123456789012\"}"))); - }); - } - - @Test - void createsPiwikTrackerWithHostUrl() { - PiwikTracker piwikTracker = new PiwikTracker(wireMockServer.baseUrl() + "/matomo.php"); - - piwikTracker.sendRequest(request); - - wireMockServer.verify( - getRequestedFor( - urlEqualTo( - "/matomo.php?rec=1&idsite=42&url=https%3A%2F%2Ftest.local%2Ftest%2Fpath%3Fid%3D123&apiv=1&_id=0de0b6b3a763ffff&send_image=0&rand=rand")) - .withHeader("User-Agent", equalTo("MatomoJavaClient"))); - } - - @Test - void createPiwikTrackerWithHostUrlAndProxyHostAndPort() { - PiwikTracker piwikTracker = - new PiwikTracker(wireMockServer.baseUrl() + "/matomo.php", "localhost", 8080); - - assertThatThrownBy(() -> piwikTracker.sendRequest(request)).isInstanceOf(MatomoException.class); - } - - @Test - void createPiwikTrackerWithHostUrlAndProxyHostAndPortAndTimeout() { - PiwikTracker piwikTracker = - new PiwikTracker(wireMockServer.baseUrl() + "/matomo.php", "localhost", 8080, 1000); - - assertThatThrownBy(() -> piwikTracker.sendRequest(request)).isInstanceOf(MatomoException.class); - } -} diff --git a/pom.xml b/pom.xml index e85b4033..2c754c4a 100644 --- a/pom.xml +++ b/pom.xml @@ -2,9 +2,9 @@ 4.0.0 - org.piwik.java.tracking + org.matomo.java matomo-java-tracker-parent - 3.5.0-SNAPSHOT + 4.0.0-SNAPSHOT pom Matomo Java Tracker Parent diff --git a/servlet-jakarta/pom.xml b/servlet-jakarta/pom.xml index e4c38c81..fb366731 100644 --- a/servlet-jakarta/pom.xml +++ b/servlet-jakarta/pom.xml @@ -3,14 +3,14 @@ 4.0.0 - org.piwik.java.tracking + org.matomo.java matomo-java-tracker-parent - 3.5.0-SNAPSHOT + 4.0.0-SNAPSHOT ../pom.xml matomo-java-tracker-servlet-jakarta - 3.5.0-SNAPSHOT + 4.0.0-SNAPSHOT jar Matomo Java Tracker Servlet Jakarta @@ -23,7 +23,7 @@ - org.piwik.java.tracking + org.matomo.java matomo-java-tracker-java11 ${project.version} diff --git a/servlet-jakarta/src/test/java/org/matomo/java/tracking/TestSender.java b/servlet-jakarta/src/test/java/org/matomo/java/tracking/TestSender.java index 0f9404a3..0725a320 100644 --- a/servlet-jakarta/src/test/java/org/matomo/java/tracking/TestSender.java +++ b/servlet-jakarta/src/test/java/org/matomo/java/tracking/TestSender.java @@ -1,7 +1,6 @@ package org.matomo.java.tracking; import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.CompletableFuture; @@ -38,15 +37,14 @@ public void sendSingle(@NonNull MatomoRequest request) { } @Override - public void sendBulk( - @NonNull Iterable requests, @Nullable String overrideAuthToken) { + public void sendBulk(@NonNull Iterable requests) { throw new UnsupportedOperationException(); } @NonNull @Override public CompletableFuture sendBulkAsync( - @NonNull Collection requests, @Nullable String overrideAuthToken) { + @NonNull Collection requests) { throw new UnsupportedOperationException(); } diff --git a/servlet-javax/pom.xml b/servlet-javax/pom.xml index ade58c26..bbfcf81b 100644 --- a/servlet-javax/pom.xml +++ b/servlet-javax/pom.xml @@ -3,14 +3,14 @@ 4.0.0 - org.piwik.java.tracking + org.matomo.java matomo-java-tracker-parent - 3.5.0-SNAPSHOT + 4.0.0-SNAPSHOT ../pom.xml matomo-java-tracker-servlet-javax - 3.5.0-SNAPSHOT + 4.0.0-SNAPSHOT jar Matomo Java Tracker Servlet Javax @@ -23,7 +23,7 @@ - org.piwik.java.tracking + org.matomo.java matomo-java-tracker ${project.version} diff --git a/servlet-javax/src/test/java/org/matomo/java/tracking/TestSender.java b/servlet-javax/src/test/java/org/matomo/java/tracking/TestSender.java index 539d01ff..7fd51bb2 100644 --- a/servlet-javax/src/test/java/org/matomo/java/tracking/TestSender.java +++ b/servlet-javax/src/test/java/org/matomo/java/tracking/TestSender.java @@ -1,7 +1,6 @@ package org.matomo.java.tracking; import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.CompletableFuture; @@ -38,15 +37,14 @@ public void sendSingle(@NonNull MatomoRequest request) { } @Override - public void sendBulk( - @NonNull Iterable requests, @Nullable String overrideAuthToken) { + public void sendBulk(@NonNull Iterable requests) { throw new UnsupportedOperationException(); } @NonNull @Override public CompletableFuture sendBulkAsync( - @NonNull Collection requests, @Nullable String overrideAuthToken) { + @NonNull Collection requests) { throw new UnsupportedOperationException(); } diff --git a/spring/pom.xml b/spring/pom.xml index 93399ae3..5e1bf8ca 100644 --- a/spring/pom.xml +++ b/spring/pom.xml @@ -3,9 +3,9 @@ 4.0.0 - org.piwik.java.tracking + org.matomo.java matomo-java-tracker-parent - 3.5.0-SNAPSHOT + 4.0.0-SNAPSHOT ../pom.xml @@ -35,12 +35,12 @@ - org.piwik.java.tracking + org.matomo.java matomo-java-tracker-java11 ${project.version} - org.piwik.java.tracking + org.matomo.java matomo-java-tracker-servlet-jakarta ${project.version} diff --git a/test/pom.xml b/test/pom.xml index dfe914f2..83668095 100644 --- a/test/pom.xml +++ b/test/pom.xml @@ -3,9 +3,9 @@ 4.0.0 - org.piwik.java.tracking + org.matomo.java matomo-java-tracker-parent - 3.5.0-SNAPSHOT + 4.0.0-SNAPSHOT ../pom.xml @@ -21,12 +21,12 @@ - org.piwik.java.tracking + org.matomo.java matomo-java-tracker-java11 ${project.version} - org.piwik.java.tracking + org.matomo.java matomo-java-tracker-servlet-jakarta ${project.version} From 03812bc9ba1efa6deece94cf72690302aa9f80b6 Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Mon, 11 May 2026 10:47:13 +0200 Subject: [PATCH 63/71] Use org.piwik.java.tracking as group id --- core/pom.xml | 2 +- java11/pom.xml | 4 ++-- java8/pom.xml | 4 ++-- pom.xml | 2 +- servlet-jakarta/pom.xml | 4 ++-- servlet-javax/pom.xml | 4 ++-- spring/pom.xml | 6 +++--- test/pom.xml | 6 +++--- 8 files changed, 16 insertions(+), 16 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index 9507cb60..f9dd4074 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -3,7 +3,7 @@ 4.0.0 - org.matomo.java + org.piwik.java.tracking matomo-java-tracker-parent 4.0.0-SNAPSHOT ../pom.xml diff --git a/java11/pom.xml b/java11/pom.xml index d44014c0..e4254d66 100644 --- a/java11/pom.xml +++ b/java11/pom.xml @@ -3,7 +3,7 @@ 4.0.0 - org.matomo.java + org.piwik.java.tracking matomo-java-tracker-parent 4.0.0-SNAPSHOT ../pom.xml @@ -23,7 +23,7 @@ - org.matomo.java + org.piwik.java.tracking matomo-java-tracker-core ${project.version} diff --git a/java8/pom.xml b/java8/pom.xml index 72c43550..60b6fe0d 100644 --- a/java8/pom.xml +++ b/java8/pom.xml @@ -3,7 +3,7 @@ 4.0.0 - org.matomo.java + org.piwik.java.tracking matomo-java-tracker-parent 4.0.0-SNAPSHOT ../pom.xml @@ -18,7 +18,7 @@ - org.matomo.java + org.piwik.java.tracking matomo-java-tracker-core ${project.version} diff --git a/pom.xml b/pom.xml index 2c754c4a..42dd0f22 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 - org.matomo.java + org.piwik.java.tracking matomo-java-tracker-parent 4.0.0-SNAPSHOT pom diff --git a/servlet-jakarta/pom.xml b/servlet-jakarta/pom.xml index fb366731..569bacdf 100644 --- a/servlet-jakarta/pom.xml +++ b/servlet-jakarta/pom.xml @@ -3,7 +3,7 @@ 4.0.0 - org.matomo.java + org.piwik.java.tracking matomo-java-tracker-parent 4.0.0-SNAPSHOT ../pom.xml @@ -23,7 +23,7 @@ - org.matomo.java + org.piwik.java.tracking matomo-java-tracker-java11 ${project.version} diff --git a/servlet-javax/pom.xml b/servlet-javax/pom.xml index bbfcf81b..deda1932 100644 --- a/servlet-javax/pom.xml +++ b/servlet-javax/pom.xml @@ -3,7 +3,7 @@ 4.0.0 - org.matomo.java + org.piwik.java.tracking matomo-java-tracker-parent 4.0.0-SNAPSHOT ../pom.xml @@ -23,7 +23,7 @@ - org.matomo.java + org.piwik.java.tracking matomo-java-tracker ${project.version} diff --git a/spring/pom.xml b/spring/pom.xml index 5e1bf8ca..c2a3d4b6 100644 --- a/spring/pom.xml +++ b/spring/pom.xml @@ -3,7 +3,7 @@ 4.0.0 - org.matomo.java + org.piwik.java.tracking matomo-java-tracker-parent 4.0.0-SNAPSHOT ../pom.xml @@ -35,12 +35,12 @@ - org.matomo.java + org.piwik.java.tracking matomo-java-tracker-java11 ${project.version} - org.matomo.java + org.piwik.java.tracking matomo-java-tracker-servlet-jakarta ${project.version} diff --git a/test/pom.xml b/test/pom.xml index 83668095..2ce0e8b7 100644 --- a/test/pom.xml +++ b/test/pom.xml @@ -3,7 +3,7 @@ 4.0.0 - org.matomo.java + org.piwik.java.tracking matomo-java-tracker-parent 4.0.0-SNAPSHOT ../pom.xml @@ -21,12 +21,12 @@ - org.matomo.java + org.piwik.java.tracking matomo-java-tracker-java11 ${project.version} - org.matomo.java + org.piwik.java.tracking matomo-java-tracker-servlet-jakarta ${project.version} From ca4e4c76ee2ea03deea13da295faa61f2c9e26ba Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Mon, 11 May 2026 11:29:25 +0200 Subject: [PATCH 64/71] Update snapshot version --- .github/release-drafter.yml | 81 --------------------------- .github/workflows/release-drafter.yml | 32 ----------- README.md | 8 +-- SECURITY.md | 4 +- core/pom.xml | 2 +- java11/pom.xml | 4 +- java8/pom.xml | 4 +- pom.xml | 2 +- servlet-jakarta/pom.xml | 4 +- servlet-javax/pom.xml | 4 +- spring/pom.xml | 2 +- test/pom.xml | 2 +- 12 files changed, 18 insertions(+), 131 deletions(-) delete mode 100644 .github/release-drafter.yml delete mode 100644 .github/workflows/release-drafter.yml diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml deleted file mode 100644 index 6830782a..00000000 --- a/.github/release-drafter.yml +++ /dev/null @@ -1,81 +0,0 @@ -name-template: 'v$RESOLVED_VERSION' -tag-template: 'v$RESOLVED_VERSION' - -categories: - - title: 💥 Breaking changes - labels: - - breaking - - title: 🚨 Removed - labels: - - removed - - title: 🎉 Major features and improvements - labels: - - major-enhancement - - major-rfe - - title: 🐛 Major bug fixes - labels: - - major-bug - - title: ⚠️ Deprecated - labels: - - deprecated - - title: 🚀 New features and improvements - labels: - - enhancement - - feature - - rfe - - title: 🐛 Bug fixes - labels: - - bug - - fix - - bugfix - - regression - - regression-fix - - title: 🌐 Localization and translation - labels: - - localization - - title: 👷 Changes for developers - labels: - - developer - - title: 📝 Documentation updates - labels: - - documentation - - title: 👻 Maintenance - labels: - - chore - - internal - - maintenance - - title: 🚦 Tests - labels: - - test - - tests - - title: ✍ Other changes - - title: 📦 Dependency updates - labels: - - dependencies - collapse-after: 15 - -exclude-labels: - - reverted - - no-changelog - - skip-changelog - - invalid - -template: | - ## Changes - - $CHANGES - -autolabeler: - - label: 'documentation' - files: - - '*.md' - branch: - - '/docs{0,1}\/.+/' - - label: 'bug' - branch: - - '/fix\/.+/' - title: - - '/fix/i' - - label: 'enhancement' - branch: - - '/feature\/.+/' diff --git a/.github/workflows/release-drafter.yml b/.github/workflows/release-drafter.yml deleted file mode 100644 index 5e9b1df6..00000000 --- a/.github/workflows/release-drafter.yml +++ /dev/null @@ -1,32 +0,0 @@ -name: Release Drafter - -on: - push: - branches: - - main - pull_request: - types: - - opened - - reopened - - synchronize - -permissions: - contents: read - -jobs: - update_release_draft: - if: github.event_name == 'push' - runs-on: ubuntu-latest - permissions: - contents: write - pull-requests: read - steps: - - uses: release-drafter/release-drafter@v7 - - autolabel: - if: github.event_name == 'pull_request' - runs-on: ubuntu-latest - permissions: - pull-requests: write - steps: - - uses: release-drafter/release-drafter/autolabeler@v7 diff --git a/README.md b/README.md index 36e3fa44..30c39c52 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ Projects that use Matomo Java Tracker: ## What Is New? -### Version 4.0.x +### Version 4.0.0 Added more tracking parameters for user agent data, ecommerce product, bot recording mode, HTTP status, bandwidth, source label and media attributes. @@ -137,14 +137,14 @@ summary of the breaking changes and the recommended replacements: - Deprecated `Country(Locale)` constructor and `Country.getLocale()` / `Country.setLocale(Locale)` methods have been removed. Construct `Country` from a country code string instead. -### Version 3.4.x +### Version 3.4.0 We fixed a synchronization issue in the Java 8 sender (https://github.com/matomo-org/matomo-java-tracker/issues/168). To consume the exact amount of space needed for the queries to send to Matomo, we need the collection size of the incoming requests. So we changed `Iterable` to `Collection` in some `MatomoTracker`. This could affect users, that use parameters of type `Iterable` in the tracker. Please use `Collection` instead. -### Version 3.3.x +### Version 3.3.1 Do you still use Matomo Java Tracker 2.x? We created version 3, that is compatible with Matomo 4 and 5 and contains fewer @@ -754,7 +754,7 @@ version can be used in your local Maven repository for testing purposes, e.g. org.matomo.java matomo-java-tracker - 4.0.0-SNAPSHOT + 4.0.1-SNAPSHOT ``` diff --git a/SECURITY.md b/SECURITY.md index 641463ae..8f6e49f6 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -7,8 +7,8 @@ currently being supported with security updates. | Version | Supported | |---------|------------------------| -| >3 | :white_check_mark: yes | -| <=2 | ✖️ no | +| >4 | :white_check_mark: yes | +| <=3 | ✖️ no | ## Reporting a Vulnerability diff --git a/core/pom.xml b/core/pom.xml index f9dd4074..78690ada 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -5,7 +5,7 @@ org.piwik.java.tracking matomo-java-tracker-parent - 4.0.0-SNAPSHOT + 4.0.1-SNAPSHOT ../pom.xml diff --git a/java11/pom.xml b/java11/pom.xml index e4254d66..e9345692 100644 --- a/java11/pom.xml +++ b/java11/pom.xml @@ -5,12 +5,12 @@ org.piwik.java.tracking matomo-java-tracker-parent - 4.0.0-SNAPSHOT + 4.0.1-SNAPSHOT ../pom.xml matomo-java-tracker-java11 - 4.0.0-SNAPSHOT + 4.0.1-SNAPSHOT jar Matomo Java Tracker Java 11 diff --git a/java8/pom.xml b/java8/pom.xml index 60b6fe0d..ac9121bd 100644 --- a/java8/pom.xml +++ b/java8/pom.xml @@ -5,12 +5,12 @@ org.piwik.java.tracking matomo-java-tracker-parent - 4.0.0-SNAPSHOT + 4.0.1-SNAPSHOT ../pom.xml matomo-java-tracker - 4.0.0-SNAPSHOT + 4.0.1-SNAPSHOT jar Matomo Java Tracker Java 8 diff --git a/pom.xml b/pom.xml index 42dd0f22..d3e7e742 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ org.piwik.java.tracking matomo-java-tracker-parent - 4.0.0-SNAPSHOT + 4.0.1-SNAPSHOT pom Matomo Java Tracker Parent diff --git a/servlet-jakarta/pom.xml b/servlet-jakarta/pom.xml index 569bacdf..132f90f1 100644 --- a/servlet-jakarta/pom.xml +++ b/servlet-jakarta/pom.xml @@ -5,12 +5,12 @@ org.piwik.java.tracking matomo-java-tracker-parent - 4.0.0-SNAPSHOT + 4.0.1-SNAPSHOT ../pom.xml matomo-java-tracker-servlet-jakarta - 4.0.0-SNAPSHOT + 4.0.1-SNAPSHOT jar Matomo Java Tracker Servlet Jakarta diff --git a/servlet-javax/pom.xml b/servlet-javax/pom.xml index deda1932..2791103f 100644 --- a/servlet-javax/pom.xml +++ b/servlet-javax/pom.xml @@ -5,12 +5,12 @@ org.piwik.java.tracking matomo-java-tracker-parent - 4.0.0-SNAPSHOT + 4.0.1-SNAPSHOT ../pom.xml matomo-java-tracker-servlet-javax - 4.0.0-SNAPSHOT + 4.0.1-SNAPSHOT jar Matomo Java Tracker Servlet Javax diff --git a/spring/pom.xml b/spring/pom.xml index c2a3d4b6..47d5c833 100644 --- a/spring/pom.xml +++ b/spring/pom.xml @@ -5,7 +5,7 @@ org.piwik.java.tracking matomo-java-tracker-parent - 4.0.0-SNAPSHOT + 4.0.1-SNAPSHOT ../pom.xml diff --git a/test/pom.xml b/test/pom.xml index 2ce0e8b7..77fcbc33 100644 --- a/test/pom.xml +++ b/test/pom.xml @@ -5,7 +5,7 @@ org.piwik.java.tracking matomo-java-tracker-parent - 4.0.0-SNAPSHOT + 4.0.1-SNAPSHOT ../pom.xml From 3ff30426ead51444a31a21cec6209295b0c94414 Mon Sep 17 00:00:00 2001 From: Daniel Heid Date: Mon, 11 May 2026 11:44:45 +0200 Subject: [PATCH 65/71] Use org.piwik.java.tracking in README --- README.md | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 30c39c52..7b1121d6 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Official Matomo Java Tracker -![Maven Central Version](https://img.shields.io/maven-central/v/org.matomo.java/matomo-java-tracker-core) +![Maven Central Version](https://img.shields.io/maven-central/v/org.piwik.java.tracking/matomo-java-tracker-core) [![Build Status](https://github.com/matomo-org/matomo-java-tracker/actions/workflows/build.yml/badge.svg)](https://github.com/matomo-org/matomo-java-tracker/actions/workflows/build.yml) [![Average time to resolve an issue](https://isitmaintained.com/badge/resolution/matomo-org/matomo-java-tracker.svg)](https://isitmaintained.com/project/matomo-org/matomo-java-tracker "Average time to resolve an issue") [![Percentage of issues still open](https://isitmaintained.com/badge/open/matomo-org/matomo-java-tracker.svg)](https://isitmaintained.com/project/matomo-org/matomo-java-tracker "Percentage of issues still open") @@ -103,9 +103,6 @@ Jetty EE10 12.0.16 → 12.1.8, Jetty (javax) 10.0.24 → 10.0.26. The local testing Docker setup now uses MariaDB 12 and Matomo 5. -The Maven groupId has changed from `org.piwik.java.tracking` to `org.matomo.java`. Update your -dependency declarations accordingly. - All previously deprecated API has been removed as part of this major release. The following is a summary of the breaking changes and the recommended replacements: @@ -163,7 +160,7 @@ See also the [Developer Guide here](https://developer.matomo.org/api-reference/t ## Javadoc The Javadoc for all versions can be found -[at javadoc.io](https://javadoc.io/doc/org.matomo.java/matomo-java-tracker-core/latest/index.html). Thanks to +[at javadoc.io](https://javadoc.io/doc/org.piwik.java.tracking/matomo-java-tracker-core/latest/index.html). Thanks to [javadoc.io](https://javadoc.io) for hosting it. ## Need help? @@ -215,7 +212,7 @@ Add a dependency on Matomo Java Tracker using Maven. For Java 8: ```xml - org.matomo.java + org.piwik.java.tracking matomo-java-tracker 4.0.0 @@ -226,7 +223,7 @@ For Java 11 or newer: ```xml - org.matomo.java + org.piwik.java.tracking matomo-java-tracker-java11 4.0.0 @@ -236,7 +233,7 @@ or Gradle (Java 8): ```groovy dependencies { - implementation("org.matomo.java:matomo-java-tracker:4.0.0") + implementation("org.piwik.java.tracking:matomo-java-tracker:4.0.0") } ``` @@ -244,20 +241,20 @@ or Gradle (Java 11 or newer): ```groovy dependencies { - implementation("org.matomo.java:matomo-java-tracker-java11:4.0.0") + implementation("org.piwik.java.tracking:matomo-java-tracker-java11:4.0.0") } ``` or Gradle with Kotlin DSL (Java 8) ```kotlin -implementation("org.matomo.java:matomo-java-tracker:4.0.0") +implementation("org.piwik.java.tracking:matomo-java-tracker:4.0.0") ``` or Gradle with Kotlin DSL (Java 11 or newer) ```kotlin -implementation("org.matomo.java:matomo-java-tracker-java11:4.0.0") +implementation("org.piwik.java.tracking:matomo-java-tracker-java11:4.0.0") ``` ### Spring Boot Module @@ -268,7 +265,7 @@ and allows you to configure the tracker via application properties. Add the foll ```xml - org.matomo.java + org.piwik.java.tracking matomo-java-tracker-spring-boot-starter 4.0.0 @@ -278,14 +275,14 @@ or Gradle: ```groovy dependencies { - implementation("org.matomo.java:matomo-java-tracker-spring-boot-starter:4.0.0") + implementation("org.piwik.java.tracking:matomo-java-tracker-spring-boot-starter:4.0.0") } ``` or Gradle with Kotlin DSL ```kotlin -implementation("org.matomo.java:matomo-java-tracker-spring-boot-starter:4.0.0") +implementation("org.piwik.java.tracking:matomo-java-tracker-spring-boot-starter:4.0.0") ``` The following properties are supported: @@ -752,7 +749,7 @@ version can be used in your local Maven repository for testing purposes, e.g. ```xml - org.matomo.java + org.piwik.java.tracking matomo-java-tracker 4.0.1-SNAPSHOT From 19382804cef951a8d642cfcadc968b6844f9c3ea Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 12 May 2026 03:59:32 +0000 Subject: [PATCH 66/71] build(deps-dev): bump com.github.tomakehurst:wiremock-standalone from 2.27.2 to 3.0.1 (#404) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- java8/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java8/pom.xml b/java8/pom.xml index ac9121bd..cd8da47d 100644 --- a/java8/pom.xml +++ b/java8/pom.xml @@ -48,7 +48,7 @@ com.github.tomakehurst wiremock-standalone - 2.27.2 + 3.0.1 test From f4fa92f93d92eb263084eff6445ce5d19ac5c554 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 19 May 2026 06:46:31 +0000 Subject: [PATCH 67/71] build(deps-dev): bump org.apache.maven.plugins:maven-enforcer-plugin from 3.6.2 to 3.6.3 (#405) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index d3e7e742..68b66eac 100644 --- a/pom.xml +++ b/pom.xml @@ -275,7 +275,7 @@ org.apache.maven.plugins maven-enforcer-plugin - 3.6.2 + 3.6.3 enforce-maven From ebe9eacc1e8e38cd631e2eed1ef71b78bb77840d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 19 May 2026 06:47:21 +0000 Subject: [PATCH 68/71] build(deps-dev): bump com.diffplug.spotless:spotless-maven-plugin from 3.4.0 to 3.5.1 (#406) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 68b66eac..dc5f6ede 100644 --- a/pom.xml +++ b/pom.xml @@ -386,7 +386,7 @@ com.diffplug.spotless spotless-maven-plugin - 3.4.0 + 3.5.1 From ec7a5aef3074c696338ed84df11a4ea551b68a9c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 19 May 2026 06:47:30 +0000 Subject: [PATCH 69/71] build(deps): bump slf4j.version from 2.0.17 to 2.0.18 (#407) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index dc5f6ede..49c90e20 100644 --- a/pom.xml +++ b/pom.xml @@ -70,7 +70,7 @@ 1.8 ${project.build.outputDirectory}/delombok 1.18.46 - 2.0.17 + 2.0.18 From 2007327f712581b85092ef3fd678eaa59756a20a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 26 May 2026 03:13:52 +0000 Subject: [PATCH 70/71] build(deps): bump org.junit.jupiter:junit-jupiter from 6.0.3 to 6.1.0 (#409) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 49c90e20..82887d22 100644 --- a/pom.xml +++ b/pom.xml @@ -95,7 +95,7 @@ org.junit.jupiter junit-jupiter - 6.0.3 + 6.1.0 test From 0f7d4676ae0520be11aff11699925e37c79b92ba Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 26 May 2026 03:15:54 +0000 Subject: [PATCH 71/71] build(deps-dev): bump org.apache.maven.plugins:maven-site-plugin from 3.21.0 to 3.22.0 (#408) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 82887d22..36806141 100644 --- a/pom.xml +++ b/pom.xml @@ -159,7 +159,7 @@ org.apache.maven.plugins maven-site-plugin - 3.21.0 + 3.22.0 org.apache.maven.plugins