matomo-java-tracker

Official Matomo Java Tracker

Maven Central Build Status Average time to resolve an issue Percentage of issues still open

The Matomo Java Tracker functions as the official Java implementation for the Matomo Tracking HTTP API. This versatile tracker empowers you to monitor visits, goals, and ecommerce transactions and items. Specifically designed for integration into server-side applications, it seamlessly integrates with Java-based web applications or web services.

Key features:

Please prefer the Java 11 version as the Java 8 will become obsolete in the future.

You can find our Developer Guide here

Further information on Matomo and Matomo HTTP tracking:

Projects that use Matomo Java Tracker:

Table of Contents

What Is New?

Version 3.4.x

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

Do you still use Matomo Java Tracker 2.x? We created version 3, that is compatible with Matomo 4 and 5 and contains fewer dependencies. Release notes can be found here: https://github.com/matomo-org/matomo-java-tracker/releases

Here are the most important changes:

See also the Developer Guide here

Javadoc

The Javadoc for all versions can be found at javadoc.io. Thanks to javadoc.io for hosting it.

Need help?

Using this API

See the following sections for information on how to use this API. For more information, see the Javadoc. We also recommend to read the Tracking API User Guide. The Matomo Tracking HTTP API is well documented and contains many examples.

This project contains the following Maven artifacts:

  1. matomo-java-tracker-core: This artifact is the core module of the Matomo Java Tracker project. It provides the main functionality of the Matomo Java Tracker, which is a Java implementation for the Matomo Tracking HTTP API. This module is designed to be used as a base for other modules in the project that provide additional functionality or integrations.
  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.
  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 configure the Matomo Java Tracker.
  5. matomo-java-tracker-servlet-jakarta: This artifact is specifically designed for applications using the Jakarta Servlet API (part of Jakarta EE).
  6. matomo-java-tracker-servlet-javax: This artifact is specifically designed for applications using the older Java Servlet API (part of Java EE).
  7. matomo-java-tracker-test: This artifact contains tools for manual testing against a local Matomo instance created with Docker. It contains a tester class that sends randomized requests to a local Matomo instance and a servlet that can be used to test the servlet integration.

Each of these artifacts serves a different purpose and can be used depending on the specific needs of your project and the Java version you are using.

Add library to your build

Add a dependency on Matomo Java Tracker using Maven. For Java 8:


<dependency>
    <groupId>org.piwik.java.tracking</groupId>
    <artifactId>matomo-java-tracker</artifactId>
    <version>3.4.0</version>
</dependency>

For Java 11:


<dependency>
    <groupId>org.piwik.java.tracking</groupId>
    <artifactId>matomo-java-tracker-java11</artifactId>
    <version>3.4.0</version>
</dependency>

or Gradle (Java 8):

dependencies {
    implementation("org.piwik.java.tracking:matomo-java-tracker:3.4.0")
}

or Gradle (Java 11):

dependencies {
    implementation("org.piwik.java.tracking:matomo-java-tracker-java11:3.4.0")
}

or Gradle with Kotlin DSL (Java 8)

implementation("org.piwik.java.tracking:matomo-java-tracker:3.4.0")

or Gradle with Kotlin DSL (Java 11)

