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
deleted file mode 100644
index 04cbbee5..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/DaemonThreadFactory.java b/core/src/main/java/org/matomo/java/tracking/DaemonThreadFactory.java
index 9dc93b45..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,8 @@ 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;
}
-}
\ 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
deleted file mode 100644
index 64ac6037..00000000
--- a/core/src/main/java/org/matomo/java/tracking/EcommerceItem.java
+++ /dev/null
@@ -1,35 +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/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
deleted file mode 100644
index 331f4923..00000000
--- a/core/src/main/java/org/matomo/java/tracking/MatomoDate.java
+++ /dev/null
@@ -1,69 +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/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
deleted file mode 100644
index d0dad67d..00000000
--- a/core/src/main/java/org/matomo/java/tracking/MatomoLocale.java
+++ /dev/null
@@ -1,43 +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 d9349836..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;
@@ -59,10 +53,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 +65,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 +78,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,124 +131,89 @@ 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;
+ /**
+ * 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.
@@ -279,15 +231,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 +267,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 +276,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,10 +295,8 @@ public class MatomoRequest {
@TrackingParameter(name = "idgoal", min = 0)
private Integer goalId;
- /**
- * The grand total for the ecommerce order (required when tracking an ecommerce order).
- */
- @TrackingParameter(name = "revenue")
+ /** The grand total for the ecommerce order (required when tracking an ecommerce order). */
+ @TrackingParameter(name = "revenue", min = 0)
private Double ecommerceRevenue;
/**
@@ -374,21 +315,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 +341,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.
- */
- @TrackingParameter(name = "e_v")
+ /** 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,34 +384,24 @@ 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.
- */
- @TrackingParameter(name = "ec_st")
+ /** The subtotal of the order; excludes shipping. */
+ @TrackingParameter(name = "ec_st", min = 0)
private Double ecommerceSubtotal;
- /**
- * Tax amount of the order.
- */
- @TrackingParameter(name = "ec_tx")
+ /** Tax amount of the order. */
+ @TrackingParameter(name = "ec_tx", min = 0)
private Double ecommerceTax;
- /**
- * Shipping cost of the order.
- */
- @TrackingParameter(name = "ec_sh")
+ /** Shipping cost of the order. */
+ @TrackingParameter(name = "ec_sh", min = 0)
private Double ecommerceShippingCost;
- /**
- * Discount offered.
- */
- @TrackingParameter(name = "ec_dt")
+ /** Discount offered. */
+ @TrackingParameter(name = "ec_dt", min = 0)
private Double ecommerceDiscount;
/**
@@ -504,21 +411,49 @@ 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
* 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 +464,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,6 +524,33 @@ 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
@@ -619,6 +567,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.
*
@@ -634,8 +675,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 +736,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 +745,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;
@@ -733,439 +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 01c43cd2..00000000
--- a/core/src/main/java/org/matomo/java/tracking/MatomoRequestBuilder.java
+++ /dev/null
@@ -1,49 +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/MatomoRequests.java b/core/src/main/java/org/matomo/java/tracking/MatomoRequests.java
index c5b57c09..8fce9560 100644
--- a/core/src/main/java/org/matomo/java/tracking/MatomoRequests.java
+++ b/core/src/main/java/org/matomo/java/tracking/MatomoRequests.java
@@ -20,16 +20,14 @@ public class MatomoRequests {
/**
* Creates a {@link MatomoRequest} object for a download or a link action.
*
- * @param url The URL of the download or link. Must not be null.
- * @param type The type of the action. Either {@link ActionType#DOWNLOAD} or
- * {@link ActionType#LINK}.
- *
+ * @param url The URL of the download or link. Must not be null.
+ * @param type The type of the action. Either {@link ActionType#DOWNLOAD} or {@link
+ * ActionType#LINK}.
* @return A {@link MatomoRequest.MatomoRequestBuilder} object to add additional parameters.
*/
@edu.umd.cs.findbugs.annotations.NonNull
public static MatomoRequest.MatomoRequestBuilder action(
- @NonNull String url, @NonNull ActionType type
- ) {
+ @NonNull String url, @NonNull ActionType type) {
return type.applyUrl(MatomoRequest.request(), url);
}
@@ -37,30 +35,28 @@ public static MatomoRequest.MatomoRequestBuilder action(
* Creates a {@link MatomoRequest} object for a content impression.
*
* A 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..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;
@@ -23,13 +18,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.
*
@@ -45,98 +41,23 @@ 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.
*
* @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.
- *
- * @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.
*
- *
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,64 +74,42 @@ 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
- ) {
- 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
- ) {
+ public CompletableFuture sendRequestAsync(@NonNull MatomoRequest request) {
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);
}
- 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,155 +121,74 @@ 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
*/
public void sendBulkRequest(MatomoRequest... requests) {
- sendBulkRequest(Arrays.asList(requests), null);
+ sendBulkRequest(Arrays.asList(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
*/
public void sendBulkRequest(@NonNull Iterable extends MatomoRequest> 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 extends MatomoRequest> 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");
}
}
/**
- * 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(MatomoRequest... requests) {
- return sendBulkRequestAsync(Arrays.asList(requests), null, null);
+ return sendBulkRequestAsync(Arrays.asList(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 extends MatomoRequest> 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 extends MatomoRequest> requests,
- @Nullable String authToken,
- @Nullable Consumer callback
- ) {
+ @NonNull Collection extends MatomoRequest> requests) {
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 extends MatomoRequest> 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 extends MatomoRequest> requests, @Nullable String authToken
- ) {
- return sendBulkRequestAsync(requests, authToken, null);
- }
-
@Override
public void close() throws Exception {
if (sender != null) {
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..a824dedb 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);
@@ -92,9 +91,12 @@ String createQuery(
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));
+ }
}
}
}
@@ -102,10 +104,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 +122,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 +148,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..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,26 +1,17 @@
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;
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 extends MatomoRequest> requests, @Nullable String overrideAuthToken
- );
+ void sendBulk(@NonNull Iterable extends MatomoRequest> requests);
@NonNull
- CompletableFuture sendBulkAsync(
- @NonNull Collection extends MatomoRequest> requests, @Nullable String overrideAuthToken
- );
+ CompletableFuture sendBulkAsync(@NonNull Collection extends MatomoRequest> requests);
}
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..110ae027 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,21 +114,17 @@ 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");
}
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/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..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
@@ -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()
+ : languageRange.getRange() + ";q=" + 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..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
@@ -18,26 +18,13 @@
/**
* 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;
-
- /**
- * 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);
- }
+ @NonNull private String code;
/**
* Creates a country from a given code.
@@ -46,10 +33,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 +50,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;
}
@@ -84,38 +65,8 @@ public static Country fromLanguageRanges(
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/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..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
@@ -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;
}
@@ -53,7 +48,6 @@ public static DeviceResolution fromString(
@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 7f5ba051..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
@@ -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,19 +21,15 @@ 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);
+ return "[\"" + 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..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,9 +20,8 @@ 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/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..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
@@ -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,20 +125,20 @@ 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
- ) {
- if (cookieName.toLowerCase(Locale.ROOT).startsWith("_pk_id")) {
+ @edu.umd.cs.findbugs.annotations.NonNull String cookieValue) {
+ 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));
}
}
@@ -159,12 +147,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
deleted file mode 100644
index 20845bed..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 49c3a83c..00000000
--- a/core/src/main/java/org/piwik/java/tracking/EcommerceItem.java
+++ /dev/null
@@ -1,34 +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 d8029269..00000000
--- a/core/src/main/java/org/piwik/java/tracking/PiwikDate.java
+++ /dev/null
@@ -1,55 +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 34f156d6..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 e4d64fe4..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 02e18b13..00000000
--- a/core/src/main/java/org/piwik/java/tracking/PiwikTracker.java
+++ /dev/null
@@ -1,74 +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 eb647ae7..00000000
--- a/core/src/main/java/org/piwik/java/tracking/package-info.java
+++ /dev/null
@@ -1,5 +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..bdafba71 100644
--- a/core/src/test/java/org/matomo/java/tracking/AuthTokenTest.java
+++ b/core/src/test/java/org/matomo/java/tracking/AuthTokenTest.java
@@ -12,26 +12,25 @@ 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);
+ String authToken = AuthToken.determineAuthToken(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);
+ String authToken = AuthToken.determineAuthToken(null, trackerConfiguration);
assertThat(authToken).isEqualTo("bdeca231a312ab12cde124131bedfa23");
}
@@ -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);
+ String authToken = AuthToken.determineAuthToken(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);
+ 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 535986a0..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,20 +5,42 @@
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 formatsQueryAsJson() {
+ 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\"}");
+ }
+
@Test
void formatsQueriesAsJson() {
- BulkRequest bulkRequest = BulkRequest.builder()
- .queries(singleton("idsite=1&rec=1&action_name=TestBulkRequest"))
- .authToken("token")
- .build();
+ 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=TestBulkRequest\"],\"token_auth\":\"token\"}");
+ assertThat(new String(bytes))
+ .isEqualTo(
+ "{\"requests\":[\"?idsite=1&rec=1&action_name=TestBulkRequest1\",\"?idsite=1&rec=1&action_name=TestBulkRequest2\"],\"token_auth\":\"token\"}");
}
@Test
@@ -29,7 +51,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
deleted file mode 100644
index e58a10dd..00000000
--- a/core/src/test/java/org/matomo/java/tracking/CustomVariableTest.java
+++ /dev/null
@@ -1,43 +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/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/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
deleted file mode 100644
index 7822acd3..00000000
--- a/core/src/test/java/org/matomo/java/tracking/MatomoLocaleTest.java
+++ /dev/null
@@ -1,24 +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 87dab6d5..00000000
--- a/core/src/test/java/org/matomo/java/tracking/MatomoRequestBuilderTest.java
+++ /dev/null
@@ -1,88 +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 b4ad0e04..00000000
--- a/core/src/test/java/org/matomo/java/tracking/MatomoRequestTest.java
+++ /dev/null
@@ -1,134 +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/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..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;
@@ -17,18 +18,19 @@ 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() {
- matomoTracker = new MatomoTracker(HOST_URL);
+ matomoTracker =
+ new MatomoTracker(TrackerConfiguration.builder().apiEndpoint(URI.create(HOST_URL)).build());
matomoTracker.setSenderFactory(senderFactory);
matomoTracker.sendRequest(request);
@@ -36,13 +38,13 @@ void sendsRequest() {
TestSender testSender = senderFactory.getTestSender();
thenContainsRequest(testSender, QUERY);
assertThat(testSender.getTrackerConfiguration().getApiEndpoint()).hasToString(HOST_URL);
-
}
@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);
@@ -51,26 +53,34 @@ 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
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);
@@ -80,13 +90,18 @@ void sendsRequestUsingProxy() {
TrackerConfiguration trackerConfiguration = testSender.getTrackerConfiguration();
assertThat(trackerConfiguration.getProxyHost()).isEqualTo("localhost");
assertThat(trackerConfiguration.getProxyPort()).isEqualTo(8081);
-
}
@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);
@@ -94,45 +109,55 @@ void sendsRequestAsync() {
TestSender testSender = senderFactory.getTestSender();
thenContainsRequest(testSender, QUERY);
assertThat(testSender.getTrackerConfiguration().getApiEndpoint()).hasToString(HOST_URL);
-
}
@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);
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
void sendsBulkRequests() {
- matomoTracker = new MatomoTracker(HOST_URL);
+ matomoTracker =
+ new MatomoTracker(TrackerConfiguration.builder().apiEndpoint(URI.create(HOST_URL)).build());
matomoTracker.setSenderFactory(senderFactory);
matomoTracker.sendBulkRequest(request);
@@ -140,26 +165,34 @@ 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
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);
@@ -167,68 +200,65 @@ 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
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);
assertThat(testSender.getTrackerConfiguration().getApiEndpoint()).hasToString(HOST_URL);
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");
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
deleted file mode 100644
index 40c8bd80..00000000
--- a/core/src/test/java/org/matomo/java/tracking/PiwikDateTest.java
+++ /dev/null
@@ -1,43 +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 46e1c563..00000000
--- a/core/src/test/java/org/matomo/java/tracking/PiwikLocaleTest.java
+++ /dev/null
@@ -1,29 +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 c88c7570..00000000
--- a/core/src/test/java/org/matomo/java/tracking/PiwikRequestTest.java
+++ /dev/null
@@ -1,940 +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/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 8611d106..1bcac9eb 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,20 +43,20 @@ 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();
- String authToken = AuthToken.determineAuthToken(null, singleton(request), trackerConfiguration);
+ TrackerConfiguration trackerConfiguration =
+ TrackerConfiguration.builder()
+ .apiEndpoint(URI.create("http://localhost"))
+ .defaultSiteId(42)
+ .defaultAuthToken(defaultAuthToken)
+ .build();
+ String authToken = AuthToken.determineAuthToken(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
@@ -351,16 +362,15 @@ 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");
+ 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 +380,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 +404,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 +415,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,14 +552,269 @@ 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");
+
+ 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");
+ }
+
+ @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");
+ }
}
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..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,17 +1,17 @@
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 {
private final MatomoRequest request = new MatomoRequest();
-
@Test
void testSearchResultsCount() {
@@ -20,7 +20,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 +29,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 +40,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 +51,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,31 +62,52 @@ 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
- 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)
.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
- void testRequestDatetime() {
+ void testVisitorIp() {
+ request.setVisitorIp("192.168.0.1");
+
+ 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");
+ }
- PiwikDate date = new PiwikDate(1000L);
- request.setRequestDatetime(date);
+ @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
@@ -93,5 +116,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..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;
@@ -13,9 +12,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
@@ -32,39 +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 extends MatomoRequest> requests, @Nullable String overrideAuthToken
- ) {
+ public void sendBulk(@NonNull Iterable extends MatomoRequest> requests) {
for (MatomoRequest request : requests) {
- createQueryAndAddRequest(request, overrideAuthToken);
+ createQueryAndAddRequest(request);
}
}
@NonNull
@Override
public CompletableFuture sendBulkAsync(
- @NonNull Collection extends MatomoRequest> requests, @Nullable String overrideAuthToken
- ) {
+ @NonNull Collection extends MatomoRequest> 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/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..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;
@@ -23,7 +22,6 @@ void createsCountryFromCode() {
Country country = Country.fromCode("DE");
assertThat(country).hasToString("de");
-
}
@Test
@@ -32,7 +30,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 +39,6 @@ void returnsNullOnEmptyRanges(String ranges) {
Country country = Country.fromLanguageRanges(ranges);
assertThat(country).isNull();
-
}
@Test
@@ -51,7 +47,6 @@ void failsOnInvalidCountryCode() {
assertThatThrownBy(() -> Country.fromCode("invalid"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid country code");
-
}
@Test
@@ -60,7 +55,6 @@ void failsOnInvalidCountryCodeLength() {
assertThatThrownBy(() -> Country.fromCode("invalid"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid country code");
-
}
@Test
@@ -69,7 +63,6 @@ void returnsNullOnNullCode() {
Country country = Country.fromCode(null);
assertThat(country).isNull();
-
}
@Test
@@ -78,7 +71,6 @@ void returnsNullOnEmptyCode() {
Country country = Country.fromCode("");
assertThat(country).isNull();
-
}
@Test
@@ -87,7 +79,6 @@ void returnsNullOnBlankCode() {
Country country = Country.fromCode(" ");
assertThat(country).isNull();
-
}
@Test
@@ -96,7 +87,6 @@ void returnsNullOnNullRanges() {
Country country = Country.fromLanguageRanges(null);
assertThat(country).isNull();
-
}
@Test
@@ -105,7 +95,6 @@ void returnsNullOnBlankRanges() {
Country country = Country.fromLanguageRanges(" ");
assertThat(country).isNull();
-
}
@Test
@@ -114,41 +103,5 @@ void failsOnInvalidRanges() {
assertThatThrownBy(() -> Country.fromLanguageRanges("invalid"))
.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 f072d09e..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;
@@ -66,4 +67,29 @@ void equalsCustomVariable() {
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/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..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
@@ -20,7 +20,14 @@ void formatsDeviceResolution() {
DeviceResolution deviceResolution = DeviceResolution.builder().width(1280).height(1080).build();
assertThat(deviceResolution).hasToString("1280x1080");
+ }
+
+ @Test
+ void formatsDeviceResolutionFromString() {
+
+ DeviceResolution deviceResolution = DeviceResolution.fromString("1280x1080");
+ assertThat(deviceResolution).hasToString("1280x1080");
}
@Test
@@ -29,7 +36,6 @@ void returnsNullOnNull() {
DeviceResolution deviceResolution = DeviceResolution.fromString(null);
assertThat(deviceResolution).isNull();
-
}
@Test
@@ -50,5 +56,4 @@ void failsIfDeviceResolutionIsTooShort() {
void returnsNullIfDeviceResolutionIsEmpty() {
assertThat(DeviceResolution.fromString("")).isNull();
}
-
}
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 75%
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 71e9fcc0..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;
@@ -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/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/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/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..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
@@ -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,21 @@ void createsVisitorIdFromString() {
VisitorId visitorId = VisitorId.fromString("test");
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/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
deleted file mode 100644
index 4492d0a2..00000000
--- a/core/src/test/java/org/piwik/java/tracking/CustomVariableTest.java
+++ /dev/null
@@ -1,17 +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 c4ce73e6..00000000
--- a/core/src/test/java/org/piwik/java/tracking/PiwikTrackerIT.java
+++ /dev/null
@@ -1,47 +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();
-
- }
-
-}
\ 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 677f0c18..e9345692 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
+ 4.0.1-SNAPSHOT
../pom.xml
matomo-java-tracker-java11
- 3.4.1-SNAPSHOT
+ 4.0.1-SNAPSHOT
jar
Matomo Java Tracker Java 11
@@ -48,7 +49,7 @@
org.wiremock
wiremock
- 3.11.0
+ 3.13.2
test
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..9fd1e7b1 100644
--- a/java11/src/main/java/org/matomo/java/tracking/Java11Sender.java
+++ b/java11/src/main/java/org/matomo/java/tracking/Java11Sender.java
@@ -14,40 +14,31 @@
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;
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,26 +51,18 @@ 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 extends MatomoRequest> requests,
- @Nullable String overrideAuthToken
- ) {
- sendAndCheckResponse(buildHttpPostRequest(requests, overrideAuthToken));
+ public void sendBulk(@NonNull @lombok.NonNull Iterable extends MatomoRequest> requests) {
+ sendAndCheckResponse(buildHttpPostRequest(requests));
}
@NonNull
- private HttpRequest buildHttpPostRequest(
- @NonNull Iterable extends MatomoRequest> requests, @Nullable String overrideAuthToken
- ) {
- String authToken =
- AuthToken.determineAuthToken(overrideAuthToken, requests, trackerConfiguration);
+ private HttpRequest buildHttpPostRequest(@NonNull Iterable extends MatomoRequest> requests) {
+ String authToken = AuthToken.determineAuthToken(requests, trackerConfiguration);
Collection queries = new ArrayList<>();
Map headers = new LinkedHashMap<>(10);
String headerUserAgent = null;
@@ -89,23 +72,20 @@ 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));
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);
@@ -115,53 +95,50 @@ private HttpRequest buildHttpPostRequest(
@NonNull
@Override
public CompletableFuture sendBulkAsync(
- @NonNull @lombok.NonNull Collection extends MatomoRequest> requests,
- @Nullable String overrideAuthToken
- ) {
- return sendAsyncAndCheckResponse(buildHttpPostRequest(requests, overrideAuthToken), null);
+ @NonNull @lombok.NonNull Collection extends MatomoRequest> requests) {
+ return sendAsyncAndCheckResponse(buildHttpPostRequest(requests), 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
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);
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(
+ 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());
- 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()) {
@@ -172,21 +149,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 +181,28 @@ private void applyTrackerConfiguration(@NonNull HttpRequest.Builder builder) {
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");
+ @Nullable Map headers) {
+ 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 && !trackerConfiguration.getUserAgent().isEmpty()) {
+ if (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..89c9da3c 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,75 +247,72 @@ 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()));
- 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();
- 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"));
}
@@ -309,23 +320,24 @@ 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()));
future.join();
- verify(postRequestedFor(urlPathEqualTo("/matomo.php")).withHeader(
- "headerName",
- equalTo("headerValue")
- ));
+ verify(
+ postRequestedFor(urlPathEqualTo("/matomo.php"))
+ .withHeader("headerName", equalTo("headerValue")));
}
@Test
@@ -359,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");
}
@@ -371,26 +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 734d69e0..48682b5c 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())
+ .thenAccept(
+ request -> {
+ success.set(true);
+ });
+ assertThat(future)
+ .succeedsWithin(1, MINUTES)
+ .satisfies(
+ v -> {
+ verify(getRequestedFor(urlPathEqualTo("/matomo.php")));
+ });
assertThat(success).isTrue();
}
@@ -489,13 +530,16 @@ 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()))
+ .thenAccept(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
deleted file mode 100644
index 799af605..00000000
--- a/java11/src/test/java/org/matomo/java/tracking/PiwikTrackerIT.java
+++ /dev/null
@@ -1,249 +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 4b4621ad..cd8da47d 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
+ 4.0.1-SNAPSHOT
../pom.xml
matomo-java-tracker
- 3.4.1-SNAPSHOT
+ 4.0.1-SNAPSHOT
jar
Matomo Java Tracker Java 8
@@ -47,7 +48,7 @@
com.github.tomakehurst
wiremock-standalone
- 2.27.2
+ 3.0.1
test
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..c398bc51 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
- ) {
- String authToken = AuthToken.determineAuthToken(null, singleton(request), trackerConfiguration);
+ public void sendSingle(@NonNull MatomoRequest request) {
+ String authToken = AuthToken.determineAuthToken(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");
@@ -232,10 +241,8 @@ private void applySslConfiguration(
}
@Override
- public void sendBulk(
- @NonNull @lombok.NonNull Iterable extends MatomoRequest> requests, @Nullable String overrideAuthToken
- ) {
- String authToken = AuthToken.determineAuthToken(overrideAuthToken, requests, trackerConfiguration);
+ public void sendBulk(@NonNull @lombok.NonNull Iterable extends MatomoRequest> requests) {
+ String authToken = AuthToken.determineAuthToken(requests, trackerConfiguration);
Collection queries = new ArrayList<>();
Map headers = new LinkedHashMap<>();
String headerUserAgent = null;
@@ -246,10 +253,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 +275,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 +290,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 +323,13 @@ 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 extends MatomoRequest> requests, @Nullable String overrideAuthToken
- ) {
- String authToken = AuthToken.determineAuthToken(overrideAuthToken, requests, trackerConfiguration);
+ @NonNull Collection extends MatomoRequest> requests) {
+ String authToken = AuthToken.determineAuthToken(requests, trackerConfiguration);
Map headers = new LinkedHashMap<>();
String headerUserAgent = findHeaderUserAgent(requests);
String sessionId = findSessionId(requests);
@@ -337,8 +342,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 +354,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..05d38a72 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()));
+
+ 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()));
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..32ebe804 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.request()
+ .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())
+ .thenAccept(
+ request -> {
+ success.set(true);
+ });
+ assertThat(future)
+ .succeedsWithin(1, MINUTES)
+ .satisfies(
+ v -> {
+ wireMockServer.verify(getRequestedFor(urlPathEqualTo("/matomo.php")));
+ });
assertThat(success).isTrue();
}
@@ -513,13 +552,19 @@ 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()))
+ .thenAccept(
+ 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
deleted file mode 100644
index 523b9f4a..00000000
--- a/java8/src/test/java/org/matomo/java/tracking/PiwikTrackerIT.java
+++ /dev/null
@@ -1,255 +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/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 d28931b9..36806141 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
+ 4.0.1-SNAPSHOT
pom
Matomo Java Tracker Parent
@@ -37,21 +38,27 @@
+
+ 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/
+ central
+ https://central.sonatype.com/
@@ -62,8 +69,8 @@
1.8
1.8
${project.build.outputDirectory}/delombok
- 1.18.36
- 2.0.16
+ 1.18.46
+ 2.0.18
@@ -71,7 +78,7 @@
com.github.spotbugs
spotbugs-annotations
- 4.9.0
+ 4.9.8
provided
@@ -88,13 +95,13 @@
org.junit.jupiter
junit-jupiter
- 5.11.4
+ 6.1.0
test
org.assertj
assertj-core
- 3.27.3
+ 3.27.7
test
@@ -106,7 +113,7 @@
org.eclipse.jetty.ee10
jetty-ee10-servlet
- 12.0.16
+ 12.1.9
@@ -117,52 +124,52 @@
org.apache.maven.plugins
maven-compiler-plugin
- 3.13.0
+ 3.15.0
org.apache.maven.plugins
maven-project-info-reports-plugin
- 3.8.0
+ 3.9.0
org.apache.maven.plugins
maven-clean-plugin
- 3.4.0
+ 3.5.0
org.apache.maven.plugins
maven-deploy-plugin
- 3.1.3
+ 3.1.4
org.apache.maven.plugins
maven-install-plugin
- 3.1.3
+ 3.1.4
org.apache.maven.plugins
maven-jar-plugin
- 3.4.2
+ 3.5.0
org.apache.maven.plugins
maven-resources-plugin
- 3.3.1
+ 3.5.0
org.apache.maven.plugins
maven-site-plugin
- 3.21.0
+ 3.22.0
org.apache.maven.plugins
maven-surefire-plugin
- 3.5.2
+ 3.5.5
org.apache.maven.plugins
maven-release-plugin
- 3.1.1
+ 3.3.1
true
false
@@ -174,27 +181,42 @@
org.apache.maven.plugins
maven-gpg-plugin
- 3.2.7
+ 3.2.8
sign-artifacts
- verify
sign
+ verify
- 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
+
+
+
+ org.apache.maven.plugins
+ maven-javadoc-plugin
+ 3.12.0
+
+ ${delombok.output}
+ none
+
+
+ attach-javadocs
+
+ jar
+
+
+
@@ -202,7 +224,7 @@
org.apache.maven.plugins
maven-failsafe-plugin
- 3.5.2
+ 3.5.5
@@ -215,7 +237,7 @@
org.apache.maven.plugins
maven-source-plugin
- 3.3.1
+ 3.4.0
attach-sources
@@ -229,6 +251,11 @@
org.projectlombok
lombok-maven-plugin
1.18.20.0
+
+ src/main/java
+ ${delombok.output}
+ false
+
org.projectlombok
@@ -236,41 +263,19 @@
${lombok.version}
-
- src/main/java
- ${delombok.output}
- false
-
- generate-sources
delombok
-
-
-
-
- org.apache.maven.plugins
- maven-javadoc-plugin
- 3.11.2
-
- ${delombok.output}
- none
-
-
-
- attach-javadocs
-
- jar
-
+ generate-sources
org.apache.maven.plugins
maven-enforcer-plugin
- 3.5.0
+ 3.6.3
enforce-maven
@@ -290,29 +295,45 @@
org.jacoco
jacoco-maven-plugin
- 0.8.12
+ 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
@@ -342,28 +363,68 @@
-
- validate
-
check
+ validate
com.github.spotbugs
spotbugs-maven-plugin
- 4.8.6.6
+ 4.9.8.3
org.owasp
dependency-check-maven
- 12.0.2
+ 12.2.2
true
+
+ com.diffplug.spotless
+ spotless-maven-plugin
+ 3.5.1
+
+
+
+
+ 1.24.0
+
+ true
+ true
+
+
+
+
+ **/*.md
+
+
+
+
+
+ pom.xml
+ */pom.xml
+
+
+ false
+ true
+ 4
+
+
+
+
+
+ spotless-apply
+
+ apply
+
+ process-sources
+
+
+
@@ -377,21 +438,15 @@
maven-gpg-plugin
- org.sonatype.plugins
- nexus-staging-maven-plugin
+ org.apache.maven.plugins
+ maven-javadoc-plugin
+
+
+ org.sonatype.central
+ central-publishing-maven-plugin
-
-
- core
- java8
- java11
- servlet-jakarta
- servlet-javax
- spring
- test
-
diff --git a/servlet-jakarta/pom.xml b/servlet-jakarta/pom.xml
index 0c31328f..132f90f1 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
+ 4.0.1-SNAPSHOT
../pom.xml
matomo-java-tracker-servlet-jakarta
- 3.4.1-SNAPSHOT
+ 4.0.1-SNAPSHOT
jar
Matomo Java Tracker Servlet Jakarta
@@ -53,7 +54,7 @@
org.eclipse.jetty.ee10
jetty-ee10-servlet
- 12.0.16
+ 12.1.9
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..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;
@@ -11,8 +10,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
@@ -37,17 +37,14 @@ public void sendSingle(@NonNull MatomoRequest request) {
}
@Override
- public void sendBulk(
- @NonNull Iterable extends MatomoRequest> requests, @Nullable String overrideAuthToken
- ) {
+ public void sendBulk(@NonNull Iterable extends MatomoRequest> requests) {
throw new UnsupportedOperationException();
}
@NonNull
@Override
public CompletableFuture sendBulkAsync(
- @NonNull Collection extends MatomoRequest> requests, @Nullable String overrideAuthToken
- ) {
+ @NonNull Collection extends MatomoRequest> requests) {
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 26c169b5..2791103f 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
+ 4.0.1-SNAPSHOT
../pom.xml
matomo-java-tracker-servlet-javax
- 3.4.1-SNAPSHOT
+ 4.0.1-SNAPSHOT
jar
Matomo Java Tracker Servlet Javax
@@ -53,7 +54,7 @@
org.eclipse.jetty
jetty-servlet
- 11.0.0
+ 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..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;
@@ -11,8 +10,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
@@ -37,17 +37,14 @@ public void sendSingle(@NonNull MatomoRequest request) {
}
@Override
- public void sendBulk(
- @NonNull Iterable extends MatomoRequest> requests, @Nullable String overrideAuthToken
- ) {
+ public void sendBulk(@NonNull Iterable extends MatomoRequest> requests) {
throw new UnsupportedOperationException();
}
@NonNull
@Override
public CompletableFuture sendBulkAsync(
- @NonNull Collection extends MatomoRequest> requests, @Nullable String overrideAuthToken
- ) {
+ @NonNull Collection extends MatomoRequest> requests) {
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..47d5c833 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
+ 4.0.1-SNAPSHOT
../pom.xml
@@ -17,7 +18,7 @@
17
17
- 3.4.2
+ 4.0.6
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..77fcbc33 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
+ 4.0.1-SNAPSHOT
../pom.xml
@@ -46,7 +47,7 @@
org.eclipse.jetty.ee10
jetty-ee10-servlet
- 12.0.16
+ 12.1.9
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);
// ...
}
-
}