implementation("org.piwik.java.tracking:matomo-java-tracker-java11:3.4.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 and allows you to configure the tracker via application properties. Add the following dependency to your build:


<dependency>
    <groupId>org.piwik.java.tracking</groupId>
    <artifactId>matomo-java-tracker-spring-boot-starter</artifactId>
    <version>3.4.0</version>
</dependency>

or Gradle:

dependencies {
    implementation("org.piwik.java.tracking:matomo-java-tracker-spring-boot-starter:3.4.0")
}

or Gradle with Kotlin DSL

implementation("org.piwik.java.tracking:matomo-java-tracker-spring-boot-starter:3.4.0")

The following properties are supported:

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.
matomo.tracker.default-token-auth If you provide a default token auth, it will be taken if the action does not contain a token auth.
matomo.tracker.enabled The tracker is enabled per default. You can disable it per configuration with this flag.
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.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.
matomo.tracker.proxy-password The corresponding password for the basic auth proxy user. The proxy host, port and username must be set as well.
matomo.tracker.disable-ssl-cert-validation If set to true, the SSL certificate of the Matomo server will not be validated. This should only be used for testing purposes. Default: false
matomo.tracker.disable-ssl-host-verification If set to true, the SSL host of the Matomo server will not be validated. This should only be used for testing purposes. Default: false
matomo.tracker.thread-pool-size The number of threads that will be used to asynchronously send requests. Default: 2
matomo.tracker.filter.enabled Enables a servlet filter that tracks every request within the application

To ensure the MatomoTracker bean is created by the auto configuration, you have to add the following property to your application.properties file:

matomo.tracker.api-endpoint=https://your-matomo-domain.tld/matomo.php

Or if you use YAML:

matomo:
    tracker:
        api-endpoint: https://your-matomo-domain.tld/matomo.php

You can automatically add the MatomoTrackerFilter to your Spring Boot application if you add the following property:

matomo.tracker.filter.enabled=true

Or if you use YAML:

matomo:
    tracker:
        filter:
            enabled: true

The filter uses ServletMatomoRequest to create a MatomoRequest from a HttpServletRequest on every filter call.

Sending a Tracking Request

To let the Matomo Java Tracker send a request to the Matomo instance, you need the following minimal code:

import java.net.URI;
import org.matomo.java.tracking.MatomoRequests;
import org.matomo.java.tracking.MatomoTracker;
import org.matomo.java.tracking.TrackerConfiguration;
import org.matomo.java.tracking.parameters.VisitorId;

/**
 * Example for sending a request.
 */
public class SendExample {

    /**
     * Example for sending a request.
     *
     * @param args ignored
     */
    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();

        try (MatomoTracker tracker = new MatomoTracker(configuration)) {
            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);
        }
    }

}

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 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.

If you want to perform an operation after a successful asynchronous call to Matomo, you can use the completable future result like this:

import java.net.URI;
import org.matomo.java.tracking.MatomoRequest;
import org.matomo.java.tracking.MatomoRequests;
import org.matomo.java.tracking.MatomoTracker;
import org.matomo.java.tracking.TrackerConfiguration;
import org.matomo.java.tracking.parameters.VisitorId;

/**
 * Example for sending a request and performing an action when the request was sent successfully.
 */
public class ConsumerExample {

    /**
     * Example for sending a request and performing an action when the request was sent successfully.
     *
     * @param args ignored
     */
    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();

        try (MatomoTracker tracker = new MatomoTracker(configuration)) {
            MatomoRequest request = MatomoRequests
                    .event("Training", "Workout completed", "Bench press", 60.0)
                    .visitorId(VisitorId.fromString("customer@mail.com"))
                    .build();

            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;
                    });
        } catch (Exception e) {
            throw new RuntimeException("Could not close tracker", e);
        }

    }

}


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, send a bulk request. Place your requests in an Iterable data structure and call

import java.net.URI;
import org.matomo.java.tracking.MatomoRequests;
import org.matomo.java.tracking.MatomoTracker;
import org.matomo.java.tracking.TrackerConfiguration;
import org.matomo.java.tracking.parameters.VisitorId;

/**
 * Example for sending multiple requests in one bulk request.
 */
public class BulkExample {

    /**
     * Example for sending multiple requests in one bulk request.
     *
     * @param args ignored
     */
    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();

        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.ecommerceOrder("QXZ-789LMP", 100.0, 124.0, 19.0, 10.0, 5.0)
                            .visitorId(visitorId)
                            .build()
            );
        } catch (Exception e) {
            throw new RuntimeException("Could not close tracker", e);
        }

    }

}

This will send two 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
required true
visitorId random 16 character hex string
randomValue random 20 character hex string
apiVersion 1
responseAsImage false

Overwrite these properties as desired. We strongly recommend your 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:

import java.net.URI;
import org.matomo.java.tracking.MatomoRequests;
import org.matomo.java.tracking.MatomoTracker;
import org.matomo.java.tracking.TrackerConfiguration;
import org.matomo.java.tracking.parameters.EcommerceItem;
import org.matomo.java.tracking.parameters.EcommerceItems;
import org.matomo.java.tracking.parameters.VisitorId;

/**
 * Example for sending an ecommerce request.
 */
public class EcommerceExample {

    /**
     * Example for sending an ecommerce request.
     *
     * @param args ignored
     */
    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();

        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()
            );
        } catch (Exception e) {
            throw new RuntimeException("Could not close tracker", e);
        }

    }

}

Note that if you want to be able to track campaigns using Referrers > Campaigns, you must add the correct URL parameters to your actionUrl. See Tracking Campaigns for more information. All HTTP query parameters denoted on the Matomo Tracking HTTP API can be set using the appropriate getters and setters. See MatomoRequest for the mappings of the parameters to their corresponding attributes.

Requests are validated prior to sending. If a request is invalid, a MatomoException will be thrown.

In a Servlet environment, it might be easier to use the ServletMatomoRequest class to create a MatomoRequest from a HttpServletRequest:

import jakarta.servlet.http.HttpServletRequest;
import org.matomo.java.tracking.MatomoRequest;
import org.matomo.java.tracking.MatomoRequests;
import org.matomo.java.tracking.MatomoTracker;
import org.matomo.java.tracking.parameters.VisitorId;
import org.matomo.java.tracking.servlet.JakartaHttpServletWrapper;
import org.matomo.java.tracking.servlet.ServletMatomoRequest;

public class ServletMatomoRequestExample {

    private final MatomoTracker tracker;

    public ServletMatomoRequestExample(MatomoTracker tracker) {
        this.tracker = tracker;
    }

    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();
        tracker.sendRequestAsync(matomoRequest);
        // ...
    }

}

The ServletMatomoRequest automatically sets the action URL, applies browser request headers, corresponding Matomo cookies and the visitor IP address. It sets the visitor ID, Matomo session ID, custom variables and heatmap if Matomo cookies are present. Since there was a renaming from Java EE (javax) to Jakarta EE (jakarta), we provide a wrapper class JakartaHttpServletWrapper for Jakarta and JavaxHttpServletWrapper for javax.

Tracking Configuration

The MatomoTracker can be configured using the TrackerConfiguration object. The following configuration options are available:

Migration from Version 2 to 3

We improved this library by adding the dimension parameter and removing outdated parameters in Matomo version 5, removing some dependencies (that even contained vulnerabilities) and increasing maintainability. Sadly this includes the following breaking changes:

Removals

Type Changes and Renaming

Visitor ID

Custom Variables

Building and testing

This project can be tested and built by calling

mvn install

The built jars and javadoc can be found in target. By using the Maven goal `install, a snapshot version can be used in your local Maven repository for testing purposes, e.g.

<dependency>
    <groupId>org.piwik.java.tracking</groupId>
    <artifactId>matomo-java-tracker</artifactId>
    <version>3.4.1-SNAPSHOT</version>
</dependency>

Testing on a local Matomo instance

To start a local Matomo instance for testing, you can use the docker-compose file in the root directory of this project. Start the docker containers with

docker-compose up -d

You need to adapt your config.ini.php file and change the following line:

[General]
trusted_hosts[] = "localhost:8080"

to

[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.

The following snippets helps you to do this quickly:

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.

To enable debug logging, you append the following line to the config.ini.php file:

[Tracker]
debug = 1

Use the following snippet to do this:

docker-compose exec matomo sh -c 'echo -e "\n\n[Tracker]\ndebug = 1\n" >> /var/www/html/config/config.ini.php'

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. We also recommend to install the Custom Variables plugin from Marketplace to the test custom variables feature and setup some dimensions.

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

Contribute

Have a fantastic feature idea? Spot a bug? We would absolutely love for you to contribute to this project! Please feel free to:

Please read the contribution document for details on our code of conduct, and the process for submitting pull requests to us.

We use Checkstyle and JaCoCo to ensure code quality. Please run mvn verify before submitting a pull request. Please provide tests for your changes. We use JUnit 5 for testing. Coverage should be at least 80%.

Other Java Matomo Tracker Implementations

License

This software is released under the BSD 3-Clause license. See LICENSE.

Copyright (c) 2015 General Electric Company. All rights reserved.