From 804e7e6e448470a59e366acb6461ff42f96bb94b Mon Sep 17 00:00:00 2001 From: Marvin Date: Sat, 15 Dec 2018 16:50:00 +0100 Subject: [PATCH 01/10] Update .gitignore to ignore more local files Signed-off-by: Marvin --- .gitignore | 232 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 224 insertions(+), 8 deletions(-) diff --git a/.gitignore b/.gitignore index 1221a76d..df2b6add 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,228 @@ -# General System Files # -*~ -*\.DS_Store -*#*# -*.swp -info +### Maven template +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +.mvn/wrapper/maven-wrapper.jar +### Java template +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ # Package Files # -**/target/ +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* +### Eclipse template + +.metadata +bin/ +tmp/ +*.tmp +*.bak +*~.nib +local.properties +.settings/ +.loadpath +.recommenders + +# External tool builders +.externalToolBuilders/ + +# Locally stored "Eclipse launch configurations" +*.launch + +# PyDev specific (Python IDE for Eclipse) +*.pydevproject + +# CDT-specific (C/C++ Development Tooling) +.cproject + +# CDT- autotools +.autotools + +# Java annotation processor (APT) +.factorypath + +# PDT-specific (PHP Development Tools) +.buildpath + +# sbteclipse plugin +.target + +# Tern plugin +.tern-project + +# TeXlipse plugin +.texlipse + +# STS (Spring Tool Suite) +.springBeans + +# Code Recommenders +.recommenders/ + +# Annotation Processing +.apt_generated/ + +# Scala IDE specific (Scala & Java development for Eclipse) +.cache-main +.scala_dependencies +.worksheet +### Kotlin template +# Compiled class file + +# Log file + +# BlueJ files + +# Mobile Tools for Java (J2ME) + +# Package Files # + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +### JetBrains template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/modules.xml +# .idea/*.iml +# .idea/modules + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests +### macOS template +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk +### Linux template +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* +### Windows template +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk From 7a8f13338f1440647ee2d798322cf6dedac4e5d9 Mon Sep 17 00:00:00 2001 From: Marvin Date: Sat, 15 Dec 2018 17:19:17 +0100 Subject: [PATCH 02/10] Remove runtime dependencies and fix the code up for modern Java Signed-off-by: Marvin --- pom.xml | 390 ++--- .../piwik/java/tracking/CustomVariable.java | 20 +- .../java/tracking/CustomVariableList.java | 45 +- .../piwik/java/tracking/EcommerceItem.java | 69 +- .../org/piwik/java/tracking/PiwikDate.java | 25 +- .../piwik/java/tracking/PiwikJsonArray.java | 45 +- .../piwik/java/tracking/PiwikJsonObject.java | 60 +- .../org/piwik/java/tracking/PiwikLocale.java | 26 +- .../org/piwik/java/tracking/PiwikRequest.java | 1438 +++++++++-------- .../org/piwik/java/tracking/PiwikTracker.java | 86 +- .../piwik/java/tracking/PiwikTrackerTest.java | 2 +- 11 files changed, 1186 insertions(+), 1020 deletions(-) diff --git a/pom.xml b/pom.xml index ec4a1136..a1c6c3c7 100644 --- a/pom.xml +++ b/pom.xml @@ -1,220 +1,182 @@ - - 4.0.0 - - org.piwik.java.tracking - piwik-java-tracker - 1.3-SNAPSHOT - jar - - Piwik Java Tracker - Official Java implementation of the Piwik Tracking HTTP API. - https://github.com/piwik/piwik-java-tracker - - - - BSD 3-Clause License - https://github.com/piwik/piwik-java-tracker/blob/master/LICENSE - - + + 4.0.0 - - - bcsorba - Brett Csorba - brett.csorba@gmail.com - - + org.piwik.java.tracking + piwik-java-tracker + 1.3-SNAPSHOT + jar - - scm:git@github.com:piwik/piwik-java-tracker.git - scm:git@github.com:piwik/piwik-java-tracker.git - git@github.com:piwik/piwik-java-tracker.git - + Piwik Java Tracker + Official Java implementation of the Piwik Tracking HTTP API. + + https://github.com/piwik/piwik-java-tracker - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - + + + BSD 3-Clause License + + https://github.com/piwik/piwik-java-tracker/blob/master/LICENSE + + + - - UTF-8 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.3 - - 1.7 - 1.7 - - - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - attach-javadocs - - jar - - - - - - org.pitest - pitest-maven - 1.1.7 - - - org.piwik.java.tracking* - - - org.piwik.java.tracking* - - - - - org.eluder.coveralls - coveralls-maven-plugin - 4.1.0 - - - org.jacoco - jacoco-maven-plugin - 0.7.5.201505241946 - - - prepare-agent - - prepare-agent - - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.6 - - - sign-artifacts - verify - - sign - - - - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.3 - true - - ossrh - https://oss.sonatype.org/ - false - - - - + + + bcsorba + Brett Csorba + brett.csorba@gmail.com + + - - - org.glassfish.hk2 - hk2-api - 2.4.0-b27 - runtime - - - org.glassfish.hk2 - hk2-locator - 2.4.0-b27 - runtime - - - org.glassfish.hk2 - hk2-utils - 2.4.0-b27 - runtime - - - org.apache.httpcomponents - httpclient - 4.4 - - - org.apache.httpcomponents - httpcore - 4.4 - - - org.glassfish.hk2.external - javax.inject - 2.4.0-b27 - runtime - - - org.glassfish.hk2.external - aopalliance-repackaged - 2.4.0-b27 - runtime - - - javaee - javaee-api - 5 - runtime - - - org.glassfish - javax.json - 1.0.4 - - - org.glassfish.jersey.core - jersey-common - 2.20 - - - org.glassfish.jersey.bundles.repackaged - jersey-guava - 2.20 - runtime - - - org.mockito - mockito-all - 1.9.5 - test - - - junit - junit - 4.10 - test - - + + scm:git@github.com:piwik/piwik-java-tracker.git + scm:git@github.com:piwik/piwik-java-tracker.git + + git@github.com:piwik/piwik-java-tracker.git + + + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + + + ossrh + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + + + + UTF-8 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-source-plugin + + + attach-sources + + jar + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + + + attach-javadocs + + jar + + + + + + org.pitest + pitest-maven + 1.4.3 + + + org.piwik.java.tracking* + + + org.piwik.java.tracking* + + + + + org.eluder.coveralls + coveralls-maven-plugin + 4.3.0 + + + org.jacoco + jacoco-maven-plugin + 0.8.2 + + + prepare-agent + + prepare-agent + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.6 + + + sign-artifacts + verify + + sign + + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.8 + true + + ossrh + https://oss.sonatype.org/ + false + + + + + + + + org.apache.httpcomponents + httpclient + 4.4 + compile + + + org.glassfish + javax.json + 1.0.4 + compile + + + javax.xml.bind + jaxb-api + 2.3.0 + compile + + + org.mockito + mockito-all + 1.9.5 + test + + + junit + junit + 4.12 + test + + diff --git a/src/main/java/org/piwik/java/tracking/CustomVariable.java b/src/main/java/org/piwik/java/tracking/CustomVariable.java index 9300ef62..134a6a3d 100644 --- a/src/main/java/org/piwik/java/tracking/CustomVariable.java +++ b/src/main/java/org/piwik/java/tracking/CustomVariable.java @@ -1,6 +1,6 @@ -/* +/* * Piwik Java Tracker - * + * * @link https://github.com/piwik/piwik-java-tracker * @license https://github.com/piwik/piwik-java-tracker/blob/master/LICENSE BSD-3 Clause */ @@ -8,22 +8,24 @@ /** * A user defined custom variable. + * * @author brettcsorba */ -public final class CustomVariable{ +public final class CustomVariable { private final String key; private final String value; - + /** * Create a new CustomVariable - * @param key the key of this CustomVariable + * + * @param key the key of this CustomVariable * @param value the value of this CustomVariable */ - public CustomVariable(String key, String value){ - if (key == null){ + public CustomVariable(String key, String value) { + if (key == null) { throw new NullPointerException("Key cannot be null."); } - if (value == null){ + if (value == null) { throw new NullPointerException("Value cannot be null."); } this.key = key; @@ -32,6 +34,7 @@ public CustomVariable(String key, String value){ /** * Get the key of this CustomVariable + * * @return the key of this CustomVariable */ public String getKey() { @@ -40,6 +43,7 @@ public String getKey() { /** * Get the value of this CustomVariable + * * @return the value of this CustomVariable */ public String getValue() { diff --git a/src/main/java/org/piwik/java/tracking/CustomVariableList.java b/src/main/java/org/piwik/java/tracking/CustomVariableList.java index 2392030c..7575b190 100644 --- a/src/main/java/org/piwik/java/tracking/CustomVariableList.java +++ b/src/main/java/org/piwik/java/tracking/CustomVariableList.java @@ -6,30 +6,29 @@ */ package org.piwik.java.tracking; +import javax.json.Json; +import javax.json.JsonArrayBuilder; +import javax.json.JsonObjectBuilder; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; -import javax.json.Json; -import javax.json.JsonArrayBuilder; -import javax.json.JsonObjectBuilder; /** - * * @author brettcsorba */ -class CustomVariableList{ +class CustomVariableList { private final Map map = new HashMap<>(); - void add(CustomVariable cv){ + void add(CustomVariable cv) { boolean found = false; - for (Entry entry : map.entrySet()){ - if (entry.getValue().getKey().equals(cv.getKey())){ + for (Entry entry : map.entrySet()) { + if (entry.getValue().getKey().equals(cv.getKey())) { map.put(entry.getKey(), cv); found = true; } } - if (!found){ + if (!found) { int i = 1; while (map.containsKey(i)) { ++i; @@ -39,54 +38,54 @@ void add(CustomVariable cv){ } } - void add(CustomVariable cv, int index){ - if (index <= 0){ + void add(CustomVariable cv, int index) { + if (index <= 0) { throw new IllegalArgumentException("Index must be greater than 0."); } map.put(index, cv); } - CustomVariable get(int index){ - if (index <= 0){ + CustomVariable get(int index) { + if (index <= 0) { throw new IllegalArgumentException("Index must be greater than 0."); } return map.get(index); } - String get(String key){ + String get(String key) { Iterator> i = map.entrySet().iterator(); - while (i.hasNext()){ + while (i.hasNext()) { CustomVariable value = i.next().getValue(); - if (value.getKey().equals(key)){ + if (value.getKey().equals(key)) { return value.getValue(); } } return null; } - void remove(int index){ + void remove(int index) { map.remove(index); } - void remove(String key){ + void remove(String key) { Iterator> i = map.entrySet().iterator(); - while (i.hasNext()){ + while (i.hasNext()) { Entry entry = i.next(); - if (entry.getValue().getKey().equals(key)){ + if (entry.getValue().getKey().equals(key)) { i.remove(); } } } - boolean isEmpty(){ + boolean isEmpty() { return map.isEmpty(); } @Override - public String toString(){ + public String toString() { JsonObjectBuilder ob = Json.createObjectBuilder(); - for (Entry entry : map.entrySet()){ + for (Entry entry : map.entrySet()) { JsonArrayBuilder ab = Json.createArrayBuilder(); ab.add(entry.getValue().getKey()); ab.add(entry.getValue().getValue()); diff --git a/src/main/java/org/piwik/java/tracking/EcommerceItem.java b/src/main/java/org/piwik/java/tracking/EcommerceItem.java index b8225311..01bda827 100644 --- a/src/main/java/org/piwik/java/tracking/EcommerceItem.java +++ b/src/main/java/org/piwik/java/tracking/EcommerceItem.java @@ -1,6 +1,6 @@ -/* +/* * Piwik Java Tracker - * + * * @link https://github.com/piwik/piwik-java-tracker * @license https://github.com/piwik/piwik-java-tracker/blob/master/LICENSE BSD-3 Clause */ @@ -13,26 +13,27 @@ /** * Represents an item in an ecommerce order. - * + * * @author brettcsorba */ -public class EcommerceItem implements JsonValue{ +public class EcommerceItem implements JsonValue { private String sku; private String name; private String category; private Double price; private Integer quantity; - + /** - * Construct an EcommerceItem from its sku, name, category, price, and + * Construct an EcommerceItem from its sku, name, category, price, and * quantity of the order. - * @param sku the item's sku - * @param name the item's name + * + * @param sku the item's sku + * @param name the item's name * @param category the item's category - * @param price the item's price + * @param price the item's price * @param quantity the quantity of this item in this order */ - public EcommerceItem(String sku, String name, String category, Double price, Integer quantity){ + public EcommerceItem(String sku, String name, String category, Double price, Integer quantity) { this.sku = sku; this.name = name; this.category = category; @@ -42,113 +43,127 @@ public EcommerceItem(String sku, String name, String category, Double price, Int /** * Get an item's sku. + * * @return the item's sku */ - public String getSku(){ + public String getSku() { return sku; } /** * Set an item's sku. + * * @param sku the sku to set */ - public void setSku(String sku){ + public void setSku(String sku) { this.sku = sku; } /** * Get an item's name. + * * @return the item's name */ - public String getName(){ + public String getName() { return name; } /** * Set an item's name. + * * @param name the name to set */ - public void setName(String name){ + public void setName(String name) { this.name = name; } /** * Get an item's category. + * * @return an item's category */ - public String getCategory(){ + public String getCategory() { return category; } /** * Set an item's category. + * * @param category the category to set */ - public void setCategory(String category){ + public void setCategory(String category) { this.category = category; } /** * Get an item's price. + * * @return an item's price */ - public Double getPrice(){ + public Double getPrice() { return price; } /** * Set an item's price. + * * @param price the price to set */ - public void setPrice(Double price){ + public void setPrice(Double price) { this.price = price; } /** * Get the quantity of this item in this order. + * * @return the quantity of this item in the order */ - public Integer getQuantity(){ + public Integer getQuantity() { return quantity; } /** * Set the quantity of this item in this order + * * @param quantity the quantity of this item to set */ - public void setQuantity(Integer quantity){ + public void setQuantity(Integer quantity) { this.quantity = quantity; } - + /** * Get the JSON value type of EcommerceItem. + * * @return ValueType.ARRAY */ @Override - public ValueType getValueType(){ + public ValueType getValueType() { return ValueType.ARRAY; } - + /** * Returns the value of this EcommerceItem as a JSON Array string. + * * @return this as a JSON array string */ @Override - public String toString(){ + public String toString() { return toJsonArray().toString(); } + /** * Returns the value of this EcommerceItem as a JsonArray. + * * @return this as a JsonArray */ - JsonArray toJsonArray(){ + JsonArray toJsonArray() { JsonArrayBuilder ab = Json.createArrayBuilder(); ab.add(sku); ab.add(name); ab.add(category); ab.add(price); ab.add(quantity); - - return ab.build(); + + return ab.build(); } } diff --git a/src/main/java/org/piwik/java/tracking/PiwikDate.java b/src/main/java/org/piwik/java/tracking/PiwikDate.java index bb10053e..6aa913f8 100644 --- a/src/main/java/org/piwik/java/tracking/PiwikDate.java +++ b/src/main/java/org/piwik/java/tracking/PiwikDate.java @@ -1,6 +1,6 @@ -/* +/* * Piwik Java Tracker - * + * * @link https://github.com/piwik/piwik-java-tracker * @license https://github.com/piwik/piwik-java-tracker/blob/master/LICENSE BSD-3 Clause */ @@ -12,17 +12,17 @@ /** * A datetime object that will return the datetime in the format {@code yyyy-MM-dd hh:mm:ss}. - * + * * @author brettcsorba */ -public class PiwikDate extends Date{ +public class PiwikDate extends Date { SimpleDateFormat format; - + /** * Allocates a Date object and initializes it so that it represents the time * at which it was allocated, measured to the nearest millisecond. */ - public PiwikDate(){ + public PiwikDate() { super(); format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); format.setTimeZone(TimeZone.getTimeZone("UTC")); @@ -32,31 +32,34 @@ public PiwikDate(){ * 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 date the milliseconds since January 1, 1970, 00:00:00 GMT. */ - public PiwikDate(long date){ + public PiwikDate(long date) { super(date); format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); format.setTimeZone(TimeZone.getTimeZone("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(TimeZone zone){ + public void setTimeZone(TimeZone zone) { format.setTimeZone(zone); } - + /** * Converts this PiwikDate object to a String of the form:
*
* {@code yyyy-MM-dd hh:mm:ss}. + * * @return a string representation of this PiwikDate */ @Override - public String toString(){ + public String toString() { return format.format(this); } } diff --git a/src/main/java/org/piwik/java/tracking/PiwikJsonArray.java b/src/main/java/org/piwik/java/tracking/PiwikJsonArray.java index 01177c43..de741181 100644 --- a/src/main/java/org/piwik/java/tracking/PiwikJsonArray.java +++ b/src/main/java/org/piwik/java/tracking/PiwikJsonArray.java @@ -1,69 +1,72 @@ -/* +/* * Piwik Java Tracker - * + * * @link https://github.com/piwik/piwik-java-tracker * @license https://github.com/piwik/piwik-java-tracker/blob/master/LICENSE BSD-3 Clause */ package org.piwik.java.tracking; -import java.util.ArrayList; -import java.util.List; import javax.json.Json; import javax.json.JsonArrayBuilder; import javax.json.JsonValue; +import java.util.ArrayList; +import java.util.List; /** * Object representing a JSON array required by some Piwik query parameters. - * + * * @author brettcsorba */ -public class PiwikJsonArray{ +public class PiwikJsonArray { List list = new ArrayList<>(); - + /** * Get the value stored at the specified index. + * * @param index the index of the value to return * @return the value stored at the specified index */ - public JsonValue get(int index){ + public JsonValue get(int index) { return list.get(index); } - + /** * Add a value to the end of this array. + * * @param value value to add to the end of the array */ - public void add(JsonValue value){ + public void add(JsonValue value) { list.add(value); } - + /** * Set the value at the specified index to the specified value. + * * @param index the index of the value to set * @param value the value to set at the specified index */ - public void set(int index, JsonValue value){ + public void set(int index, JsonValue value) { list.set(index, value); } - + /** * Returns a JSON encoded array string representing this object. + * * @return returns the current array as a JSON encode string */ @Override - public String toString(){ + public String toString() { JsonArrayBuilder ab = Json.createArrayBuilder(); - - for (int x = 0; x < list.size(); ++x){ + + for (int x = 0; x < list.size(); ++x) { JsonValue value = list.get(x); - if (value instanceof EcommerceItem){ - ab.add(((EcommerceItem)value).toJsonArray()); - } - else{ + if (value instanceof EcommerceItem) { + ab.add(((EcommerceItem) value).toJsonArray()); + } else { ab.add(value); } } - + return ab.build().toString(); } } diff --git a/src/main/java/org/piwik/java/tracking/PiwikJsonObject.java b/src/main/java/org/piwik/java/tracking/PiwikJsonObject.java index 505a3dde..f09bab32 100644 --- a/src/main/java/org/piwik/java/tracking/PiwikJsonObject.java +++ b/src/main/java/org/piwik/java/tracking/PiwikJsonObject.java @@ -1,74 +1,79 @@ -/* +/* * Piwik Java Tracker - * + * * @link https://github.com/piwik/piwik-java-tracker * @license https://github.com/piwik/piwik-java-tracker/blob/master/LICENSE BSD-3 Clause */ package org.piwik.java.tracking; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; import javax.json.Json; import javax.json.JsonArrayBuilder; import javax.json.JsonObjectBuilder; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Map.Entry; /** - * Object representing the custom variable array required by some + * Object representing the custom variable array required by some * Piwik query parameters. An array is represented by an object that has - * the index of the entry as the key (1 indexed) and a 2 entry array representing + * the index of the entry as the key (1 indexed) and a 2 entry array representing * a custom key and custom value as the value. - * + * * @author brettcsorba */ @Deprecated -public class PiwikJsonObject{ +public class PiwikJsonObject { Map map = new LinkedHashMap<>(); - + /** * Gets the custom value stored at this custom key. + * * @param key key used to lookup value * @return value stored at specified key, null if not present */ - public String get(String key){ + public String get(String key) { return map.get(key); } - + /** * Returns true if this object contains no custom key-value pairs. + * * @return true if this object contains no custom key-value pairs */ - public boolean isEmpty(){ + public boolean isEmpty() { return size() == 0; } - + /** * Puts a custom value at this custom key. - * @param key key to store value at + * + * @param key key to store value at * @param value value to store at specified key * @return previous value stored at key if present, null otherwise */ - public String put(String key, String value){ + public String put(String key, String value) { return map.put(key, value); } - + /** * Removes the custom value stored at this custom key. + * * @param key key used to lookup value to remove * @return the value that was removed, null if no value was there to remove */ - public String remove(String key){ + public String remove(String key) { return map.remove(key); } - - /** + + /** * Returns the number of custom key-value pairs. + * * @return the number of custom key-value pairs */ - public int size(){ + public int size() { return map.size(); } - + /** * Produces the JSON string representing this object.
*
@@ -90,22 +95,23 @@ public int size(){ *
* {@code {"1": ["key1", "value1"], "2": ["key3": "value3"]} }
*
- * would be produced. + * would be produced. *
+ * * @return the JSON string representation of this object */ @Override - public String toString(){ + public String toString() { JsonObjectBuilder ob = Json.createObjectBuilder(); - + int x = 1; - for (Entry entry : map.entrySet()){ + for (Entry entry : map.entrySet()) { JsonArrayBuilder ab = Json.createArrayBuilder(); ab.add(entry.getKey()); ab.add(entry.getValue()); ob.add(Integer.toString(x++), ab); } - + return ob.build().toString(); } } diff --git a/src/main/java/org/piwik/java/tracking/PiwikLocale.java b/src/main/java/org/piwik/java/tracking/PiwikLocale.java index 45f14338..e9a9307e 100644 --- a/src/main/java/org/piwik/java/tracking/PiwikLocale.java +++ b/src/main/java/org/piwik/java/tracking/PiwikLocale.java @@ -1,6 +1,6 @@ -/* +/* * Piwik Java Tracker - * + * * @link https://github.com/piwik/piwik-java-tracker * @license https://github.com/piwik/piwik-java-tracker/blob/master/LICENSE BSD-3 Clause */ @@ -10,42 +10,46 @@ /** * Object representing a locale required by some Piwik query parameters. - * + * * @author brettcsorba */ -public class PiwikLocale{ +public class PiwikLocale { private Locale locale; - + /** * Create this PiwikLocale from a Locale. + * * @param locale the locale to create this object from */ - public PiwikLocale(Locale locale){ + public PiwikLocale(Locale locale) { this.locale = locale; } /** * Gets the locale. + * * @return the locale */ - public Locale getLocale(){ + public Locale getLocale() { return locale; } /** * Sets the locale. + * * @param locale the locale to set */ - public void setLocale(Locale locale){ + public void setLocale(Locale locale) { this.locale = locale; } - + /** * Returns the locale's lowercase country code. + * * @return the locale's lowercase country code */ @Override - public String toString(){ + public String toString() { return locale.getCountry().toLowerCase(); - } + } } diff --git a/src/main/java/org/piwik/java/tracking/PiwikRequest.java b/src/main/java/org/piwik/java/tracking/PiwikRequest.java index bf27a70e..69237c3a 100644 --- a/src/main/java/org/piwik/java/tracking/PiwikRequest.java +++ b/src/main/java/org/piwik/java/tracking/PiwikRequest.java @@ -1,35 +1,31 @@ -/* +/* * Piwik Java Tracker - * + * * @link https://github.com/piwik/piwik-java-tracker * @license https://github.com/piwik/piwik-java-tracker/blob/master/LICENSE BSD-3 Clause */ package org.piwik.java.tracking; +import javax.json.JsonValue; +import javax.xml.bind.DatatypeConverter; +import javax.xml.bind.TypeConstraintException; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.Random; -import javax.json.JsonValue; -import javax.xml.bind.DatatypeConverter; -import javax.xml.bind.TypeConstraintException; /** * A class that implements the * Piwik Tracking HTTP API. These requests can be sent using {@link PiwikTracker}. + * * @author brettcsorba */ -public class PiwikRequest{ +public class PiwikRequest { public static final int ID_LENGTH = 16; public static final int AUTH_TOKEN_LENGTH = 32; - + private static final String ACTION_NAME = "action_name"; private static final String ACTION_TIME = "gt_ms"; private static final String ACTION_URL = "url"; @@ -98,13 +94,13 @@ public class PiwikRequest{ private static final String VISITOR_PREVIOUS_VISIT_TIMESTAMP = "_viewts"; private static final String VISITOR_REGION = "region"; private static final String VISITOR_VISIT_COUNT = "_idvc"; - + private static final int RANDOM_VALUE_LENGTH = 20; private static final long REQUEST_DATETIME_AUTH_LIMIT = 14400000L; - + private final Map parameters = new HashMap<>(); private final Map customTrackingParameters = new HashMap<>(); - + /** * Create a new request from the id of the site being tracked and the full * url for the current action. This constructor also sets: @@ -118,126 +114,150 @@ public class PiwikRequest{ * } * * Overwrite these values yourself as desired. - * @param siteId the id of the website we're tracking a visit/action for + * + * @param siteId the id of the website we're tracking a visit/action for * @param actionUrl the full URL for the current action */ - public PiwikRequest(Integer siteId, URL actionUrl){ + public PiwikRequest(Integer siteId, URL actionUrl) { setParameter(SITE_ID, siteId); setBooleanParameter(REQUIRED, true); setParameter(ACTION_URL, actionUrl); setParameter(VISITOR_ID, getRandomHexString(ID_LENGTH)); setParameter(RANDOM_VALUE, getRandomHexString(RANDOM_VALUE_LENGTH)); setParameter(API_VERSION, "1"); - setBooleanParameter(RESPONSE_AS_IMAGE, false); - } - + setBooleanParameter(RESPONSE_AS_IMAGE, false); + } + + /** + * Get a random hexadecimal string of a specified length. + * + * @param length length of the string to produce + * @return a random string consisting only of hexadecimal characters + */ + public static String getRandomHexString(int length) { + byte[] bytes = new byte[length / 2]; + new Random().nextBytes(bytes); + return DatatypeConverter.printHexBinary(bytes); + } + /** * Get the title of the action being tracked + * * @return the title of the action being tracked */ - - public String getActionName(){ - return (String)getParameter(ACTION_NAME); + + public String getActionName() { + return (String) getParameter(ACTION_NAME); } - + /** - * Set the title of the action being tracked. It is possible to - * use slashes / + * Set the title of the action being tracked. It is possible to + * use slashes / * to set one or several categories for this action. * For example, Help / Feedback * will create the Action Feedback in the category Help. * * @param actionName the title of the action to set. A null value will remove this parameter */ - public void setActionName(String actionName){ + public void setActionName(String actionName) { setParameter(ACTION_NAME, actionName); } - + /** * Get the amount of time it took the server to generate this action, in milliseconds. + * * @return the amount of time */ - public Long getActionTime(){ - return (Long)getParameter(ACTION_TIME); + public Long getActionTime() { + return (Long) getParameter(ACTION_TIME); } - + /** * Set the amount of time it took the server to generate this action, in milliseconds. - * This value is used to process the - * Page speed report + * This value is used to process the + * Page speed report * Avg. generation time column in the Page URL and Page Title reports, - * as well as a site wide running average of the speed of your server. + * as well as a site wide running average of the speed of your server. + * * @param actionTime the amount of time to set. A null value will remove this parameter */ - public void setActionTime(Long actionTime){ + public void setActionTime(Long actionTime) { setParameter(ACTION_TIME, actionTime); } - + /** * Get the full URL for the current action. + * * @return the full URL * @throws TypeConstraintException if the stored Action URL is a string */ - public URL getActionUrl(){ + public URL getActionUrl() { return returnAsUrl(ACTION_URL, "Action URL", "getActionUrlAsString"); } - + + /** + * Set the full URL for the current action. + * + * @param actionUrl the full URL to set. A null value will remove this parameter + */ + public void setActionUrl(URL actionUrl) { + setParameter(ACTION_URL, actionUrl); + } + /** * Get the full URL for the current action. + * * @return the full URL * @throws TypeConstraintException if the stored Action URL is a URL */ - public String getActionUrlAsString(){ + public String getActionUrlAsString() { return returnAsString(ACTION_URL, "Action URL", "getActionUrl"); } - - /** - * Set the full URL for the current action. - * @param actionUrl the full URL to set. A null value will remove this parameter - */ - public void setActionUrl(URL actionUrl){ - setParameter(ACTION_URL, actionUrl); - } - + /** * Set the full URL for the current action. + * * @param actionUrl the full URL to set. A null value will remove this parameter */ - public void setActionUrlWithString(String actionUrl){ + public void setActionUrlWithString(String actionUrl) { setParameter(ACTION_URL, actionUrl); } - + /** * Get the api version + * * @return the api version */ - public String getApiVersion(){ - return (String)getParameter(API_VERSION); + public String getApiVersion() { + return (String) getParameter(API_VERSION); } - + /** * Set the api version to use (currently always set to 1) + * * @param apiVersion the api version to set. A null value will remove this parameter */ - public void setApiVersion(String apiVersion){ + public void setApiVersion(String apiVersion) { setParameter(API_VERSION, apiVersion); } - + /** * Get the authorization key. + * * @return the authorization key */ - public String getAuthToken(){ - return (String)getParameter(AUTH_TOKEN); + public String getAuthToken() { + return (String) getParameter(AUTH_TOKEN); } - + /** * Set the {@value #AUTH_TOKEN_LENGTH} character authorization key used to authenticate the API request. + * * @param authToken the authorization key to set. A null value will remove this parameter */ - public void setAuthToken(String authToken){ - if (authToken != null && authToken.length() != AUTH_TOKEN_LENGTH){ - throw new IllegalArgumentException(authToken+" is not "+AUTH_TOKEN_LENGTH+" characters long."); + public void setAuthToken(String authToken) { + if (authToken != null && authToken.length() != AUTH_TOKEN_LENGTH) { + throw new IllegalArgumentException(authToken + " is not " + AUTH_TOKEN_LENGTH + " characters long."); } setParameter(AUTH_TOKEN, authToken); } @@ -246,1436 +266,1575 @@ public void setAuthToken(String authToken){ * Verifies that AuthToken has been set for this request. Will throw an * {@link IllegalStateException} if not. */ - public void verifyAuthTokenSet(){ - if (getAuthToken() == null){ + public void verifyAuthTokenSet() { + if (getAuthToken() == null) { throw new IllegalStateException("AuthToken must be set before this value can be set."); } } - + /** * Get the campaign keyword + * * @return the campaign keyword */ - public String getCampaignKeyword(){ - return (String)getParameter(CAMPAIGN_KEYWORD); + public String getCampaignKeyword() { + return (String) getParameter(CAMPAIGN_KEYWORD); } - + /** - * Set the Campaign Keyword (see - * Tracking Campaigns). - * Used to populate the Referrers > Campaigns report (clicking on a - * campaign loads all keywords for this campaign). Note: this parameter + * Set the Campaign Keyword (see + * Tracking Campaigns). + * Used to populate the Referrers > Campaigns report (clicking on a + * campaign loads all keywords for this campaign). Note: this parameter * will only be used for the first pageview of a visit. + * * @param campaignKeyword the campaign keyword to set. A null value will remove this parameter */ - public void setCampaignKeyword(String campaignKeyword){ + public void setCampaignKeyword(String campaignKeyword) { setParameter(CAMPAIGN_KEYWORD, campaignKeyword); } - + /** * Get the campaign name + * * @return the campaign name */ - public String getCampaignName(){ - return (String)getParameter(CAMPAIGN_NAME); + public String getCampaignName() { + return (String) getParameter(CAMPAIGN_NAME); } - + /** - * Set the Campaign Name (see - * Tracking Campaigns). - * Used to populate the Referrers > Campaigns report. Note: this parameter + * Set the Campaign Name (see + * Tracking Campaigns). + * Used to populate the Referrers > Campaigns report. Note: this parameter * will only be used for the first pageview of a visit. + * * @param campaignName the campaign name to set. A null value will remove this parameter */ - public void setCampaignName(String campaignName){ + public void setCampaignName(String campaignName) { setParameter(CAMPAIGN_NAME, campaignName); } - + /** * Get the charset of the page being tracked - * @return the charset + * + * @return the charset */ - public Charset getCharacterSet(){ - return (Charset)getParameter(CHARACTER_SET); + public Charset getCharacterSet() { + return (Charset) getParameter(CHARACTER_SET); } - + /** - * The charset of the page being tracked. Specify the charset if the data + * The charset of the page being tracked. Specify the charset if the data * you send to Piwik is encoded in a different character set than the default * utf-8. + * * @param characterSet the charset to set. A null value will remove this parameter */ - public void setCharacterSet(Charset characterSet){ + public void setCharacterSet(Charset characterSet) { setParameter(CHARACTER_SET, characterSet); } - + /** * Get the name of the interaction with the content + * * @return the name of the interaction */ - public String getContentInteraction(){ - return (String)getParameter(CONTENT_INTERACTION); + public String getContentInteraction() { + return (String) getParameter(CONTENT_INTERACTION); } - + /** * Set the name of the interaction with the content. For instance a 'click'. + * * @param contentInteraction the name of the interaction to set. A null value will remove this parameter */ - public void setContentInteraction(String contentInteraction){ + public void setContentInteraction(String contentInteraction) { setParameter(CONTENT_INTERACTION, contentInteraction); } - + /** * Get the name of the content + * * @return the name */ - public String getContentName(){ - return (String)getParameter(CONTENT_NAME); + public String getContentName() { + return (String) getParameter(CONTENT_NAME); } - + /** * Set the name of the content. For instance 'Ad Foo Bar'. + * * @param contentName the name to set. A null value will remove this parameter */ - public void setContentName(String contentName){ + public void setContentName(String contentName) { setParameter(CONTENT_NAME, contentName); } - + /** * Get the content piece. + * * @return the content piece. */ - public String getContentPiece(){ - return (String)getParameter(CONTENT_PIECE); + public String getContentPiece() { + return (String) getParameter(CONTENT_PIECE); } - + /** * Set the actual content piece. For instance the path to an image, video, audio, any text. + * * @param contentPiece the content piece to set. A null value will remove this parameter */ - public void setContentPiece(String contentPiece){ + public void setContentPiece(String contentPiece) { setParameter(CONTENT_PIECE, contentPiece); } - + /** * Get the content target + * * @return the target * @throws TypeConstraintException if the stored Content Target is a string */ - public URL getContentTarget(){ + public URL getContentTarget() { return returnAsUrl(CONTENT_TARGET, "Content Target", "getContentTargetAsString"); } - + + /** + * Set the target of the content. For instance the URL of a landing page. + * + * @param contentTarget the target to set. A null value will remove this parameter + */ + public void setContentTarget(URL contentTarget) { + setParameter(CONTENT_TARGET, contentTarget); + } + /** * Get the content target + * * @return the target * @throws TypeConstraintException if the stored Content Target is a URL */ - public String getContentTargetAsString(){ + public String getContentTargetAsString() { return returnAsString(CONTENT_TARGET, "Content Target", "getContentTarget"); } - - /** - * Set the target of the content. For instance the URL of a landing page. - * @param contentTarget the target to set. A null value will remove this parameter - */ - public void setContentTarget(URL contentTarget){ - setParameter(CONTENT_TARGET, contentTarget); - } - + /** * Set the target of the content. For instance the URL of a landing page. + * * @param contentTarget the target to set. A null value will remove this parameter */ - public void setContentTargetWithString(String contentTarget){ + public void setContentTargetWithString(String contentTarget) { setParameter(CONTENT_TARGET, contentTarget); } - + /** * Get the current hour. + * * @return the current hour */ - public Integer getCurrentHour(){ - return (Integer)getParameter(CURRENT_HOUR); + public Integer getCurrentHour() { + return (Integer) getParameter(CURRENT_HOUR); } - + /** * Set the current hour (local time). + * * @param currentHour the hour to set. A null value will remove this parameter */ - public void setCurrentHour(Integer currentHour){ + public void setCurrentHour(Integer currentHour) { setParameter(CURRENT_HOUR, currentHour); } - + /** * Get the current minute. + * * @return the current minute */ - public Integer getCurrentMinute(){ - return (Integer)getParameter(CURRENT_MINUTE); + public Integer getCurrentMinute() { + return (Integer) getParameter(CURRENT_MINUTE); } - + /** * Set the current minute (local time). + * * @param currentMinute the minute to set. A null value will remove this parameter */ - public void setCurrentMinute(Integer currentMinute){ + public void setCurrentMinute(Integer currentMinute) { setParameter(CURRENT_MINUTE, currentMinute); } - + /** * Get the current second + * * @return the current second */ - public Integer getCurrentSecond(){ - return (Integer)getParameter(CURRENT_SECOND); + public Integer getCurrentSecond() { + return (Integer) getParameter(CURRENT_SECOND); } - + /** * Set the current second (local time). + * * @param currentSecond the second to set. A null value will remove this parameter */ - public void setCurrentSecond(Integer currentSecond){ + public void setCurrentSecond(Integer currentSecond) { setParameter(CURRENT_SECOND, currentSecond); } - + /** * 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 list of objects currently stored at the specified key */ - public List getCustomTrackingParameter(String key){ - if (key == null){ + public List getCustomTrackingParameter(String key) { + if (key == null) { throw new NullPointerException("Key cannot be null."); } List l = customTrackingParameters.get(key); - if (l == null){ + if (l == null) { return new ArrayList(0); } return new ArrayList(l); } - + /** * Set a custom tracking parameter whose toString() value will be sent to * the Piwik server. These parameters are stored separately from named Piwik * parameters, meaning it is not possible to overwrite or clear named Piwik * parameters with this method. A custom parameter that has the same name * as a named Piwik parameter will be sent in addition to that named parameter. - * @param key the parameter's key. Cannot be null + * + * @param key the parameter's key. Cannot be null * @param value the parameter's value. Removes the parameter if null */ - public void setCustomTrackingParameter(String key, Object value){ - if (key == null){ + public void setCustomTrackingParameter(String key, Object value) { + if (key == null) { throw new NullPointerException("Key cannot be null."); } - if (value == null){ + if (value == null) { customTrackingParameters.remove(key); - } - else{ + } else { List l = new ArrayList(); l.add(value); customTrackingParameters.put(key, l); } } - + /** * Add a custom tracking parameter to the specified key. This allows users * to have multiple parameters with the same name and different values, * commonly used during situations where list parameters are needed - * @param key the parameter's key. Cannot be null + * + * @param key the parameter's key. Cannot be null * @param value the parameter's value. Cannot be null */ - public void addCustomTrackingParameter(String key, Object value){ - if (key == null){ + public void addCustomTrackingParameter(String key, Object value) { + if (key == null) { throw new NullPointerException("Key cannot be null."); } - if (value == null){ + if (value == null) { throw new NullPointerException("Cannot add a null custom tracking parameter."); - } - else{ + } else { List l = customTrackingParameters.get(key); - if (l == null){ + if (l == null) { l = new ArrayList(); - customTrackingParameters.put(key, l); + customTrackingParameters.put(key, l); } l.add(value); } } - + /** * Removes all custom tracking parameters */ - public void clearCustomTrackingParameter(){ + public void clearCustomTrackingParameter() { customTrackingParameters.clear(); } - + /** * Get the resolution of the device + * * @return the resolution */ - public String getDeviceResolution(){ - return (String)getParameter(DEVICE_RESOLUTION); + public String getDeviceResolution() { + return (String) getParameter(DEVICE_RESOLUTION); } - + /** * Set the resolution of the device the visitor is using, eg 1280x1024. + * * @param deviceResolution the resolution to set. A null value will remove this parameter */ - public void setDeviceResolution(String deviceResolution){ + public void setDeviceResolution(String deviceResolution) { setParameter(DEVICE_RESOLUTION, deviceResolution); } - + /** * Get the url of a file the user had downloaded + * * @return the url * @throws TypeConstraintException if the stored Download URL is a String */ - public URL getDownloadUrl(){ + public URL getDownloadUrl() { return returnAsUrl(DOWNLOAD_URL, "Download URL", "getDownloadUrlAsString"); } - - /** - * Get the url of a file the user had downloaded - * @return the url - * @throws TypeConstraintException if the stored Download URL is a URL - */ - public String getDownloadUrlAsString(){ - return returnAsString(DOWNLOAD_URL, "Download URL", "getDownloadUrl"); - } - + /** * Set the url of a file the user has downloaded. Used for tracking downloads. * We recommend to also set the url parameter to this same value. + * * @param downloadUrl the url to set. A null value will remove this parameter */ - public void setDownloadUrl(URL downloadUrl){ + public void setDownloadUrl(URL downloadUrl) { setParameter(DOWNLOAD_URL, downloadUrl); } - + + /** + * Get the url of a file the user had downloaded + * + * @return the url + * @throws TypeConstraintException if the stored Download URL is a URL + */ + public String getDownloadUrlAsString() { + return returnAsString(DOWNLOAD_URL, "Download URL", "getDownloadUrl"); + } + /** * Set the url of a file the user has downloaded. Used for tracking downloads. * We recommend to also set the url parameter to this same value. + * * @param downloadUrl the url to set. A null value will remove this parameter */ - public void setDownloadUrlWithString(String downloadUrl){ + public void setDownloadUrlWithString(String downloadUrl) { setParameter(DOWNLOAD_URL, downloadUrl); } - + /** - * Sets idgoal=0 in the request to track an ecommerce interaction: + * Sets idgoal=0 in the request to track an ecommerce interaction: * cart update or an ecommerce order. */ - public void enableEcommerce(){ + public void enableEcommerce() { setGoalId(0); } - + /** * Verifies that Ecommerce has been enabled for the request. Will throw an * {@link IllegalStateException} if not. */ - public void verifyEcommerceEnabled(){ - if (getGoalId() == null || getGoalId() != 0){ + public void verifyEcommerceEnabled() { + if (getGoalId() == null || getGoalId() != 0) { throw new IllegalStateException("GoalId must be \"0\". Try calling enableEcommerce first before calling this method."); } } - + /** - * Verifies that Ecommerce has been enabled and that Ecommerce Id and + * Verifies that Ecommerce has been enabled and that Ecommerce Id and * Ecommerce Revenue have been set for the request. Will throw an * {@link IllegalStateException} if not. - * */ - public void verifyEcommerceState(){ + public void verifyEcommerceState() { verifyEcommerceEnabled(); - if (getEcommerceId() == null){ + if (getEcommerceId() == null) { throw new IllegalStateException("EcommerceId must be set before this value can be set."); } - if (getEcommerceRevenue() == null){ + if (getEcommerceRevenue() == null) { throw new IllegalStateException("EcommerceRevenue must be set before this value can be set."); } } - + /** * Get the discount offered. + * * @return the discount */ - public Double getEcommerceDiscount(){ - return (Double)getParameter(ECOMMERCE_DISCOUNT); + public Double getEcommerceDiscount() { + return (Double) getParameter(ECOMMERCE_DISCOUNT); } - + /** * Set the discount offered. Ecommerce must be enabled, and EcommerceId and * EcommerceRevenue must first be set. + * * @param discount the discount to set. A null value will remove this parameter */ - public void setEcommerceDiscount(Double discount){ - if (discount != null){ + public void setEcommerceDiscount(Double discount) { + if (discount != null) { verifyEcommerceState(); } setParameter(ECOMMERCE_DISCOUNT, discount); } - + /** * Get the id of this order. + * * @return the id */ - public String getEcommerceId(){ - return (String)getParameter(ECOMMERCE_ID); + public String getEcommerceId() { + return (String) getParameter(ECOMMERCE_ID); } - + /** - * Set the unique string identifier for the ecommerce order (required when + * Set the unique string identifier for the ecommerce order (required when * tracking an ecommerce order). Ecommerce must be enabled. + * * @param id the id to set. A null value will remove this parameter */ - public void setEcommerceId(String id){ - if (id != null){ + public void setEcommerceId(String id) { + if (id != null) { verifyEcommerceEnabled(); } setParameter(ECOMMERCE_ID, id); } - + /** * 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 */ - public EcommerceItem getEcommerceItem(int index){ - return (EcommerceItem)getFromJsonArray(ECOMMERCE_ITEMS, index); + public EcommerceItem getEcommerceItem(int index) { + return (EcommerceItem) getFromJsonArray(ECOMMERCE_ITEMS, 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 */ - public void addEcommerceItem(EcommerceItem item){ - if (item != null){ + public void addEcommerceItem(EcommerceItem item) { + if (item != null) { verifyEcommerceState(); } addToJsonArray(ECOMMERCE_ITEMS, item); } - + /** * Clears all {@link EcommerceItem} from this order. */ - public void clearEcommerceItems(){ + public void clearEcommerceItems() { removeJsonArray(ECOMMERCE_ITEMS); } - + /** * Get the timestamp of the customer's last ecommerce order + * * @return the timestamp */ - public Long getEcommerceLastOrderTimestamp(){ - return (Long)getParameter(ECOMMERCE_LAST_ORDER_TIMESTAMP); + public Long getEcommerceLastOrderTimestamp() { + return (Long) getParameter(ECOMMERCE_LAST_ORDER_TIMESTAMP); } - + /** * Set the UNUX timestamp of this customer's last ecommerce order. This value * is used to process the "Days since last order" report. Ecommerce must be * enabled, and EcommerceId and EcommerceRevenue must first be set. + * * @param timestamp the timestamp to set. A null value will remove this parameter */ - public void setEcommerceLastOrderTimestamp(Long timestamp){ - if (timestamp != null){ + public void setEcommerceLastOrderTimestamp(Long timestamp) { + if (timestamp != null) { verifyEcommerceState(); } setParameter(ECOMMERCE_LAST_ORDER_TIMESTAMP, timestamp); } - + /** * Get the grand total of the ecommerce order. + * * @return the grand total */ - public Double getEcommerceRevenue(){ - return (Double)getParameter(ECOMMERCE_REVENUE); + public Double getEcommerceRevenue() { + return (Double) getParameter(ECOMMERCE_REVENUE); } - + /** - * Set the grand total of the ecommerce order (required when tracking an + * Set the grand total of the ecommerce order (required when tracking an * ecommerce order). Ecommerce must be enabled. + * * @param revenue the grand total to set. A null value will remove this parameter */ - public void setEcommerceRevenue(Double revenue){ - if (revenue != null){ + public void setEcommerceRevenue(Double revenue) { + if (revenue != null) { verifyEcommerceEnabled(); } setParameter(ECOMMERCE_REVENUE, revenue); } - + /** * Get the shipping cost of the ecommerce order. + * * @return the shipping cost */ - public Double getEcommerceShippingCost(){ - return (Double)getParameter(ECOMMERCE_SHIPPING_COST); + public Double getEcommerceShippingCost() { + return (Double) getParameter(ECOMMERCE_SHIPPING_COST); } - + /** - * Set the shipping cost of the ecommerce order. Ecommerce must be enabled, + * Set the shipping cost of the ecommerce order. Ecommerce must be enabled, * and EcommerceId and EcommerceRevenue must first be set. + * * @param shippingCost the shipping cost to set. A null value will remove this parameter */ - public void setEcommerceShippingCost(Double shippingCost){ - if (shippingCost != null){ + public void setEcommerceShippingCost(Double shippingCost) { + if (shippingCost != null) { verifyEcommerceState(); } setParameter(ECOMMERCE_SHIPPING_COST, shippingCost); } - + /** * Get the subtotal of the ecommerce order; excludes shipping. + * * @return the subtotal */ - public Double getEcommerceSubtotal(){ - return (Double)getParameter(ECOMMERCE_SUBTOTAL); + public Double getEcommerceSubtotal() { + return (Double) getParameter(ECOMMERCE_SUBTOTAL); } - + /** - * Set the subtotal of the ecommerce order; excludes shipping. Ecommerce + * Set the subtotal of the ecommerce order; excludes shipping. Ecommerce * must be enabled and EcommerceId and EcommerceRevenue must first be set. + * * @param subtotal the subtotal to set. A null value will remove this parameter */ - public void setEcommerceSubtotal(Double subtotal){ - if (subtotal != null){ + public void setEcommerceSubtotal(Double subtotal) { + if (subtotal != null) { verifyEcommerceState(); } setParameter(ECOMMERCE_SUBTOTAL, subtotal); } - + /** * Get the tax amount of the ecommerce order. + * * @return the tax amount */ - public Double getEcommerceTax(){ - return (Double)getParameter(ECOMMERCE_TAX); + public Double getEcommerceTax() { + return (Double) getParameter(ECOMMERCE_TAX); } - + /** * Set the tax amount of the ecommerce order. Ecommerce must be enabled, and * EcommerceId and EcommerceRevenue must first be set. + * * @param tax the tax amount to set. A null value will remove this parameter */ - public void setEcommerceTax(Double tax){ - if (tax != null){ + public void setEcommerceTax(Double tax) { + if (tax != null) { verifyEcommerceState(); } setParameter(ECOMMERCE_TAX, tax); } - + /** * Get the event action. + * * @return the event action */ - public String getEventAction(){ + public String getEventAction() { return getNonEmptyStringParameter(EVENT_ACTION); } - + /** - * Set the event action. Must not be empty. (eg. Play, Pause, Duration, + * Set the event action. Must not be empty. (eg. Play, Pause, Duration, * Add Playlist, Downloaded, Clicked...). + * * @param eventAction the event action to set. A null value will remove this parameter */ - public void setEventAction(String eventAction){ + public void setEventAction(String eventAction) { setNonEmptyStringParameter(EVENT_ACTION, eventAction); } - + /** * Get the event category. + * * @return the event category */ - public String getEventCategory(){ + public String getEventCategory() { return getNonEmptyStringParameter(EVENT_CATEGORY); } - + /** * Set the event category. Must not be empty. (eg. Videos, Music, Games...). + * * @param eventCategory the event category to set. A null value will remove this parameter */ - public void setEventCategory(String eventCategory){ + public void setEventCategory(String eventCategory) { setNonEmptyStringParameter(EVENT_CATEGORY, eventCategory); } - + /** * Get the event name. + * * @return the event name */ - public String getEventName(){ - return (String)getParameter(EVENT_NAME); + public String getEventName() { + return (String) getParameter(EVENT_NAME); } - + /** * Set the event name. (eg. a Movie name, or Song name, or File name...). + * * @param eventName the event name to set. A null value will remove this parameter */ - public void setEventName(String eventName){ + public void setEventName(String eventName) { setParameter(EVENT_NAME, eventName); } - + /** * Get the event value. + * * @return the event value */ - public Number getEventValue(){ - return (Number)getParameter(EVENT_VALUE); + public Number getEventValue() { + return (Number) getParameter(EVENT_VALUE); } - + /** * Set the event value. Must be a float or integer value (numeric), not a string. + * * @param eventValue the event value to set. A null value will remove this parameter */ - public void setEventValue(Number eventValue){ + public void setEventValue(Number eventValue) { setParameter(EVENT_VALUE, eventValue); } - + /** * Get the goal id + * * @return the goal id */ - public Integer getGoalId(){ - return (Integer)getParameter(GOAL_ID); + public Integer getGoalId() { + return (Integer) getParameter(GOAL_ID); } - + /** - * Set the goal id. If specified, the tracking request will trigger a + * Set the goal id. If specified, the tracking request will trigger a * conversion for the goal of the website being tracked with this id. + * * @param goalId the goal id to set. A null value will remove this parameter */ - public void setGoalId(Integer goalId){ + public void setGoalId(Integer goalId) { setParameter(GOAL_ID, goalId); } - + /** * Get the goal revenue. + * * @return the goal revenue */ - public Double getGoalRevenue(){ - return (Double)getParameter(GOAL_REVENUE); + public Double getGoalRevenue() { + return (Double) getParameter(GOAL_REVENUE); } - + /** * Set a monetary value that was generated as revenue by this goal conversion. * Only used if idgoal is specified in the request. + * * @param goalRevenue the goal revenue to set. A null value will remove this parameter */ - public void setGoalRevenue(Double goalRevenue){ - if (goalRevenue != null && getGoalId() == null){ + public void setGoalRevenue(Double goalRevenue) { + if (goalRevenue != null && getGoalId() == null) { throw new IllegalStateException("GoalId must be set before GoalRevenue can be set."); } setParameter(GOAL_REVENUE, goalRevenue); } - + /** * Get the Accept-Language HTTP header + * * @return the Accept-Language HTTP header */ - public String getHeaderAcceptLanguage(){ - return (String)getParameter(HEADER_ACCEPT_LANGUAGE); + public String getHeaderAcceptLanguage() { + return (String) getParameter(HEADER_ACCEPT_LANGUAGE); } - + /** * Set an override value for the Accept-Language HTTP header - * field. This value is used to detect the visitor's country if + * field. This value is used to detect the visitor's country if * GeoIP is not enabled. + * * @param acceptLangage the Accept-Language HTTP header to set. A null value will remove this parameter */ - public void setHeaderAcceptLanguage(String acceptLangage){ + public void setHeaderAcceptLanguage(String acceptLangage) { setParameter(HEADER_ACCEPT_LANGUAGE, acceptLangage); } - + /** * Get the User-Agent HTTP header + * * @return the User-Agent HTTP header */ - public String getHeaderUserAgent(){ - return (String)getParameter(HEADER_USER_AGENT); + public String getHeaderUserAgent() { + return (String) getParameter(HEADER_USER_AGENT); } - + /** * Set an override value for the User-Agent HTTP header field. * The user agent is used to detect the operating system and browser used. + * * @param userAgent the User-Agent HTTP header tos et */ - public void setHeaderUserAgent(String userAgent){ + public void setHeaderUserAgent(String userAgent) { setParameter(HEADER_USER_AGENT, userAgent); } - + /** * Get if this request will force a new visit. + * * @return true if this request will force a new visit */ - public Boolean getNewVisit(){ + public Boolean getNewVisit() { return getBooleanParameter(NEW_VISIT); } - + /** * If set to true, will force a new visit to be created for this action. + * * @param newVisit if this request will force a new visit */ - public void setNewVisit(Boolean newVisit){ + public void setNewVisit(Boolean newVisit) { setBooleanParameter(NEW_VISIT, newVisit); } - + /** * Get the outlink url + * * @return the outlink url * @throws TypeConstraintException if the stored Outlink URL is a String */ - public URL getOutlinkUrl(){ - return returnAsUrl(OUTLINK_URL, "Outlink URL", "getOutlinkUrlAsString"); - } - - /** - * Get the outlink url - * @return the outlink url - * @throws TypeConstraintException if the stored Outlink URL is a URL - */ - public String getOutlinkUrlAsString(){ - return returnAsString(OUTLINK_URL, "Outlink URL", "getOutlinkUrl"); + public URL getOutlinkUrl() { + return returnAsUrl(OUTLINK_URL, "Outlink URL", "getOutlinkUrlAsString"); } - + /** * Set an external URL the user has opened. Used for tracking outlink clicks. * We recommend to also set the url parameter to this same value. + * * @param outlinkUrl the outlink url to set. A null value will remove this parameter */ - public void setOutlinkUrl(URL outlinkUrl){ + public void setOutlinkUrl(URL outlinkUrl) { setParameter(OUTLINK_URL, outlinkUrl); } - + + /** + * Get the outlink url + * + * @return the outlink url + * @throws TypeConstraintException if the stored Outlink URL is a URL + */ + public String getOutlinkUrlAsString() { + return returnAsString(OUTLINK_URL, "Outlink URL", "getOutlinkUrl"); + } + /** * Set an external URL the user has opened. Used for tracking outlink clicks. * We recommend to also set the url parameter to this same value. + * * @param outlinkUrl the outlink url to set. A null value will remove this parameter */ - public void setOutlinkUrlWithString(String outlinkUrl){ + public void setOutlinkUrlWithString(String outlinkUrl) { setParameter(OUTLINK_URL, outlinkUrl); } - + /** * 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 #getPageCustomVariable(int)} method instead. */ @Deprecated - public String getPageCustomVariable(String key){ + public String getPageCustomVariable(String key) { return getCustomVariable(PAGE_CUSTOM_VARIABLE, 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 */ - public CustomVariable getPageCustomVariable(int index){ + public CustomVariable getPageCustomVariable(int index) { return getCustomVariable(PAGE_CUSTOM_VARIABLE, 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 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 the {@link #setPageCustomVariable(CustomVariable, int)} method instead. */ @Deprecated - public void setPageCustomVariable(String key, String value){ - if (value == null){ + public void setPageCustomVariable(String key, String value) { + if (value == null) { removeCustomVariable(PAGE_CUSTOM_VARIABLE, key); } else { setCustomVariable(PAGE_CUSTOM_VARIABLE, new CustomVariable(key, value), null); } } - + /** * Set a page custom variable at the specified index. + * * @param customVariable the CustomVariable to set. A null value will remove the CustomVariable at the specified index - * @param index the index of he CustomVariable to set + * @param index the index of he CustomVariable to set */ - public void setPageCustomVariable(CustomVariable customVariable, int index){ + public void setPageCustomVariable(CustomVariable customVariable, int index) { setCustomVariable(PAGE_CUSTOM_VARIABLE, customVariable, index); } - + /** * Check if the visitor has the Director plugin. + * * @return true if visitor has the Director plugin */ - public Boolean getPluginDirector(){ + public Boolean getPluginDirector() { return getBooleanParameter(PLUGIN_DIRECTOR); } - + /** * Set if the visitor has the Director plugin. + * * @param director true if the visitor has the Director plugin */ - public void setPluginDirector(Boolean director){ + public void setPluginDirector(Boolean director) { setBooleanParameter(PLUGIN_DIRECTOR, director); } - + /** * Check if the visitor has the Flash plugin. + * * @return true if the visitor has the Flash plugin */ - public Boolean getPluginFlash(){ + public Boolean getPluginFlash() { return getBooleanParameter(PLUGIN_FLASH); } - + /** * Set if the visitor has the Flash plugin. + * * @param flash true if the visitor has the Flash plugin */ - public void setPluginFlash(Boolean flash){ + public void setPluginFlash(Boolean flash) { setBooleanParameter(PLUGIN_FLASH, flash); } - + /** * Check if the visitor has the Gears plugin. + * * @return true if the visitor has the Gears plugin */ - public Boolean getPluginGears(){ + public Boolean getPluginGears() { return getBooleanParameter(PLUGIN_GEARS); } - + /** * Set if the visitor has the Gears plugin. + * * @param gears true if the visitor has the Gears plugin */ - public void setPluginGears(Boolean gears){ + public void setPluginGears(Boolean gears) { setBooleanParameter(PLUGIN_GEARS, gears); } - + /** * Check if the visitor has the Java plugin. + * * @return true if the visitor has the Java plugin */ - public Boolean getPluginJava(){ + public Boolean getPluginJava() { return getBooleanParameter(PLUGIN_JAVA); } - + /** * Set if the visitor has the Java plugin. + * * @param java true if the visitor has the Java plugin */ - public void setPluginJava(Boolean java){ + public void setPluginJava(Boolean java) { setBooleanParameter(PLUGIN_JAVA, java); } - + /** * Check if the visitor has the PDF plugin. + * * @return true if the visitor has the PDF plugin */ - public Boolean getPluginPDF(){ + public Boolean getPluginPDF() { return getBooleanParameter(PLUGIN_PDF); } - + /** * Set if the visitor has the PDF plugin. + * * @param pdf true if the visitor has the PDF plugin */ - public void setPluginPDF(Boolean pdf){ + public void setPluginPDF(Boolean pdf) { setBooleanParameter(PLUGIN_PDF, pdf); } - + /** * Check if the visitor has the Quicktime plugin. + * * @return true if the visitor has the Quicktime plugin */ - public Boolean getPluginQuicktime(){ + public Boolean getPluginQuicktime() { return getBooleanParameter(PLUGIN_QUICKTIME); } - + /** * Set if the visitor has the Quicktime plugin. + * * @param quicktime true if the visitor has the Quicktime plugin */ - public void setPluginQuicktime(Boolean quicktime){ + public void setPluginQuicktime(Boolean quicktime) { setBooleanParameter(PLUGIN_QUICKTIME, quicktime); } - + /** * Check if the visitor has the RealPlayer plugin. + * * @return true if the visitor has the RealPlayer plugin */ - public Boolean getPluginRealPlayer(){ + public Boolean getPluginRealPlayer() { return getBooleanParameter(PLUGIN_REAL_PLAYER); } - + /** * Set if the visitor has the RealPlayer plugin. + * * @param realPlayer true if the visitor has the RealPlayer plugin */ - public void setPluginRealPlayer(Boolean realPlayer){ + public void setPluginRealPlayer(Boolean realPlayer) { setBooleanParameter(PLUGIN_REAL_PLAYER, realPlayer); } - + /** * Check if the visitor has the Silverlight plugin. + * * @return true if the visitor has the Silverlight plugin */ - public Boolean getPluginSilverlight(){ + public Boolean getPluginSilverlight() { return getBooleanParameter(PLUGIN_SILVERLIGHT); } - + /** * Set if the visitor has the Silverlight plugin. + * * @param silverlight true if the visitor has the Silverlight plugin */ - public void setPluginSilverlight(Boolean silverlight){ + public void setPluginSilverlight(Boolean silverlight) { setBooleanParameter(PLUGIN_SILVERLIGHT, silverlight); } - + /** * Check if the visitor has the Windows Media plugin. + * * @return true if the visitor has the Windows Media plugin */ - public Boolean getPluginWindowsMedia(){ + public Boolean getPluginWindowsMedia() { return getBooleanParameter(PLUGIN_WINDOWS_MEDIA); } - + /** * Set if the visitor has the Windows Media plugin. + * * @param windowsMedia true if the visitor has the Windows Media plugin */ - public void setPluginWindowsMedia(Boolean windowsMedia){ + public void setPluginWindowsMedia(Boolean windowsMedia) { setBooleanParameter(PLUGIN_WINDOWS_MEDIA, windowsMedia); } - + /** * Get the random value for this request + * * @return the random value */ - public String getRandomValue(){ - return (String)getParameter(RANDOM_VALUE); + public String getRandomValue() { + return (String) getParameter(RANDOM_VALUE); } - + /** - * Set a random value that is generated before each request. Using it helps + * Set a random value that is generated before each request. Using it helps * avoid the tracking request being cached by the browser or a proxy. + * * @param randomValue the random value to set. A null value will remove this parameter */ - public void setRandomValue(String randomValue){ + public void setRandomValue(String randomValue) { setParameter(RANDOM_VALUE, randomValue); } - + /** * Get the referrer url + * * @return the referrer url * @throws TypeConstraintException if the stored Referrer URL is a String */ - public URL getReferrerUrl(){ + public URL getReferrerUrl() { return returnAsUrl(REFERRER_URL, "Referrer URL", "getReferrerUrlAsString"); } - - /** - * Get the referrer url - * @return the referrer url - * @throws TypeConstraintException if the stored Referrer URL is a URL - */ - public String getReferrerUrlAsString(){ - return returnAsString(REFERRER_URL, "Referrer URL", "getReferrerUrl"); - } - + /** * Set the full HTTP Referrer URL. This value is used to determine how someone * got to your website (ie, through a website, search engine or campaign). + * * @param referrerUrl the referrer url to set. A null value will remove this parameter */ - public void setReferrerUrl(URL referrerUrl){ + public void setReferrerUrl(URL referrerUrl) { setParameter(REFERRER_URL, referrerUrl); } - + + /** + * Get the referrer url + * + * @return the referrer url + * @throws TypeConstraintException if the stored Referrer URL is a URL + */ + public String getReferrerUrlAsString() { + return returnAsString(REFERRER_URL, "Referrer URL", "getReferrerUrl"); + } + /** * Set the full HTTP Referrer URL. This value is used to determine how someone * got to your website (ie, through a website, search engine or campaign). + * * @param referrerUrl the referrer url to set. A null value will remove this parameter */ - public void setReferrerUrlWithString(String referrerUrl){ + public void setReferrerUrlWithString(String referrerUrl) { setParameter(REFERRER_URL, referrerUrl); } - + /** * Get the datetime of the request + * * @return the datetime of the request */ - public PiwikDate getRequestDatetime(){ - return (PiwikDate)getParameter(REQUEST_DATETIME); + public PiwikDate getRequestDatetime() { + return (PiwikDate) getParameter(REQUEST_DATETIME); } - + /** - * Set the datetime of the request (normally the current time is used). + * 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 Piwik 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 + * 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 datetime the datetime of the request to set. A null value will remove this parameter */ - public void setRequestDatetime(PiwikDate datetime){ - if (datetime != null && new Date().getTime()-datetime.getTime() > REQUEST_DATETIME_AUTH_LIMIT && getAuthToken() == null){ - throw new IllegalStateException("Because you are trying to set RequestDatetime for a time greater than 4 hours ago, AuthToken must be set first."); + public void setRequestDatetime(PiwikDate datetime) { + if (datetime != null && new Date().getTime() - datetime.getTime() > REQUEST_DATETIME_AUTH_LIMIT && getAuthToken() == null) { + throw new IllegalStateException("Because you are trying to set RequestDatetime for a time greater than 4 hours ago, AuthToken must be set first."); } setParameter(REQUEST_DATETIME, datetime); } - + /** * Get if this request will be tracked. + * * @return true if request will be tracked */ - public Boolean getRequired(){ + public Boolean getRequired() { return getBooleanParameter(REQUIRED); } - + /** * Set if this request will be tracked by the Piwik server. + * * @param required true if request will be tracked */ - public void setRequired(Boolean required){ + public void setRequired(Boolean required) { setBooleanParameter(REQUIRED, required); } - + /** * Get if the response will be an image. + * * @return true if the response will be an an image */ - public Boolean getResponseAsImage(){ + public Boolean getResponseAsImage() { return getBooleanParameter(RESPONSE_AS_IMAGE); } - + /** * Set if the response will be an image. If set to false, Piwik will respond * with a HTTP 204 response code instead of a GIF image. This improves performance * and can fix errors if images are not allowed to be obtained directly * (eg Chrome Apps). Available since Piwik 2.10.0. - + * * @param responseAsImage true if the response will be an image */ - public void setResponseAsImage(Boolean responseAsImage){ + public void setResponseAsImage(Boolean responseAsImage) { setBooleanParameter(RESPONSE_AS_IMAGE, responseAsImage); } - + /** * Get the search category + * * @return the search category */ - public String getSearchCategory(){ - return (String)getParameter(SEARCH_CATEGORY); + public String getSearchCategory() { + return (String) getParameter(SEARCH_CATEGORY); } - + /** * Specify a search category with this parameter. SearchQuery must first be * set. + * * @param searchCategory the search category to set. A null value will remove this parameter */ - public void setSearchCategory(String searchCategory){ - if (searchCategory != null && getSearchQuery() == null){ + public void setSearchCategory(String searchCategory) { + if (searchCategory != null && getSearchQuery() == null) { throw new IllegalStateException("SearchQuery must be set before SearchCategory can be set."); } setParameter(SEARCH_CATEGORY, searchCategory); } - + /** * Get the search query. + * * @return the search query */ - public String getSearchQuery(){ - return (String)getParameter(SEARCH_QUERY); + public String getSearchQuery() { + return (String) getParameter(SEARCH_QUERY); } - + /** * Set the search query. When specified, the request will not be tracked as * a normal pageview but will instead be tracked as a Site Search request. + * * @param searchQuery the search query to set. A null value will remove this parameter */ - public void setSearchQuery(String searchQuery){ + public void setSearchQuery(String searchQuery) { setParameter(SEARCH_QUERY, searchQuery); } - + /** * Get the search results count. + * * @return the search results count */ - public Long getSearchResultsCount(){ - return (Long)getParameter(SEARCH_RESULTS_COUNT); + public Long getSearchResultsCount() { + return (Long) getParameter(SEARCH_RESULTS_COUNT); } - + /** - * We recommend to set the - * search count to the number of search results displayed on the results page. - * When keywords are tracked with {@code Search Results Count=0} they will appear in + * We recommend to set the + * search count to the number of search results displayed on the results page. + * When keywords are tracked with {@code Search Results Count=0} they will appear in * the "No Result Search Keyword" report. SearchQuery must first be set. + * * @param searchResultsCount the search results count to set. A null value will remove this parameter */ - public void setSearchResultsCount(Long searchResultsCount){ - if (searchResultsCount != null && getSearchQuery() == null){ + public void setSearchResultsCount(Long searchResultsCount) { + if (searchResultsCount != null && getSearchQuery() == null) { throw new IllegalStateException("SearchQuery must be set before SearchResultsCount can be set."); } setParameter(SEARCH_RESULTS_COUNT, searchResultsCount); } - + /** * Get the id of the website we're tracking. + * * @return the id of the website */ - public Integer getSiteId(){ - return (Integer)getParameter(SITE_ID); - } - + public Integer getSiteId() { + return (Integer) getParameter(SITE_ID); + } + /** * Set the ID of the website we're tracking a visit/action for. + * * @param siteId the id of the website to set. A null value will remove this parameter */ - public void setSiteId(Integer siteId){ + public void setSiteId(Integer siteId) { setParameter(SITE_ID, siteId); } - + /** * Set if bot requests should be tracked + * * @return true if bot requests should be tracked */ - public Boolean getTrackBotRequests(){ + public Boolean getTrackBotRequests() { return getBooleanParameter(TRACK_BOT_REQUESTS); } - + /** * By default Piwik does not track bots. If you use the Tracking Java API, * you may be interested in tracking bot requests. To enable Bot Tracking in * Piwik, set Track Bot Requests to true. + * * @param trackBotRequests true if bot requests should be tracked */ - public void setTrackBotRequests(Boolean trackBotRequests){ + public void setTrackBotRequests(Boolean trackBotRequests) { setBooleanParameter(TRACK_BOT_REQUESTS, trackBotRequests); } - + /** * 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 #getVisitCustomVariable(int)} method instead. */ @Deprecated - public String getUserCustomVariable(String key){ + public String getUserCustomVariable(String key) { return getCustomVariable(VISIT_CUSTOM_VARIABLE, 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 */ - public CustomVariable getVisitCustomVariable(int index){ + public CustomVariable getVisitCustomVariable(int index) { return getCustomVariable(VISIT_CUSTOM_VARIABLE, 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 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 the {@link #setVisitCustomVariable(CustomVariable, int)} method instead. */ @Deprecated - public void setUserCustomVariable(String key, String value){ - if (value == null){ + public void setUserCustomVariable(String key, String value) { + if (value == null) { removeCustomVariable(VISIT_CUSTOM_VARIABLE, key); } else { setCustomVariable(VISIT_CUSTOM_VARIABLE, new CustomVariable(key, value), null); } } + /** * Set a user custom variable at the specified key. + * * @param customVariable the CustomVariable to set. A null value will remove the custom variable at the specified index - * @param index the index to set the customVariable at. + * @param index the index to set the customVariable at. */ - public void setVisitCustomVariable(CustomVariable customVariable, int index){ + public void setVisitCustomVariable(CustomVariable customVariable, int index) { setCustomVariable(VISIT_CUSTOM_VARIABLE, customVariable, index); } - + /** * Get the user id for this request. + * * @return the user id */ - public String getUserId(){ - return (String)getParameter(USER_ID); + public String getUserId() { + return (String) getParameter(USER_ID); } - + /** * Set the user id for this request. * User id is any non empty unique string identifying the user (such as an email * address or a username). To access this value, users must be logged-in in your - * system so you can fetch this user id from your system, and pass it to Piwik. - * The user id appears in the visitor log, the Visitor profile, and you can + * system so you can fetch this user id from your system, and pass it to Piwik. + * The user id appears in the visitor log, the Visitor profile, and you can * Segment * reports for one or several user ids. When specified, the user id will be * "enforced". This means that if there is no recent visit with this user id, * a new one will be created. If a visit is found in the last 30 minutes with * your specified user id, then the new action will be recorded to this existing visit. + * * @param userId the user id to set. A null value will remove this parameter */ - public void setUserId(String userId){ + public void setUserId(String userId) { setNonEmptyStringParameter(USER_ID, userId); } - + /** * Get the visitor's city. + * * @return the visitor's city */ - public String getVisitorCity(){ - return (String)getParameter(VISITOR_CITY); + public String getVisitorCity() { + return (String) getParameter(VISITOR_CITY); } - + /** - * Set an override value for the city. The name of the city the visitor is + * Set an override value for the city. The name of the city the visitor is * located in, eg, Tokyo. AuthToken must first be set. + * * @param city the visitor's city to set. A null value will remove this parameter */ - public void setVisitorCity(String city){ - if (city != null){ + public void setVisitorCity(String city) { + if (city != null) { verifyAuthTokenSet(); } setParameter(VISITOR_CITY, city); } - + /** * Get the visitor's country. + * * @return the visitor's country */ - public PiwikLocale getVisitorCountry(){ - return (PiwikLocale)getParameter(VISITOR_COUNTRY); + public PiwikLocale getVisitorCountry() { + return (PiwikLocale) getParameter(VISITOR_COUNTRY); } - + /** * Set an override value for the country. AuthToken must first be set. + * * @param country the visitor's country to set. A null value will remove this parameter */ - public void setVisitorCountry(PiwikLocale country){ - if (country != null){ + public void setVisitorCountry(PiwikLocale country) { + if (country != null) { verifyAuthTokenSet(); } setParameter(VISITOR_COUNTRY, country); } - + /** * Get the visitor's custom id. + * * @return the visitor's custom id */ - public String getVisitorCustomId(){ - return (String)getParameter(VISITOR_CUSTOM_ID); + public String getVisitorCustomId() { + return (String) getParameter(VISITOR_CUSTOM_ID); } - + /** * Set a custom visitor ID for this request. You must set this value to exactly * a {@value #ID_LENGTH} character hexadecimal string (containing only characters 01234567890abcdefABCDEF). * We recommended to set the UserId rather than the VisitorCustomId. + * * @param visitorCustomId the visitor's custom id to set. A null value will remove this parameter */ - public void setVisitorCustomId(String visitorCustomId){ - if (visitorCustomId != null){ - if (visitorCustomId.length() != ID_LENGTH){ - throw new IllegalArgumentException(visitorCustomId+" is not "+ID_LENGTH+" characters long."); + public void setVisitorCustomId(String visitorCustomId) { + if (visitorCustomId != null) { + if (visitorCustomId.length() != ID_LENGTH) { + throw new IllegalArgumentException(visitorCustomId + " is not " + ID_LENGTH + " characters long."); } // Verify visitorID is a 16 character hexadecimal string - else if (!visitorCustomId.matches("[0-9A-Fa-f]+")){ - throw new IllegalArgumentException(visitorCustomId+" is not a hexadecimal string."); + else if (!visitorCustomId.matches("[0-9A-Fa-f]+")) { + throw new IllegalArgumentException(visitorCustomId + " is not a hexadecimal string."); } } setParameter(VISITOR_CUSTOM_ID, visitorCustomId); } - + /** * Get the timestamp of the visitor's first visit. + * * @return the timestamp of the visitor's first visit */ - public Long getVisitorFirstVisitTimestamp(){ - return (Long)getParameter(VISITOR_FIRST_VISIT_TIMESTAMP); + public Long getVisitorFirstVisitTimestamp() { + return (Long) getParameter(VISITOR_FIRST_VISIT_TIMESTAMP); } - + /** - * Set the UNIX timestamp of this visitor's first visit. This could be set + * Set the UNIX timestamp of this visitor's first visit. This could be set * to the date where the user first started using your software/app, or when - * he/she created an account. This parameter is used to populate the + * he/she created an account. This parameter is used to populate the * Goals > Days to Conversion report. + * * @param timestamp the timestamp of the visitor's first visit to set. A null value will remove this parameter */ - public void setVisitorFirstVisitTimestamp(Long timestamp){ + public void setVisitorFirstVisitTimestamp(Long timestamp) { setParameter(VISITOR_FIRST_VISIT_TIMESTAMP, timestamp); } - + /** * Get the visitor's id. + * * @return the visitor's id */ - public String getVisitorId(){ - return (String)getParameter(VISITOR_ID); + public String getVisitorId() { + return (String) getParameter(VISITOR_ID); } - + /** - * Set the unique visitor ID, must be a {@value #ID_LENGTH} characters hexadecimal string. + * Set the unique visitor ID, must be a {@value #ID_LENGTH} 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 Piwik will still + * change after it is assigned. If this value is not set Piwik will still * track visits, but the unique visitors metric might be less accurate. + * * @param visitorId the visitor id to set. A null value will remove this parameter */ - public void setVisitorId(String visitorId){ - if (visitorId != null){ - if (visitorId.length() != ID_LENGTH){ - throw new IllegalArgumentException(visitorId+" is not "+ID_LENGTH+" characters long."); + public void setVisitorId(String visitorId) { + if (visitorId != null) { + if (visitorId.length() != ID_LENGTH) { + throw new IllegalArgumentException(visitorId + " is not " + ID_LENGTH + " characters long."); } // Verify visitorID is a 16 character hexadecimal string - else if (!visitorId.matches("[0-9A-Fa-f]+")){ - throw new IllegalArgumentException(visitorId+" is not a hexadecimal string."); + else if (!visitorId.matches("[0-9A-Fa-f]+")) { + throw new IllegalArgumentException(visitorId + " is not a hexadecimal string."); } } setParameter(VISITOR_ID, visitorId); } - + /** * Get the visitor's ip. + * * @return the visitor's ip */ - public String getVisitorIp(){ - return (String)getParameter(VISITOR_IP); + public String getVisitorIp() { + return (String) getParameter(VISITOR_IP); } - + /** - * Set the override value for the visitor IP (both IPv4 and IPv6 notations + * Set the override value for the visitor IP (both IPv4 and IPv6 notations * supported). AuthToken must first be set. + * * @param visitorIp the visitor's ip to set. A null value will remove this parameter */ - public void setVisitorIp(String visitorIp){ - if (visitorIp != null){ + public void setVisitorIp(String visitorIp) { + if (visitorIp != null) { verifyAuthTokenSet(); } setParameter(VISITOR_IP, visitorIp); } - + /** * Get the visitor's latitude. + * * @return the visitor's latitude */ - public Double getVisitorLatitude(){ - return (Double)getParameter(VISITOR_LATITUDE); + public Double getVisitorLatitude() { + return (Double) getParameter(VISITOR_LATITUDE); } - + /** - * Set an override value for the visitor's latitude, eg 22.456. AuthToken + * Set an override value for the visitor's latitude, eg 22.456. AuthToken * must first be set. + * * @param latitude the visitor's latitude to set. A null value will remove this parameter */ - public void setVisitorLatitude(Double latitude){ - if (latitude != null){ + public void setVisitorLatitude(Double latitude) { + if (latitude != null) { verifyAuthTokenSet(); } setParameter(VISITOR_LATITUDE, latitude); } - + /** * Get the visitor's longitude. + * * @return the visitor's longitude */ - public Double getVisitorLongitude(){ - return (Double)getParameter(VISITOR_LONGITUDE); + public Double getVisitorLongitude() { + return (Double) getParameter(VISITOR_LONGITUDE); } - + /** - * Set an override value for the visitor's longitude, eg 22.456. AuthToken + * Set an override value for the visitor's longitude, eg 22.456. AuthToken * must first be set. + * * @param longitude the visitor's longitude to set. A null value will remove this parameter */ - public void setVisitorLongitude(Double longitude){ - if (longitude != null){ + public void setVisitorLongitude(Double longitude) { + if (longitude != null) { verifyAuthTokenSet(); } setParameter(VISITOR_LONGITUDE, longitude); } - + /** * Get the timestamp of the visitor's previous visit. + * * @return the timestamp of the visitor's previous visit */ - public Long getVisitorPreviousVisitTimestamp(){ - return (Long)getParameter(VISITOR_PREVIOUS_VISIT_TIMESTAMP); + public Long getVisitorPreviousVisitTimestamp() { + return (Long) getParameter(VISITOR_PREVIOUS_VISIT_TIMESTAMP); } - + /** - * Set the UNIX timestamp of this visitor's previous visit. This parameter - * is used to populate the report + * Set the UNIX timestamp of this visitor's previous visit. This parameter + * is used to populate the report * Visitors > Engagement > Visits by days since last visit. + * * @param timestamp the timestamp of the visitor's previous visit to set. A null value will remove this parameter */ - public void setVisitorPreviousVisitTimestamp(Long timestamp){ + public void setVisitorPreviousVisitTimestamp(Long timestamp) { setParameter(VISITOR_PREVIOUS_VISIT_TIMESTAMP, timestamp); } - + /** * Get the visitor's region. + * * @return the visitor's region */ - public String getVisitorRegion(){ - return (String)getParameter(VISITOR_REGION); + public String getVisitorRegion() { + return (String) getParameter(VISITOR_REGION); } - + /** - * Set an override value for the region. Should be set to the two letter - * region code as defined by + * Set an override value for the region. Should be set to the two letter + * region code as defined by * MaxMind's GeoIP databases. * See here - * for a list of them for every country (the region codes are located in the + * for a list of them for every country (the region codes are located in the * second column, to the left of the region name and to the right of the country * code). + * * @param region the visitor's region to set. A null value will remove this parameter */ - public void setVisitorRegion(String region){ - if (region != null){ + public void setVisitorRegion(String region) { + if (region != null) { verifyAuthTokenSet(); } setParameter(VISITOR_REGION, region); } - + /** * Get the count of visits for this visitor. + * * @return the count of visits for this visitor */ - public Integer getVisitorVisitCount(){ - return (Integer)getParameter(VISITOR_VISIT_COUNT); + public Integer getVisitorVisitCount() { + return (Integer) getParameter(VISITOR_VISIT_COUNT); } - + /** * Set the current count of visits for this visitor. To set this value correctly, * it would be required to store the value for each visitor in your application * (using sessions or persisting in a database). Then you would manually increment * the counts by one on each new visit or "session", depending on how you choose - * to define a visit. This value is used to populate the report + * to define a visit. This value is used to populate the report * Visitors > Engagement > Visits by visit number. + * * @param visitorVisitCount the count of visits for this visitor to set. A null value will remove this parameter */ - public void setVisitorVisitCount(Integer visitorVisitCount){ + public void setVisitorVisitCount(Integer visitorVisitCount) { setParameter(VISITOR_VISIT_COUNT, visitorVisitCount); } - + /** * Get the query string represented by this object. + * * @return the query string represented by this object */ - - public String getQueryString(){ + + public String getQueryString() { StringBuilder sb = new StringBuilder(); - for (Entry parameter : parameters.entrySet()){ - if (sb.length() > 0){ + for (Entry parameter : parameters.entrySet()) { + if (sb.length() > 0) { sb.append("&"); } sb.append(parameter.getKey()); sb.append("="); sb.append(parameter.getValue().toString()); } - for (Entry customTrackingParameter : customTrackingParameters.entrySet()){ - for (Object o : customTrackingParameter.getValue()){ - if (sb.length() > 0){ + for (Entry customTrackingParameter : customTrackingParameters.entrySet()) { + for (Object o : customTrackingParameter.getValue()) { + if (sb.length() > 0) { sb.append("&"); } sb.append(customTrackingParameter.getKey()); @@ -1683,18 +1842,19 @@ public String getQueryString(){ sb.append(o.toString()); } } - + return sb.toString(); } - + /** * Get the url encoded query string represented by this object. + * * @return the url encoded query string represented by this object */ - public String getUrlEncodedQueryString(){ + public String getUrlEncodedQueryString() { StringBuilder sb = new StringBuilder(); - for (Entry parameter : parameters.entrySet()){ - if (sb.length() > 0){ + for (Entry parameter : parameters.entrySet()) { + if (sb.length() > 0) { sb.append("&"); } try { @@ -1703,14 +1863,13 @@ public String getUrlEncodedQueryString(){ sb2.append("="); sb2.append(URLEncoder.encode(parameter.getValue().toString(), "UTF-8")); sb.append(sb2); - } - catch (UnsupportedEncodingException e) { + } catch (UnsupportedEncodingException e) { System.err.println(e.getMessage()); } } - for (Entry customTrackingParameter : customTrackingParameters.entrySet()){ - for (Object o : customTrackingParameter.getValue()){ - if (sb.length() > 0){ + for (Entry customTrackingParameter : customTrackingParameters.entrySet()) { + for (Object o : customTrackingParameter.getValue()) { + if (sb.length() > 0) { sb.append("&"); } try { @@ -1719,240 +1878,233 @@ public String getUrlEncodedQueryString(){ sb2.append("="); sb2.append(URLEncoder.encode(o.toString(), "UTF-8")); sb.append(sb2); - } - catch (UnsupportedEncodingException e) { + } catch (UnsupportedEncodingException e) { System.err.println(e.getMessage()); } } } - + return sb.toString(); } - - /** - * Get a random hexadecimal string of a specified length. - * @param length length of the string to produce - * @return a random string consisting only of hexadecimal characters - */ - public static String getRandomHexString(int length){ - byte[] bytes = new byte[length/2]; - new Random().nextBytes(bytes); - return DatatypeConverter.printHexBinary(bytes); - } - + /** * Get a stored parameter. + * * @param key the parameter's key * @return the stored parameter's value */ - private Object getParameter(String key){ + private Object getParameter(String key) { return parameters.get(key); } - + /** * Set a stored parameter. - * @param key the parameter's key + * + * @param key the parameter's key * @param value the parameter's value. Removes the parameter if null */ - private void setParameter(String key, Object value){ - if (value == null){ + private void setParameter(String key, Object value) { + if (value == null) { parameters.remove(key); - } - else{ + } else { parameters.put(key, value); } } - + /** * Get a stored parameter that is a non-empty string. + * * @param key the parameter's key * @return the stored parameter's value */ - private String getNonEmptyStringParameter(String key){ - return (String)parameters.get(key); + private String getNonEmptyStringParameter(String key) { + return (String) parameters.get(key); } - + /** * Set a stored parameter and verify it is a non-empty string. - * @param key the parameter's key + * + * @param key the parameter's key * @param value the parameter's value. Cannot be the empty. Removes the parameter if null - * string + * string */ - private void setNonEmptyStringParameter(String key, String value){ - if (value == null){ + private void setNonEmptyStringParameter(String key, String value) { + if (value == null) { parameters.remove(key); - } - else if (value.length() == 0){ + } else if (value.length() == 0) { throw new IllegalArgumentException("Value cannot be empty."); - } - else{ + } else { parameters.put(key, value); } } - + /** * Get a stored parameter that is a boolean. + * * @param key the parameter's key * @return the stored parameter's value */ - private Boolean getBooleanParameter(String key){ - Integer i = (Integer)parameters.get(key); - if (i == null){ + private Boolean getBooleanParameter(String key) { + Integer i = (Integer) parameters.get(key); + if (i == null) { return null; } return i.equals(1); } - + /** * Set a stored parameter that is a boolean. This value will be stored as "1" * for true and "0" for false. - * @param key the parameter's key + * + * @param key the parameter's key * @param value the parameter's value. Removes the parameter if null */ - private void setBooleanParameter(String key, Boolean value){ - if (value == null){ + private void setBooleanParameter(String key, Boolean value) { + if (value == null) { parameters.remove(key); - } - else if (value){ + } else if (value) { parameters.put(key, 1); - } - else{ - parameters.put(key, 0); + } else { + parameters.put(key, 0); } } - + /** * Get a value that is stored in a json object at the specified parameter. + * * @param parameter the parameter to retrieve the json object from - * @param key the key of the value. Cannot be null + * @param key the key of the value. Cannot be null * @return the value */ - private CustomVariable getCustomVariable(String parameter, int index){ - CustomVariableList cvl = (CustomVariableList)parameters.get(parameter); - if (cvl == null){ + private CustomVariable getCustomVariable(String parameter, int index) { + CustomVariableList cvl = (CustomVariableList) parameters.get(parameter); + if (cvl == null) { return null; } - + return cvl.get(index); } - - private String getCustomVariable(String parameter, String key){ - if (key == null){ + + private String getCustomVariable(String parameter, String key) { + if (key == null) { throw new NullPointerException("Key cannot be null."); } - - CustomVariableList cvl = (CustomVariableList)parameters.get(parameter); - if (cvl == null){ + + CustomVariableList cvl = (CustomVariableList) parameters.get(parameter); + if (cvl == null) { return null; } - + return cvl.get(key); } - + /** * Store a value in a json object at the specified parameter. + * * @param parameter the parameter to store the json object at - * @param key the key of the value. Cannot be null - * @param value the value. Removes the parameter if null + * @param key the key of the value. Cannot be null + * @param value the value. Removes the parameter if null */ - private void setCustomVariable(String parameter, CustomVariable customVariable, Integer index){ - CustomVariableList cvl = (CustomVariableList)parameters.get(parameter); - if (cvl == null){ + private void setCustomVariable(String parameter, CustomVariable customVariable, Integer index) { + CustomVariableList cvl = (CustomVariableList) parameters.get(parameter); + if (cvl == null) { cvl = new CustomVariableList(); parameters.put(parameter, cvl); } - - if (customVariable == null){ + + if (customVariable == null) { cvl.remove(index); - if (cvl.isEmpty()){ + if (cvl.isEmpty()) { parameters.remove(parameter); } - } - else if (index == null){ + } else if (index == null) { cvl.add(customVariable); - } - else { + } else { cvl.add(customVariable, index); } } - - private void removeCustomVariable(String parameter, String key){ - if (key == null){ + + private void removeCustomVariable(String parameter, String key) { + if (key == null) { throw new NullPointerException("Key cannot be null."); } - CustomVariableList cvl = (CustomVariableList)parameters.get(parameter); - if (cvl != null){ + CustomVariableList cvl = (CustomVariableList) parameters.get(parameter); + if (cvl != null) { cvl.remove(key); - if (cvl.isEmpty()){ + if (cvl.isEmpty()) { parameters.remove(parameter); } } } - + /** * Get the value at the specified index from the json array at the specified * parameter. - * @param key the key of the json array to access + * + * @param key the key of the json array to access * @param index the index of the value in the json array * @return the value at the index in the json array */ - private JsonValue getFromJsonArray(String key, int index){ - PiwikJsonArray a = (PiwikJsonArray)parameters.get(key); - if (a == null){ + private JsonValue getFromJsonArray(String key, int index) { + PiwikJsonArray a = (PiwikJsonArray) parameters.get(key); + if (a == null) { return null; } - + return a.get(index); } + /** * Add a value to the json array at the specified parameter - * @param key the key of the json array to add to + * + * @param key the key of the json array to add to * @param value the value to add. Cannot be null */ - private void addToJsonArray(String key, JsonValue value){ - if (value == null){ + private void addToJsonArray(String key, JsonValue value) { + if (value == null) { throw new NullPointerException("Value cannot be null."); } - - PiwikJsonArray a = (PiwikJsonArray)parameters.get(key); - if (a == null){ + + PiwikJsonArray a = (PiwikJsonArray) parameters.get(key); + if (a == null) { a = new PiwikJsonArray(); parameters.put(key, a); } a.add(value); } - + /** * Removes the json array at the specified parameter + * * @param key the key of the json array to remove */ - private void removeJsonArray(String key){ + private void removeJsonArray(String key) { parameters.remove(key); } - - private URL returnAsUrl(String parameter, String name, String altMethod){ + + private URL returnAsUrl(String parameter, String name, String altMethod) { Object obj = getParameter(parameter); - if (obj == null){ + if (obj == null) { return null; } - if (obj instanceof URL){ - return (URL)obj; + if (obj instanceof URL) { + return (URL) obj; } throw new TypeConstraintException("The stored " + name + - " is a String, not a URL. Use \""+ + " is a String, not a URL. Use \"" + altMethod + "\" instead."); } - - private String returnAsString(String parameter, String name, String altMethod){ + + private String returnAsString(String parameter, String name, String altMethod) { Object obj = getParameter(parameter); - if (obj == null){ + if (obj == null) { return null; } - if (obj instanceof String){ - return (String)obj; + if (obj instanceof String) { + return (String) obj; } throw new TypeConstraintException("The stored " + name + - " is a URL, not a String. Use \""+ + " is a URL, not a String. Use \"" + altMethod + "\" instead."); } } diff --git a/src/main/java/org/piwik/java/tracking/PiwikTracker.java b/src/main/java/org/piwik/java/tracking/PiwikTracker.java index 2e7f9f1b..d44eb446 100644 --- a/src/main/java/org/piwik/java/tracking/PiwikTracker.java +++ b/src/main/java/org/piwik/java/tracking/PiwikTracker.java @@ -1,6 +1,6 @@ -/* +/* * Piwik Java Tracker - * + * * @link https://github.com/piwik/piwik-java-tracker * @license https://github.com/piwik/piwik-java-tracker/blob/master/LICENSE BSD-3 Clause */ @@ -12,6 +12,7 @@ import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; @@ -20,18 +21,20 @@ import javax.json.Json; import javax.json.JsonArrayBuilder; import javax.json.JsonObjectBuilder; -import javax.ws.rs.core.UriBuilder; import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; /** * A class that sends {@link PiwikRequest}s to a specified Piwik server. + * * @author brettcsorba */ -public class PiwikTracker{ +public class PiwikTracker { private static final String AUTH_TOKEN = "token_auth"; private static final String REQUESTS = "requests"; private static final int DEFAULT_TIMEOUT = 5000; - private final UriBuilder uriBuilder; + private final URIBuilder uriBuilder; private final int timeout; private String proxyHost = null; private int proxyPort = 0; @@ -39,22 +42,24 @@ public class PiwikTracker{ /** * Creates a tracker that will send {@link PiwikRequest}s to the specified * Tracking HTTP API endpoint. + * * @param hostUrl url endpoint to send requests to. Usually in the format - * http://your-piwik-domain.tld/piwik.php. + * http://your-piwik-domain.tld/piwik.php. */ - public PiwikTracker(String hostUrl){ + public PiwikTracker(String hostUrl) { this(hostUrl, DEFAULT_TIMEOUT); } /** * Creates a tracker that will send {@link PiwikRequest}s to the specified * Tracking HTTP API endpoint. + * * @param hostUrl url endpoint to send requests to. Usually in the format - * http://your-piwik-domain.tld/piwik.php. + * http://your-piwik-domain.tld/piwik.php. * @param timeout the timeout of the sent request in milliseconds */ - public PiwikTracker(String hostUrl, int timeout){ - uriBuilder = UriBuilder.fromPath(hostUrl); + public PiwikTracker(String hostUrl, int timeout) { + uriBuilder = new URIBuilder(URI.create(hostUrl)); this.timeout = timeout; } @@ -62,17 +67,17 @@ public PiwikTracker(String hostUrl, int timeout){ * Creates a tracker that will send {@link PiwikRequest}s to the specified * Tracking HTTP API endpoint via the provided proxy * - * @param hostUrl url endpoint to send requests to. Usually in the format - * http://your-piwik-domain.tld/piwik.php. + * @param hostUrl url endpoint to send requests to. Usually in the format + * http://your-piwik-domain.tld/piwik.php. * @param proxyHost url endpoint for the proxy * @param proxyPort proxy server port number */ - public PiwikTracker(String hostUrl, String proxyHost, int proxyPort){ + public PiwikTracker(String hostUrl, String proxyHost, int proxyPort) { this(hostUrl, proxyHost, proxyPort, DEFAULT_TIMEOUT); } - public PiwikTracker(String hostUrl, String proxyHost, int proxyPort, int timeout){ - uriBuilder = UriBuilder.fromPath(hostUrl); + public PiwikTracker(String hostUrl, String proxyHost, int proxyPort, int timeout) { + uriBuilder = new URIBuilder(URI.create(hostUrl)); this.proxyHost = proxyHost; this.proxyPort = proxyPort; this.timeout = timeout; @@ -80,30 +85,36 @@ public PiwikTracker(String hostUrl, String proxyHost, int proxyPort, int timeout /** * Send a request. + * * @param request request to send * @return the response from this request * @throws IOException thrown if there was a problem with this connection */ - public HttpResponse sendRequest(PiwikRequest request) throws IOException{ + public HttpResponse sendRequest(PiwikRequest request) throws IOException { HttpClient client = getHttpClient(); - uriBuilder.replaceQuery(request.getUrlEncodedQueryString()); - HttpGet get = new HttpGet(uriBuilder.build()); - + uriBuilder.setCustomQuery(request.getQueryString()); + HttpGet get = null; try { + get = new HttpGet(uriBuilder.build()); return client.execute(get); + } catch (URISyntaxException e) { + throw new IOException(e); } finally { - get.releaseConnection(); + if (get != null) { + get.releaseConnection(); + } } } /** * Send multiple requests in a single HTTP call. More efficient than sending * several individual requests. + * * @param requests the requests to send * @return the response from these requests * @throws IOException thrown if there was a problem with this connection */ - public HttpResponse sendBulkRequest(Iterable requests) throws IOException{ + public HttpResponse sendBulkRequest(Iterable requests) throws IOException { return sendBulkRequest(requests, null); } @@ -111,50 +122,57 @@ public HttpResponse sendBulkRequest(Iterable requests) throws IOEx * Send multiple requests in a single HTTP call. More efficient than sending * several individual requests. Specify the AuthToken if parameters that require * an auth token is used. - * @param requests the requests to send + * + * @param requests the requests to send * @param authToken specify if any of the parameters use require AuthToken * @return the response from these requests * @throws IOException thrown if there was a problem with this connection */ - public HttpResponse sendBulkRequest(Iterable requests, String authToken) throws IOException{ - if (authToken != null && authToken.length() != PiwikRequest.AUTH_TOKEN_LENGTH){ - throw new IllegalArgumentException(authToken+" is not "+PiwikRequest.AUTH_TOKEN_LENGTH+" characters long."); + public HttpResponse sendBulkRequest(Iterable requests, String authToken) throws IOException { + if (authToken != null && authToken.length() != PiwikRequest.AUTH_TOKEN_LENGTH) { + throw new IllegalArgumentException(authToken + " is not " + PiwikRequest.AUTH_TOKEN_LENGTH + " characters long."); } JsonObjectBuilder ob = Json.createObjectBuilder(); JsonArrayBuilder ab = Json.createArrayBuilder(); - for (PiwikRequest request : requests){ - ab.add("?"+request.getQueryString()); + for (PiwikRequest request : requests) { + ab.add('?' + request.getQueryString()); } ob.add(REQUESTS, ab); - if (authToken != null){ + if (authToken != null) { ob.add(AUTH_TOKEN, authToken); } HttpClient client = getHttpClient(); - HttpPost post = new HttpPost(uriBuilder.build()); - post.setEntity(new StringEntity(ob.build().toString(), - ContentType.APPLICATION_JSON)); + HttpPost post = null; try { + post = new HttpPost(uriBuilder.build()); + post.setEntity(new StringEntity(ob.build().toString(), + ContentType.APPLICATION_JSON)); return client.execute(post); + } catch (URISyntaxException e) { + throw new IOException(e); } finally { - post.releaseConnection(); + if (post != null) { + post.releaseConnection(); + } } } /** * Get a HTTP client. With proxy if a proxy is provided in the constructor. + * * @return a HTTP client */ - protected HttpClient getHttpClient(){ + protected HttpClient getHttpClient() { HttpClientBuilder builder = HttpClientBuilder.create(); - if(proxyHost != null && proxyPort != 0) { + if (proxyHost != null && proxyPort != 0) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); builder.setRoutePlanner(routePlanner); diff --git a/src/test/java/org/piwik/java/tracking/PiwikTrackerTest.java b/src/test/java/org/piwik/java/tracking/PiwikTrackerTest.java index 59be0503..0a4d27a5 100644 --- a/src/test/java/org/piwik/java/tracking/PiwikTrackerTest.java +++ b/src/test/java/org/piwik/java/tracking/PiwikTrackerTest.java @@ -72,7 +72,7 @@ public void testSendRequest() throws Exception{ HttpResponse response = mock(HttpResponse.class); doReturn(client).when(piwikTracker).getHttpClient(); - doReturn("query").when(request).getUrlEncodedQueryString(); + doReturn("query").when(request).getQueryString(); doReturn(response).when(client).execute(argThat(new CorrectGetRequest("http://test.com?query"))); assertEquals(response, piwikTracker.sendRequest(request)); From c63193a514a15a78c0ebdb6e7b857b6fb94b9e85 Mon Sep 17 00:00:00 2001 From: Marvin Date: Sat, 15 Dec 2018 17:19:51 +0100 Subject: [PATCH 03/10] Refactor the test code Signed-off-by: Marvin --- .../java/tracking/CustomVariableListTest.java | 38 +- .../java/tracking/CustomVariableTest.java | 28 +- .../java/tracking/EcommerceItemTest.java | 69 +- .../piwik/java/tracking/PiwikDateTest.java | 40 +- .../java/tracking/PiwikJsonArrayTest.java | 47 +- .../java/tracking/PiwikJsonObjectTest.java | 47 +- .../piwik/java/tracking/PiwikLocaleTest.java | 43 +- .../piwik/java/tracking/PiwikRequestTest.java | 741 +++++++++--------- .../piwik/java/tracking/PiwikTrackerTest.java | 177 ++--- 9 files changed, 606 insertions(+), 624 deletions(-) diff --git a/src/test/java/org/piwik/java/tracking/CustomVariableListTest.java b/src/test/java/org/piwik/java/tracking/CustomVariableListTest.java index 861400f2..a691bbf4 100644 --- a/src/test/java/org/piwik/java/tracking/CustomVariableListTest.java +++ b/src/test/java/org/piwik/java/tracking/CustomVariableListTest.java @@ -5,21 +5,17 @@ */ package org.piwik.java.tracking; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.*; + /** - * * @author Katie */ public class CustomVariableListTest { private CustomVariableList cvl; - + @Before public void setUp() { cvl = new CustomVariableList(); @@ -31,31 +27,31 @@ public void testAdd_CustomVariable() { CustomVariable b = new CustomVariable("c", "d"); CustomVariable c = new CustomVariable("a", "e"); CustomVariable d = new CustomVariable("a", "f"); - + assertTrue(cvl.isEmpty()); cvl.add(a); assertFalse(cvl.isEmpty()); assertEquals("b", cvl.get("a")); assertEquals(a, cvl.get(1)); assertEquals("{\"1\":[\"a\",\"b\"]}", cvl.toString()); - + cvl.add(b); assertEquals("d", cvl.get("c")); assertEquals(b, cvl.get(2)); assertEquals("{\"1\":[\"a\",\"b\"],\"2\":[\"c\",\"d\"]}", cvl.toString()); - + cvl.add(c, 5); assertEquals("b", cvl.get("a")); assertEquals(c, cvl.get(5)); assertNull(cvl.get(3)); assertEquals("{\"1\":[\"a\",\"b\"],\"2\":[\"c\",\"d\"],\"5\":[\"a\",\"e\"]}", cvl.toString()); - + cvl.add(d); assertEquals("f", cvl.get("a")); assertEquals(d, cvl.get(1)); assertEquals(d, cvl.get(5)); assertEquals("{\"1\":[\"a\",\"f\"],\"2\":[\"c\",\"d\"],\"5\":[\"a\",\"f\"]}", cvl.toString()); - + cvl.remove("a"); assertNull(cvl.get("a")); assertNull(cvl.get(1)); @@ -68,25 +64,23 @@ public void testAdd_CustomVariable() { assertTrue(cvl.isEmpty()); assertEquals("{}", cvl.toString()); } - + @Test - public void testAddCustomVariableIndexLessThan1(){ - try{ + public void testAddCustomVariableIndexLessThan1() { + try { cvl.add(new CustomVariable("a", "b"), 0); fail("Exception should have been throw."); - } - catch(IllegalArgumentException e){ + } catch (IllegalArgumentException e) { assertEquals("Index must be greater than 0.", e.getLocalizedMessage()); } } - + @Test - public void testGetCustomVariableIntegerLessThan1(){ - try{ + public void testGetCustomVariableIntegerLessThan1() { + try { cvl.get(0); fail("Exception should have been throw."); - } - catch(IllegalArgumentException e){ + } catch (IllegalArgumentException e) { assertEquals("Index must be greater than 0.", e.getLocalizedMessage()); } } diff --git a/src/test/java/org/piwik/java/tracking/CustomVariableTest.java b/src/test/java/org/piwik/java/tracking/CustomVariableTest.java index 28b4e475..e14bd215 100644 --- a/src/test/java/org/piwik/java/tracking/CustomVariableTest.java +++ b/src/test/java/org/piwik/java/tracking/CustomVariableTest.java @@ -7,37 +7,37 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.*; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; /** - * * @author Katie */ public class CustomVariableTest { private CustomVariable customVariable; - + @Before public void setUp() { customVariable = new CustomVariable("key", "value"); } - + @Test - public void testConstructorNullKey(){ - try{ + public void testConstructorNullKey() { + try { new CustomVariable(null, null); - fail("Exception should have been throw."); - } - catch(NullPointerException e){ + fail("Exception should have been throw."); + } catch (NullPointerException e) { assertEquals("Key cannot be null.", e.getLocalizedMessage()); } } + @Test - public void testConstructorNullValue(){ - try{ + public void testConstructorNullValue() { + try { new CustomVariable("key", null); fail("Exception should have been throw."); - } - catch(NullPointerException e){ + } catch (NullPointerException e) { assertEquals("Value cannot be null.", e.getLocalizedMessage()); } } @@ -50,5 +50,5 @@ public void testGetKey() { @Test public void testGetValue() { assertEquals("value", customVariable.getValue()); - } + } } diff --git a/src/test/java/org/piwik/java/tracking/EcommerceItemTest.java b/src/test/java/org/piwik/java/tracking/EcommerceItemTest.java index 4359920b..6a8d8f26 100644 --- a/src/test/java/org/piwik/java/tracking/EcommerceItemTest.java +++ b/src/test/java/org/piwik/java/tracking/EcommerceItemTest.java @@ -1,67 +1,64 @@ -/* +/* * Piwik Java Tracker - * + * * @link https://github.com/piwik/piwik-java-tracker * @license https://github.com/piwik/piwik-java-tracker/blob/master/LICENSE BSD-3 Clause */ package org.piwik.java.tracking; +import org.junit.*; + import javax.json.JsonValue.ValueType; -import org.junit.After; -import org.junit.AfterClass; + import static org.junit.Assert.assertEquals; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; /** - * * @author brettcsorba */ -public class EcommerceItemTest{ +public class EcommerceItemTest { EcommerceItem ecommerceItem; - - public EcommerceItemTest(){ + + public EcommerceItemTest() { } - + @BeforeClass - public static void setUpClass(){ + public static void setUpClass() { } - + @AfterClass - public static void tearDownClass(){ + public static void tearDownClass() { } - + @Before - public void setUp(){ + public void setUp() { ecommerceItem = new EcommerceItem(null, null, null, null, null); } - + @After - public void tearDown(){ + public void tearDown() { } /** * Test of constructor, of class EcommerceItem. */ @Test - public void testConstructor(){ + public void testConstructor() { EcommerceItem ecommerceItem = new EcommerceItem("sku", "name", "category", 1.0, 1); - + assertEquals("sku", ecommerceItem.getSku()); assertEquals("name", ecommerceItem.getName()); assertEquals("category", ecommerceItem.getCategory()); assertEquals(new Double(1.0), ecommerceItem.getPrice()); assertEquals(new Integer(1), ecommerceItem.getQuantity()); } - + /** * Test of getSku method, of class EcommerceItem. */ @Test - public void testGetSku(){ + public void testGetSku() { ecommerceItem.setSku("sku"); - + assertEquals("sku", ecommerceItem.getSku()); } @@ -69,9 +66,9 @@ public void testGetSku(){ * Test of getName method, of class EcommerceItem. */ @Test - public void testGetName(){ + public void testGetName() { ecommerceItem.setName("name"); - + assertEquals("name", ecommerceItem.getName()); } @@ -79,9 +76,9 @@ public void testGetName(){ * Test of getCategory method, of class EcommerceItem. */ @Test - public void testGetCategory(){ + public void testGetCategory() { ecommerceItem.setCategory("category"); - + assertEquals("category", ecommerceItem.getCategory()); } @@ -89,9 +86,9 @@ public void testGetCategory(){ * Test of getPrice method, of class EcommerceItem. */ @Test - public void testGetPrice(){ + public void testGetPrice() { ecommerceItem.setPrice(1.0); - + assertEquals(new Double(1.0), ecommerceItem.getPrice()); } @@ -99,9 +96,9 @@ public void testGetPrice(){ * Test of getQuantity method, of class EcommerceItem. */ @Test - public void testGetQuantity(){ + public void testGetQuantity() { ecommerceItem.setQuantity(1); - + assertEquals(new Integer(1), ecommerceItem.getQuantity()); } @@ -109,7 +106,7 @@ public void testGetQuantity(){ * Test of getValueType method, of class EcommerceItem. */ @Test - public void testGetValueType(){ + public void testGetValueType() { assertEquals(ValueType.ARRAY, ecommerceItem.getValueType()); } @@ -117,10 +114,10 @@ public void testGetValueType(){ * Test of toString method, of class EcommerceItem. */ @Test - public void testToString(){ + public void testToString() { ecommerceItem = new EcommerceItem("sku", "name", "category", 1.0, 1); - + assertEquals("[\"sku\",\"name\",\"category\",1.0,1]", ecommerceItem.toString()); } - + } diff --git a/src/test/java/org/piwik/java/tracking/PiwikDateTest.java b/src/test/java/org/piwik/java/tracking/PiwikDateTest.java index 704f937e..20f8c325 100644 --- a/src/test/java/org/piwik/java/tracking/PiwikDateTest.java +++ b/src/test/java/org/piwik/java/tracking/PiwikDateTest.java @@ -1,57 +1,55 @@ -/* +/* * Piwik Java Tracker - * + * * @link https://github.com/piwik/piwik-java-tracker * @license https://github.com/piwik/piwik-java-tracker/blob/master/LICENSE BSD-3 Clause */ package org.piwik.java.tracking; +import org.junit.Test; + import java.util.TimeZone; -import org.junit.After; -import org.junit.AfterClass; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; /** - * * @author brettcsorba */ -public class PiwikDateTest{ +public class PiwikDateTest { /** * Test of constructor, of class PiwikDate. */ @Test - public void testConstructor0(){ + public void testConstructor0() { PiwikDate date = new PiwikDate(); - + assertNotNull(date); } + @Test - public void testConstructor1(){ + public void testConstructor1() { PiwikDate date = new PiwikDate(1433186085092L); - + assertNotNull(date); - + assertEquals("2015-06-01 19:14:45", date.toString()); - + date = new PiwikDate(1467437553000L); - + assertEquals("2016-07-02 05:32:33", date.toString()); } - + /** * Test of setTimeZone method, of class PiwikDate. */ @Test - public void testSetTimeZone(){ + public void testSetTimeZone() { PiwikDate date = new PiwikDate(1433186085092L); - + date.setTimeZone(TimeZone.getTimeZone("America/New_York")); - + assertEquals("2015-06-01 15:14:45", date.toString()); } - + } diff --git a/src/test/java/org/piwik/java/tracking/PiwikJsonArrayTest.java b/src/test/java/org/piwik/java/tracking/PiwikJsonArrayTest.java index a3d9187a..bfe69720 100644 --- a/src/test/java/org/piwik/java/tracking/PiwikJsonArrayTest.java +++ b/src/test/java/org/piwik/java/tracking/PiwikJsonArrayTest.java @@ -1,58 +1,55 @@ -/* +/* * Piwik Java Tracker - * + * * @link https://github.com/piwik/piwik-java-tracker * @license https://github.com/piwik/piwik-java-tracker/blob/master/LICENSE BSD-3 Clause */ package org.piwik.java.tracking; +import org.junit.*; + import javax.json.JsonValue; -import org.junit.After; -import org.junit.AfterClass; + import static org.junit.Assert.assertEquals; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; import static org.mockito.Mockito.mock; /** - * * @author brettcsorba */ -public class PiwikJsonArrayTest{ +public class PiwikJsonArrayTest { PiwikJsonArray array; - - public PiwikJsonArrayTest(){ + + public PiwikJsonArrayTest() { } - + @BeforeClass - public static void setUpClass(){ + public static void setUpClass() { } - + @AfterClass - public static void tearDownClass(){ + public static void tearDownClass() { } - + @Before - public void setUp(){ + public void setUp() { array = new PiwikJsonArray(); } - + @After - public void tearDown(){ + public void tearDown() { } /** * Test of get method, of class PiwikJsonArray. */ @Test - public void testAddGetSet(){ + public void testAddGetSet() { JsonValue value = mock(JsonValue.class); JsonValue value2 = mock(JsonValue.class); - + array.add(value); assertEquals(value, array.get(0)); - + array.set(0, value2); assertEquals(value2, array.get(0)); } @@ -61,12 +58,12 @@ public void testAddGetSet(){ * Test of toString method, of class PiwikJsonArray. */ @Test - public void testToString(){ + public void testToString() { array.add(JsonValue.TRUE); array.add(new EcommerceItem("a", "b", "c", 1.0, 2)); array.add(JsonValue.FALSE); - + assertEquals("[true,[\"a\",\"b\",\"c\",1.0,2],false]", array.toString()); } - + } diff --git a/src/test/java/org/piwik/java/tracking/PiwikJsonObjectTest.java b/src/test/java/org/piwik/java/tracking/PiwikJsonObjectTest.java index 0a840fce..e96d8fe9 100644 --- a/src/test/java/org/piwik/java/tracking/PiwikJsonObjectTest.java +++ b/src/test/java/org/piwik/java/tracking/PiwikJsonObjectTest.java @@ -1,53 +1,46 @@ -/* +/* * Piwik Java Tracker - * + * * @link https://github.com/piwik/piwik-java-tracker * @license https://github.com/piwik/piwik-java-tracker/blob/master/LICENSE BSD-3 Clause */ package org.piwik.java.tracking; -import org.junit.After; -import org.junit.AfterClass; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.*; + +import static org.junit.Assert.*; /** - * * @author brettcsorba */ -public class PiwikJsonObjectTest{ +public class PiwikJsonObjectTest { PiwikJsonObject obj; - - public PiwikJsonObjectTest(){ + + public PiwikJsonObjectTest() { } - + @BeforeClass - public static void setUpClass(){ + public static void setUpClass() { } - + @AfterClass - public static void tearDownClass(){ + public static void tearDownClass() { } - + @Before - public void setUp(){ + public void setUp() { obj = new PiwikJsonObject(); } - + @After - public void tearDown(){ + public void tearDown() { } /** * Test of get method, of class PiwikJsonObject. */ @Test - public void testMethods(){ + public void testMethods() { assertTrue(obj.isEmpty()); assertEquals(0, obj.size()); assertNull(obj.put("key", "value")); @@ -64,13 +57,13 @@ public void testMethods(){ * Test of toString method, of class PiwikJsonObject. */ @Test - public void testToString(){ + public void testToString() { obj.put("key", "value"); obj.put("key2", "value2"); obj.put("key3", "value3"); obj.remove("key2"); - + assertEquals("{\"1\":[\"key\",\"value\"],\"2\":[\"key3\",\"value3\"]}", obj.toString()); } - + } diff --git a/src/test/java/org/piwik/java/tracking/PiwikLocaleTest.java b/src/test/java/org/piwik/java/tracking/PiwikLocaleTest.java index e2d720da..d68cc03f 100644 --- a/src/test/java/org/piwik/java/tracking/PiwikLocaleTest.java +++ b/src/test/java/org/piwik/java/tracking/PiwikLocaleTest.java @@ -1,51 +1,48 @@ -/* +/* * Piwik Java Tracker - * + * * @link https://github.com/piwik/piwik-java-tracker * @license https://github.com/piwik/piwik-java-tracker/blob/master/LICENSE BSD-3 Clause */ package org.piwik.java.tracking; +import org.junit.*; + import java.util.Locale; -import org.junit.After; -import org.junit.AfterClass; + import static org.junit.Assert.assertEquals; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; /** - * * @author brettcsorba */ -public class PiwikLocaleTest{ +public class PiwikLocaleTest { PiwikLocale locale; - - public PiwikLocaleTest(){ + + public PiwikLocaleTest() { } - + @BeforeClass - public static void setUpClass(){ + public static void setUpClass() { } - + @AfterClass - public static void tearDownClass(){ + public static void tearDownClass() { } - + @Before - public void setUp(){ + public void setUp() { locale = new PiwikLocale(Locale.US); } - + @After - public void tearDown(){ + public void tearDown() { } /** * Test of getLocale method, of class PiwikLocale. */ @Test - public void testConstructor(){ + public void testConstructor() { assertEquals(Locale.US, locale.getLocale()); } @@ -53,7 +50,7 @@ public void testConstructor(){ * Test of setLocale method, of class PiwikLocale. */ @Test - public void testLocale(){ + public void testLocale() { locale.setLocale(Locale.GERMANY); assertEquals(Locale.GERMANY, locale.getLocale()); } @@ -62,8 +59,8 @@ public void testLocale(){ * Test of toString method, of class PiwikLocale. */ @Test - public void testToString(){ + public void testToString() { assertEquals("us", locale.toString()); } - + } diff --git a/src/test/java/org/piwik/java/tracking/PiwikRequestTest.java b/src/test/java/org/piwik/java/tracking/PiwikRequestTest.java index 162a5210..249ae0d0 100644 --- a/src/test/java/org/piwik/java/tracking/PiwikRequestTest.java +++ b/src/test/java/org/piwik/java/tracking/PiwikRequestTest.java @@ -1,44 +1,40 @@ -/* +/* * Piwik Java Tracker - * + * * @link https://github.com/piwik/piwik-java-tracker * @license https://github.com/piwik/piwik-java-tracker/blob/master/LICENSE BSD-3 Clause */ package org.piwik.java.tracking; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import javax.xml.bind.TypeConstraintException; import java.net.URL; import java.nio.charset.Charset; import java.util.List; import java.util.Locale; -import javax.xml.bind.TypeConstraintException; -import org.junit.After; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import org.junit.Before; -import org.junit.Test; + +import static org.junit.Assert.*; /** - * * @author brettcsorba */ -public class PiwikRequestTest{ +public class PiwikRequestTest { private PiwikRequest request; - + @Before - public void setUp() throws Exception{ + public void setUp() throws Exception { request = new PiwikRequest(3, new URL("http://test.com")); } - + @After - public void tearDown(){ + public void tearDown() { } - + @Test - public void testConstructor() throws Exception{ + public void testConstructor() throws Exception { request = new PiwikRequest(3, new URL("http://test.com")); assertEquals(new Integer(3), request.getSiteId()); assertTrue(request.getRequired()); @@ -53,7 +49,7 @@ public void testConstructor() throws Exception{ * Test of getActionName method, of class PiwikRequest. */ @Test - public void testActionName(){ + public void testActionName() { request.setActionName("action"); assertEquals("action", request.getActionName()); request.setActionName(null); @@ -64,7 +60,7 @@ public void testActionName(){ * Test of getActionTime method, of class PiwikRequest. */ @Test - public void testActionTime(){ + public void testActionTime() { request.setActionTime(1000L); assertEquals(new Long(1000L), request.getActionTime()); } @@ -73,33 +69,31 @@ public void testActionTime(){ * Test of getActionUrl method, of class PiwikRequest. */ @Test - public void testActionUrl() throws Exception{ + public void testActionUrl() throws Exception { request.setActionUrl(null); assertNull(request.getActionUrl()); assertNull(request.getActionUrlAsString()); - + URL url = new URL("http://action.com"); request.setActionUrl(url); assertEquals(url, request.getActionUrl()); - try{ + try { request.getActionUrlAsString(); fail("Exception should have been thrown."); - } - catch(TypeConstraintException e){ + } catch (TypeConstraintException e) { assertEquals("The stored Action URL is a URL, not a String. Use \"getActionUrl\" instead.", e.getLocalizedMessage()); } - + request.setActionUrlWithString(null); assertNull(request.getActionUrl()); assertNull(request.getActionUrlAsString()); - + request.setActionUrlWithString("actionUrl"); assertEquals("actionUrl", request.getActionUrlAsString()); - try{ + try { request.getActionUrl(); fail("Exception should have been thrown."); - } - catch(TypeConstraintException e){ + } catch (TypeConstraintException e) { assertEquals("The stored Action URL is a String, not a URL. Use \"getActionUrlAsString\" instead.", e.getLocalizedMessage()); } } @@ -108,7 +102,7 @@ public void testActionUrl() throws Exception{ * Test of getApiVersion method, of class PiwikRequest. */ @Test - public void testApiVersion(){ + public void testApiVersion() { request.setApiVersion("2"); assertEquals("2", request.getApiVersion()); } @@ -117,22 +111,23 @@ public void testApiVersion(){ * Test of getAuthToken method, of class PiwikRequest. */ @Test - public void testAuthTokenTT(){ - try{ + public void testAuthTokenTT() { + try { request.setAuthToken("1234"); fail("Exception should have been thrown."); - } - catch(IllegalArgumentException e){ - assertEquals("1234 is not 32 characters long.", e.getLocalizedMessage()); + } catch (IllegalArgumentException e) { + assertEquals("1234 is not 32 characters long.", e.getLocalizedMessage()); } } + @Test - public void testAuthTokenTF(){ + public void testAuthTokenTF() { request.setAuthToken("12345678901234567890123456789012"); assertEquals("12345678901234567890123456789012", request.getAuthToken()); } + @Test - public void testAuthTokenF(){ + public void testAuthTokenF() { request.setAuthToken("12345678901234567890123456789012"); request.setAuthToken(null); assertNull(request.getAuthToken()); @@ -142,13 +137,12 @@ public void testAuthTokenF(){ * Test of verifyAuthTokenSet method, of class PiwikRequest. */ @Test - public void testVerifyAuthTokenSet(){ - try{ + public void testVerifyAuthTokenSet() { + try { request.verifyAuthTokenSet(); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ - assertEquals("AuthToken must be set before this value can be set.", e.getLocalizedMessage()); + } catch (IllegalStateException e) { + assertEquals("AuthToken must be set before this value can be set.", e.getLocalizedMessage()); } } @@ -156,7 +150,7 @@ public void testVerifyAuthTokenSet(){ * Test of getCampaignKeyword method, of class PiwikRequest. */ @Test - public void testCampaignKeyword(){ + public void testCampaignKeyword() { request.setCampaignKeyword("keyword"); assertEquals("keyword", request.getCampaignKeyword()); } @@ -165,7 +159,7 @@ public void testCampaignKeyword(){ * Test of getCampaignName method, of class PiwikRequest. */ @Test - public void testCampaignName(){ + public void testCampaignName() { request.setCampaignName("name"); assertEquals("name", request.getCampaignName()); } @@ -174,7 +168,7 @@ public void testCampaignName(){ * Test of getCharacterSet method, of class PiwikRequest. */ @Test - public void testCharacterSet(){ + public void testCharacterSet() { Charset charset = Charset.defaultCharset(); request.setCharacterSet(charset); assertEquals(charset, request.getCharacterSet()); @@ -184,7 +178,7 @@ public void testCharacterSet(){ * Test of getContentInteraction method, of class PiwikRequest. */ @Test - public void testContentInteraction(){ + public void testContentInteraction() { request.setContentInteraction("interaction"); assertEquals("interaction", request.getContentInteraction()); } @@ -193,7 +187,7 @@ public void testContentInteraction(){ * Test of getContentName method, of class PiwikRequest. */ @Test - public void testContentName(){ + public void testContentName() { request.setContentName("name"); assertEquals("name", request.getContentName()); } @@ -202,7 +196,7 @@ public void testContentName(){ * Test of getContentPiece method, of class PiwikRequest. */ @Test - public void testContentPiece(){ + public void testContentPiece() { request.setContentPiece("piece"); assertEquals("piece", request.getContentPiece()); } @@ -211,27 +205,25 @@ public void testContentPiece(){ * Test of getContentTarget method, of class PiwikRequest. */ @Test - public void testContentTarget() throws Exception{ + public void testContentTarget() throws Exception { URL url = new URL("http://target.com"); request.setContentTarget(url); assertEquals(url, request.getContentTarget()); - - try{ + + try { request.getContentTargetAsString(); fail("Exception should have been thrown."); - } - catch(TypeConstraintException e){ + } catch (TypeConstraintException e) { assertEquals("The stored Content Target is a URL, not a String. Use \"getContentTarget\" instead.", e.getLocalizedMessage()); } - + request.setContentTargetWithString("contentTarget"); assertEquals("contentTarget", request.getContentTargetAsString()); - - try{ + + try { request.getContentTarget(); fail("Exception should have been thrown."); - } - catch(TypeConstraintException e){ + } catch (TypeConstraintException e) { assertEquals("The stored Content Target is a String, not a URL. Use \"getContentTargetAsString\" instead.", e.getLocalizedMessage()); } } @@ -240,7 +232,7 @@ public void testContentTarget() throws Exception{ * Test of getCurrentHour method, of class PiwikRequest. */ @Test - public void testCurrentHour(){ + public void testCurrentHour() { request.setCurrentHour(1); assertEquals(new Integer(1), request.getCurrentHour()); } @@ -249,7 +241,7 @@ public void testCurrentHour(){ * Test of getCurrentMinute method, of class PiwikRequest. */ @Test - public void testCurrentMinute(){ + public void testCurrentMinute() { request.setCurrentMinute(2); assertEquals(new Integer(2), request.getCurrentMinute()); } @@ -258,89 +250,92 @@ public void testCurrentMinute(){ * Test of getCurrentSecond method, of class PiwikRequest. */ @Test - public void testCurrentSecond(){ + public void testCurrentSecond() { request.setCurrentSecond(3); assertEquals(new Integer(3), request.getCurrentSecond()); } - + /** * Test of getCustomTrackingParameter method, of class PiwikRequest. */ @Test - public void testGetCustomTrackingParameter_T(){ - try{ + public void testGetCustomTrackingParameter_T() { + try { request.getCustomTrackingParameter(null); fail("Exception should have been thrown."); - } - catch(NullPointerException e){ + } catch (NullPointerException e) { assertEquals("Key cannot be null.", e.getLocalizedMessage()); - } + } } + @Test - public void testGetCustomTrackingParameter_FT(){ + public void testGetCustomTrackingParameter_FT() { assertTrue(request.getCustomTrackingParameter("key").isEmpty()); } + @Test - public void testSetCustomTrackingParameter_T(){ - try{ + public void testSetCustomTrackingParameter_T() { + try { request.setCustomTrackingParameter(null, null); fail("Exception should have been thrown."); - } - catch(NullPointerException e){ + } catch (NullPointerException e) { assertEquals("Key cannot be null.", e.getLocalizedMessage()); - } + } } + @Test - public void testSetCustomTrackingParameter_F(){ + public void testSetCustomTrackingParameter_F() { request.setCustomTrackingParameter("key", "value"); List l = request.getCustomTrackingParameter("key"); assertEquals(1, l.size()); assertEquals("value", l.get(0)); - + request.setCustomTrackingParameter("key", "value2"); l = request.getCustomTrackingParameter("key"); assertEquals(1, l.size()); assertEquals("value2", l.get(0)); - + request.setCustomTrackingParameter("key", null); l = request.getCustomTrackingParameter("key"); assertTrue(l.isEmpty()); } + @Test - public void testAddCustomTrackingParameter_T(){ - try{ + public void testAddCustomTrackingParameter_T() { + try { request.addCustomTrackingParameter(null, null); fail("Exception should have been thrown."); - } - catch(NullPointerException e){ + } catch (NullPointerException e) { assertEquals("Key cannot be null.", e.getLocalizedMessage()); - } + } } + @Test - public void testAddCustomTrackingParameter_FT(){ - try{ + public void testAddCustomTrackingParameter_FT() { + try { request.addCustomTrackingParameter("key", null); fail("Exception should have been thrown."); - } - catch(NullPointerException e){ + } catch (NullPointerException e) { assertEquals("Cannot add a null custom tracking parameter.", e.getLocalizedMessage()); - } + } } + @Test - public void testAddCustomTrackingParameter_FF(){ + public void testAddCustomTrackingParameter_FF() { request.addCustomTrackingParameter("key", "value"); List l = request.getCustomTrackingParameter("key"); assertEquals(1, l.size()); assertEquals("value", l.get(0)); - + request.addCustomTrackingParameter("key", "value2"); l = request.getCustomTrackingParameter("key"); assertEquals(2, l.size()); assertTrue(l.contains("value")); assertTrue(l.contains("value2")); } + @Test - public void testClearCustomTrackingParameter(){ + public void testClearCustomTrackingParameter() { request.setCustomTrackingParameter("key", "value"); request.clearCustomTrackingParameter(); List l = request.getCustomTrackingParameter("key"); @@ -351,7 +346,7 @@ public void testClearCustomTrackingParameter(){ * Test of getDeviceResolution method, of class PiwikRequest. */ @Test - public void testDeviceResolution(){ + public void testDeviceResolution() { request.setDeviceResolution("1x2"); assertEquals("1x2", request.getDeviceResolution()); } @@ -360,27 +355,25 @@ public void testDeviceResolution(){ * Test of getDownloadUrl method, of class PiwikRequest. */ @Test - public void testDownloadUrl() throws Exception{ + public void testDownloadUrl() throws Exception { URL url = new URL("http://download.com"); request.setDownloadUrl(url); assertEquals(url, request.getDownloadUrl()); - - try{ + + try { request.getDownloadUrlAsString(); fail("Exception should have been thrown."); - } - catch(TypeConstraintException e){ + } catch (TypeConstraintException e) { assertEquals("The stored Download URL is a URL, not a String. Use \"getDownloadUrl\" instead.", e.getLocalizedMessage()); } - + request.setDownloadUrlWithString("downloadUrl"); assertEquals("downloadUrl", request.getDownloadUrlAsString()); - - try{ + + try { request.getDownloadUrl(); fail("Exception should have been thrown."); - } - catch(TypeConstraintException e){ + } catch (TypeConstraintException e) { assertEquals("The stored Download URL is a String, not a URL. Use \"getDownloadUrlAsString\" instead.", e.getLocalizedMessage()); } } @@ -389,7 +382,7 @@ public void testDownloadUrl() throws Exception{ * Test of enableEcommerce method, of class PiwikRequest. */ @Test - public void testEnableEcommerce(){ + public void testEnableEcommerce() { request.enableEcommerce(); assertEquals(new Integer(0), request.getGoalId()); } @@ -398,30 +391,30 @@ public void testEnableEcommerce(){ * Test of verifyEcommerceEnabled method, of class PiwikRequest. */ @Test - public void testVerifyEcommerceEnabledT(){ - try{ + public void testVerifyEcommerceEnabledT() { + try { request.verifyEcommerceEnabled(); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("GoalId must be \"0\". Try calling enableEcommerce first before calling this method.", e.getLocalizedMessage()); } } + @Test - public void testVerifyEcommerceEnabledFT(){ - try{ + public void testVerifyEcommerceEnabledFT() { + try { request.setGoalId(1); request.verifyEcommerceEnabled(); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("GoalId must be \"0\". Try calling enableEcommerce first before calling this method.", e.getLocalizedMessage()); } } + @Test - public void testVerifyEcommerceEnabledFF(){ + public void testVerifyEcommerceEnabledFF() { request.enableEcommerce(); request.verifyEcommerceEnabled(); } @@ -430,43 +423,43 @@ public void testVerifyEcommerceEnabledFF(){ * Test of verifyEcommerceState method, of class PiwikRequest. */ @Test - public void testVerifyEcommerceStateE(){ - try{ + public void testVerifyEcommerceStateE() { + try { request.verifyEcommerceState(); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("GoalId must be \"0\". Try calling enableEcommerce first before calling this method.", e.getLocalizedMessage()); } } + @Test - public void testVerifyEcommerceStateT(){ - try{ + public void testVerifyEcommerceStateT() { + try { request.enableEcommerce(); request.verifyEcommerceState(); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("EcommerceId must be set before this value can be set.", e.getLocalizedMessage()); } } + @Test - public void testVerifyEcommerceStateFT(){ - try{ + public void testVerifyEcommerceStateFT() { + try { request.enableEcommerce(); request.setEcommerceId("1"); request.verifyEcommerceState(); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("EcommerceRevenue must be set before this value can be set.", e.getLocalizedMessage()); } } + @Test - public void testVerifyEcommerceStateFF(){ + public void testVerifyEcommerceStateFF() { request.enableEcommerce(); request.setEcommerceId("1"); request.setEcommerceRevenue(2.0); @@ -477,29 +470,30 @@ public void testVerifyEcommerceStateFF(){ * Test of getEcommerceDiscount method, of class PiwikRequest. */ @Test - public void testEcommerceDiscountT(){ + public void testEcommerceDiscountT() { request.enableEcommerce(); request.setEcommerceId("1"); request.setEcommerceRevenue(2.0); request.setEcommerceDiscount(1.0); - + assertEquals(new Double(1.0), request.getEcommerceDiscount()); } + @Test - public void testEcommerceDiscountTE(){ - try{ + public void testEcommerceDiscountTE() { + try { request.setEcommerceDiscount(1.0); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("GoalId must be \"0\". Try calling enableEcommerce first before calling this method.", e.getLocalizedMessage()); } } + @Test - public void testEcommerceDiscountF(){ + public void testEcommerceDiscountF() { request.setEcommerceDiscount(null); - + assertNull(request.getEcommerceDiscount()); } @@ -507,27 +501,28 @@ public void testEcommerceDiscountF(){ * Test of getEcommerceId method, of class PiwikRequest. */ @Test - public void testEcommerceIdT(){ + public void testEcommerceIdT() { request.enableEcommerce(); request.setEcommerceId("1"); - + assertEquals("1", request.getEcommerceId()); } + @Test - public void testEcommerceIdTE(){ - try{ + public void testEcommerceIdTE() { + try { request.setEcommerceId("1"); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("GoalId must be \"0\". Try calling enableEcommerce first before calling this method.", e.getLocalizedMessage()); } } + @Test - public void testEcommerceIdF(){ + public void testEcommerceIdF() { request.setEcommerceId(null); - + assertNull(request.getEcommerceId()); } @@ -535,42 +530,42 @@ public void testEcommerceIdF(){ * Test of getEcommerceItem method, of class PiwikRequest. */ @Test - public void testEcommerceItemE(){ - try{ + public void testEcommerceItemE() { + try { EcommerceItem item = new EcommerceItem("sku", "name", "category", 1.0, 2); request.addEcommerceItem(item); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("GoalId must be \"0\". Try calling enableEcommerce first before calling this method.", e.getLocalizedMessage()); } } + @Test - public void testEcommerceItemE2(){ - try{ + public void testEcommerceItemE2() { + try { request.enableEcommerce(); request.setEcommerceId("1"); request.setEcommerceRevenue(2.0); request.addEcommerceItem(null); fail("Exception should have been thrown."); - } - catch(NullPointerException e){ + } catch (NullPointerException e) { assertEquals("Value cannot be null.", e.getLocalizedMessage()); } } + @Test - public void testEcommerceItem(){ + public void testEcommerceItem() { assertNull(request.getEcommerceItem(0)); - + EcommerceItem item = new EcommerceItem("sku", "name", "category", 1.0, 2); request.enableEcommerce(); request.setEcommerceId("1"); request.setEcommerceRevenue(2.0); request.addEcommerceItem(item); - + assertEquals(item, request.getEcommerceItem(0)); - + request.clearEcommerceItems(); assertNull(request.getEcommerceItem(0)); } @@ -579,29 +574,30 @@ public void testEcommerceItem(){ * Test of getEcommerceLastOrderTimestamp method, of class PiwikRequest. */ @Test - public void testEcommerceLastOrderTimestampT(){ + public void testEcommerceLastOrderTimestampT() { request.enableEcommerce(); request.setEcommerceId("1"); request.setEcommerceRevenue(2.0); request.setEcommerceLastOrderTimestamp(1000L); - + assertEquals(new Long(1000L), request.getEcommerceLastOrderTimestamp()); } + @Test - public void testEcommerceLastOrderTimestampTE(){ - try{ + public void testEcommerceLastOrderTimestampTE() { + try { request.setEcommerceLastOrderTimestamp(1000L); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("GoalId must be \"0\". Try calling enableEcommerce first before calling this method.", e.getLocalizedMessage()); } } + @Test - public void testEcommerceLastOrderTimestampF(){ + public void testEcommerceLastOrderTimestampF() { request.setEcommerceLastOrderTimestamp(null); - + assertNull(request.getEcommerceLastOrderTimestamp()); } @@ -609,28 +605,29 @@ public void testEcommerceLastOrderTimestampF(){ * Test of getEcommerceRevenue method, of class PiwikRequest. */ @Test - public void testEcommerceRevenueT(){ + public void testEcommerceRevenueT() { request.enableEcommerce(); request.setEcommerceId("1"); request.setEcommerceRevenue(20.0); - + assertEquals(new Double(20.0), request.getEcommerceRevenue()); } + @Test - public void testEcommerceRevenueTE(){ - try{ + public void testEcommerceRevenueTE() { + try { request.setEcommerceRevenue(20.0); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("GoalId must be \"0\". Try calling enableEcommerce first before calling this method.", e.getLocalizedMessage()); } } + @Test - public void testEcommerceRevenueF(){ + public void testEcommerceRevenueF() { request.setEcommerceRevenue(null); - + assertNull(request.getEcommerceRevenue()); } @@ -638,29 +635,30 @@ public void testEcommerceRevenueF(){ * Test of getEcommerceShippingCost method, of class PiwikRequest. */ @Test - public void testEcommerceShippingCostT(){ + public void testEcommerceShippingCostT() { request.enableEcommerce(); request.setEcommerceId("1"); request.setEcommerceRevenue(2.0); request.setEcommerceShippingCost(20.0); - + assertEquals(new Double(20.0), request.getEcommerceShippingCost()); } + @Test - public void testEcommerceShippingCostTE(){ - try{ + public void testEcommerceShippingCostTE() { + try { request.setEcommerceShippingCost(20.0); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("GoalId must be \"0\". Try calling enableEcommerce first before calling this method.", e.getLocalizedMessage()); } } + @Test - public void testEcommerceShippingCostF(){ + public void testEcommerceShippingCostF() { request.setEcommerceShippingCost(null); - + assertNull(request.getEcommerceShippingCost()); } @@ -668,29 +666,30 @@ public void testEcommerceShippingCostF(){ * Test of getEcommerceSubtotal method, of class PiwikRequest. */ @Test - public void testEcommerceSubtotalT(){ + public void testEcommerceSubtotalT() { request.enableEcommerce(); request.setEcommerceId("1"); request.setEcommerceRevenue(2.0); request.setEcommerceSubtotal(20.0); - + assertEquals(new Double(20.0), request.getEcommerceSubtotal()); } + @Test - public void testEcommerceSubtotalTE(){ - try{ + public void testEcommerceSubtotalTE() { + try { request.setEcommerceSubtotal(20.0); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("GoalId must be \"0\". Try calling enableEcommerce first before calling this method.", e.getLocalizedMessage()); } } + @Test - public void testEcommerceSubtotalF(){ + public void testEcommerceSubtotalF() { request.setEcommerceSubtotal(null); - + assertNull(request.getEcommerceSubtotal()); } @@ -698,29 +697,30 @@ public void testEcommerceSubtotalF(){ * Test of getEcommerceTax method, of class PiwikRequest. */ @Test - public void testEcommerceTaxT(){ + public void testEcommerceTaxT() { request.enableEcommerce(); request.setEcommerceId("1"); request.setEcommerceRevenue(2.0); request.setEcommerceTax(20.0); - + assertEquals(new Double(20.0), request.getEcommerceTax()); } + @Test - public void testEcommerceTaxTE(){ - try{ + public void testEcommerceTaxTE() { + try { request.setEcommerceTax(20.0); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("GoalId must be \"0\". Try calling enableEcommerce first before calling this method.", e.getLocalizedMessage()); } } + @Test - public void testEcommerceTaxF(){ + public void testEcommerceTaxF() { request.setEcommerceTax(null); - + assertNull(request.getEcommerceTax()); } @@ -728,19 +728,19 @@ public void testEcommerceTaxF(){ * Test of getEventAction method, of class PiwikRequest. */ @Test - public void testEventAction(){ + public void testEventAction() { request.setEventAction("action"); assertEquals("action", request.getEventAction()); request.setEventAction(null); assertNull(request.getEventAction()); } + @Test - public void testEventActionException(){ - try{ + public void testEventActionException() { + try { request.setEventAction(""); fail("Exception should have been thrown"); - } - catch(IllegalArgumentException e){ + } catch (IllegalArgumentException e) { assertEquals("Value cannot be empty.", e.getLocalizedMessage()); } } @@ -749,7 +749,7 @@ public void testEventActionException(){ * Test of getEventCategory method, of class PiwikRequest. */ @Test - public void testEventCategory(){ + public void testEventCategory() { request.setEventCategory("category"); assertEquals("category", request.getEventCategory()); } @@ -758,7 +758,7 @@ public void testEventCategory(){ * Test of getEventName method, of class PiwikRequest. */ @Test - public void testEventName(){ + public void testEventName() { request.setEventName("name"); assertEquals("name", request.getEventName()); } @@ -768,7 +768,7 @@ public void testEventName(){ * Test of getEventValue method, of class PiwikRequest. */ @Test - public void testEventValue(){ + public void testEventValue() { request.setEventValue(1); assertEquals(1, request.getEventValue()); } @@ -777,7 +777,7 @@ public void testEventValue(){ * Test of getGoalId method, of class PiwikRequest. */ @Test - public void testGoalId(){ + public void testGoalId() { request.setGoalId(1); assertEquals(new Integer(1), request.getGoalId()); } @@ -786,27 +786,28 @@ public void testGoalId(){ * Test of getGoalRevenue method, of class PiwikRequest. */ @Test - public void testGoalRevenueTT(){ - try{ + public void testGoalRevenueTT() { + try { request.setGoalRevenue(20.0); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("GoalId must be set before GoalRevenue can be set.", e.getLocalizedMessage()); } } + @Test - public void testGoalRevenueTF(){ + public void testGoalRevenueTF() { request.setGoalId(1); request.setGoalRevenue(20.0); - + assertEquals(new Double(20.0), request.getGoalRevenue()); } + @Test - public void testGoalRevenueF(){ + public void testGoalRevenueF() { request.setGoalRevenue(null); - + assertNull(request.getGoalRevenue()); } @@ -814,8 +815,8 @@ public void testGoalRevenueF(){ * Test of getHeaderAcceptLanguage method, of class PiwikRequest. */ @Test - public void testHeaderAcceptLanguage(){ - request.setHeaderAcceptLanguage("language"); + public void testHeaderAcceptLanguage() { + request.setHeaderAcceptLanguage("language"); assertEquals("language", request.getHeaderAcceptLanguage()); } @@ -823,7 +824,7 @@ public void testHeaderAcceptLanguage(){ * Test of getHeaderUserAgent method, of class PiwikRequest. */ @Test - public void testHeaderUserAgent(){ + public void testHeaderUserAgent() { request.setHeaderUserAgent("agent"); assertEquals("agent", request.getHeaderUserAgent()); } @@ -832,7 +833,7 @@ public void testHeaderUserAgent(){ * Test of getNewVisit method, of class PiwikRequest. */ @Test - public void testNewVisit(){ + public void testNewVisit() { request.setNewVisit(true); assertEquals(true, request.getNewVisit()); request.setNewVisit(null); @@ -843,27 +844,25 @@ public void testNewVisit(){ * Test of getOutlinkUrl method, of class PiwikRequest. */ @Test - public void testOutlinkUrl() throws Exception{ + public void testOutlinkUrl() throws Exception { URL url = new URL("http://outlink.com"); request.setOutlinkUrl(url); assertEquals(url, request.getOutlinkUrl()); - - try{ + + try { request.getOutlinkUrlAsString(); fail("Exception should have been thrown."); - } - catch(TypeConstraintException e){ + } catch (TypeConstraintException e) { assertEquals("The stored Outlink URL is a URL, not a String. Use \"getOutlinkUrl\" instead.", e.getLocalizedMessage()); } - + request.setOutlinkUrlWithString("outlinkUrl"); assertEquals("outlinkUrl", request.getOutlinkUrlAsString()); - - try{ + + try { request.getOutlinkUrl(); fail("Exception should have been thrown."); - } - catch(TypeConstraintException e){ + } catch (TypeConstraintException e) { assertEquals("The stored Outlink URL is a String, not a URL. Use \"getOutlinkUrlAsString\" instead.", e.getLocalizedMessage()); } } @@ -872,37 +871,37 @@ public void testOutlinkUrl() throws Exception{ * Test of getPageCustomVariable method, of class PiwikRequest. */ @Test - public void testPageCustomVariableStringStringE(){ - try{ + public void testPageCustomVariableStringStringE() { + try { request.setPageCustomVariable(null, null); fail("Exception should have been thrown"); - } - catch(NullPointerException e){ + } catch (NullPointerException e) { assertEquals("Key cannot be null.", e.getLocalizedMessage()); - } + } } + @Test - public void testPageCustomVariableStringStringE2(){ - try{ + public void testPageCustomVariableStringStringE2() { + try { request.setPageCustomVariable(null, "pageVal"); fail("Exception should have been thrown"); - } - catch(NullPointerException e){ + } catch (NullPointerException e) { assertEquals("Key cannot be null.", e.getLocalizedMessage()); - } + } } + @Test - public void testPageCustomVariableStringStringE3(){ - try{ + public void testPageCustomVariableStringStringE3() { + try { request.getPageCustomVariable(null); fail("Exception should have been thrown"); - } - catch(NullPointerException e){ + } catch (NullPointerException e) { assertEquals("Key cannot be null.", e.getLocalizedMessage()); - } + } } + @Test - public void testPageCustomVariableStringString(){ + public void testPageCustomVariableStringString() { assertNull(request.getPageCustomVariable("pageKey")); request.setPageCustomVariable("pageKey", "pageVal"); assertEquals("pageVal", request.getPageCustomVariable("pageKey")); @@ -911,8 +910,9 @@ public void testPageCustomVariableStringString(){ request.setPageCustomVariable("pageKey", "pageVal"); assertEquals("pageVal", request.getPageCustomVariable("pageKey")); } + @Test - public void testPageCustomVariableCustomVariable(){ + public void testPageCustomVariableCustomVariable() { assertNull(request.getPageCustomVariable(1)); CustomVariable cv = new CustomVariable("pageKey", "pageVal"); request.setPageCustomVariable(cv, 1); @@ -927,7 +927,7 @@ public void testPageCustomVariableCustomVariable(){ * Test of getPluginDirector method, of class PiwikRequest. */ @Test - public void testPluginDirector(){ + public void testPluginDirector() { request.setPluginDirector(true); assertEquals(true, request.getPluginDirector()); } @@ -936,7 +936,7 @@ public void testPluginDirector(){ * Test of getPluginFlash method, of class PiwikRequest. */ @Test - public void testPluginFlash(){ + public void testPluginFlash() { request.setPluginFlash(true); assertEquals(true, request.getPluginFlash()); } @@ -945,7 +945,7 @@ public void testPluginFlash(){ * Test of getPluginGears method, of class PiwikRequest. */ @Test - public void testPluginGears(){ + public void testPluginGears() { request.setPluginGears(true); assertEquals(true, request.getPluginGears()); } @@ -954,7 +954,7 @@ public void testPluginGears(){ * Test of getPluginJava method, of class PiwikRequest. */ @Test - public void testPluginJava(){ + public void testPluginJava() { request.setPluginJava(true); assertEquals(true, request.getPluginJava()); } @@ -963,7 +963,7 @@ public void testPluginJava(){ * Test of getPluginPDF method, of class PiwikRequest. */ @Test - public void testPluginPDF(){ + public void testPluginPDF() { request.setPluginPDF(true); assertEquals(true, request.getPluginPDF()); } @@ -972,7 +972,7 @@ public void testPluginPDF(){ * Test of getPluginQuicktime method, of class PiwikRequest. */ @Test - public void testPluginQuicktime(){ + public void testPluginQuicktime() { request.setPluginQuicktime(true); assertEquals(true, request.getPluginQuicktime()); } @@ -981,7 +981,7 @@ public void testPluginQuicktime(){ * Test of getPluginRealPlayer method, of class PiwikRequest. */ @Test - public void testPluginRealPlayer(){ + public void testPluginRealPlayer() { request.setPluginRealPlayer(true); assertEquals(true, request.getPluginRealPlayer()); } @@ -990,7 +990,7 @@ public void testPluginRealPlayer(){ * Test of getPluginSilverlight method, of class PiwikRequest. */ @Test - public void testPluginSilverlight(){ + public void testPluginSilverlight() { request.setPluginSilverlight(true); assertEquals(true, request.getPluginSilverlight()); } @@ -999,7 +999,7 @@ public void testPluginSilverlight(){ * Test of getPluginWindowsMedia method, of class PiwikRequest. */ @Test - public void testPluginWindowsMedia(){ + public void testPluginWindowsMedia() { request.setPluginWindowsMedia(true); assertEquals(true, request.getPluginWindowsMedia()); } @@ -1008,7 +1008,7 @@ public void testPluginWindowsMedia(){ * Test of getRandomValue method, of class PiwikRequest. */ @Test - public void testRandomValue(){ + public void testRandomValue() { request.setRandomValue("value"); assertEquals("value", request.getRandomValue()); } @@ -1017,27 +1017,25 @@ public void testRandomValue(){ * Test of setReferrerUrl method, of class PiwikRequest. */ @Test - public void testReferrerUrl() throws Exception{ + public void testReferrerUrl() throws Exception { URL url = new URL("http://referrer.com"); request.setReferrerUrl(url); assertEquals(url, request.getReferrerUrl()); - - try{ + + try { request.getReferrerUrlAsString(); fail("Exception should have been thrown."); - } - catch(TypeConstraintException e){ + } catch (TypeConstraintException e) { assertEquals("The stored Referrer URL is a URL, not a String. Use \"getReferrerUrl\" instead.", e.getLocalizedMessage()); } - + request.setReferrerUrlWithString("referrerUrl"); assertEquals("referrerUrl", request.getReferrerUrlAsString()); - - try{ + + try { request.getReferrerUrl(); fail("Exception should have been thrown."); - } - catch(TypeConstraintException e){ + } catch (TypeConstraintException e) { assertEquals("The stored Referrer URL is a String, not a URL. Use \"getReferrerUrlAsString\" instead.", e.getLocalizedMessage()); } } @@ -1046,33 +1044,35 @@ public void testReferrerUrl() throws Exception{ * Test of getRequestDatetime method, of class PiwikRequest. */ @Test - public void testRequestDatetimeTTT(){ + public void testRequestDatetimeTTT() { request.setAuthToken("12345678901234567890123456789012"); PiwikDate date = new PiwikDate(1000L); request.setRequestDatetime(date); - + assertEquals(date, request.getRequestDatetime()); } + @Test - public void testRequestDatetimeTTF(){ - try{ + public void testRequestDatetimeTTF() { + try { PiwikDate date = new PiwikDate(1000L); request.setRequestDatetime(date); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("Because you are trying to set RequestDatetime for a time greater than 4 hours ago, AuthToken must be set first.", e.getLocalizedMessage()); } } + @Test - public void testRequestDatetimeTF(){ + public void testRequestDatetimeTF() { PiwikDate date = new PiwikDate(); request.setRequestDatetime(date); assertEquals(date, request.getRequestDatetime()); } + @Test - public void testRequestDatetimeF(){ + public void testRequestDatetimeF() { PiwikDate date = new PiwikDate(); request.setRequestDatetime(date); request.setRequestDatetime(null); @@ -1083,7 +1083,7 @@ public void testRequestDatetimeF(){ * Test of getRequired method, of class PiwikRequest. */ @Test - public void testRequired(){ + public void testRequired() { request.setRequired(false); assertEquals(false, request.getRequired()); } @@ -1092,7 +1092,7 @@ public void testRequired(){ * Test of getResponseAsImage method, of class PiwikRequest. */ @Test - public void testResponseAsImage(){ + public void testResponseAsImage() { request.setResponseAsImage(true); assertEquals(true, request.getResponseAsImage()); } @@ -1101,24 +1101,25 @@ public void testResponseAsImage(){ * Test of getSearchCategory method, of class PiwikRequest. */ @Test - public void testSearchCategoryTT(){ - try{ + public void testSearchCategoryTT() { + try { request.setSearchCategory("category"); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("SearchQuery must be set before SearchCategory can be set.", e.getLocalizedMessage()); } } + @Test - public void testSearchCategoryTF(){ + public void testSearchCategoryTF() { request.setSearchQuery("query"); request.setSearchCategory("category"); assertEquals("category", request.getSearchCategory()); } + @Test - public void testSearchCategoryF(){ + public void testSearchCategoryF() { request.setSearchCategory(null); assertNull(request.getSearchCategory()); } @@ -1127,7 +1128,7 @@ public void testSearchCategoryF(){ * Test of getSearchQuery method, of class PiwikRequest. */ @Test - public void testSearchQuery(){ + public void testSearchQuery() { request.setSearchQuery("query"); assertEquals("query", request.getSearchQuery()); } @@ -1136,24 +1137,25 @@ public void testSearchQuery(){ * Test of getSearchResultsCount method, of class PiwikRequest. */ @Test - public void testSearchResultsCountTT(){ - try{ + public void testSearchResultsCountTT() { + try { request.setSearchResultsCount(100L); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("SearchQuery must be set before SearchResultsCount can be set.", e.getLocalizedMessage()); } } + @Test - public void testSearchResultsCountTF(){ + public void testSearchResultsCountTF() { request.setSearchQuery("query"); request.setSearchResultsCount(100L); assertEquals(new Long(100L), request.getSearchResultsCount()); } + @Test - public void testSearchResultsCountF(){ + public void testSearchResultsCountF() { request.setSearchResultsCount(null); assertNull(request.getSearchResultsCount()); } @@ -1162,7 +1164,7 @@ public void testSearchResultsCountF(){ * Test of getSiteId method, of class PiwikRequest. */ @Test - public void testSiteId(){ + public void testSiteId() { request.setSiteId(2); assertEquals(new Integer(2), request.getSiteId()); } @@ -1171,7 +1173,7 @@ public void testSiteId(){ * Test of setTrackBotRequest method, of class PiwikRequest. */ @Test - public void testTrackBotRequests(){ + public void testTrackBotRequests() { request.setTrackBotRequests(true); assertEquals(true, request.getTrackBotRequests()); } @@ -1181,32 +1183,33 @@ public void testTrackBotRequests(){ * Test of getUserrCustomVariable method, of class PiwikRequest. */ @Test - public void testUserCustomVariableStringString(){ + public void testUserCustomVariableStringString() { request.setUserCustomVariable("userKey", "userValue"); assertEquals("userValue", request.getUserCustomVariable("userKey")); } + @Test - public void testVisitCustomVariableCustomVariable(){ + public void testVisitCustomVariableCustomVariable() { request.setRandomValue("random"); request.setVisitorId("1234567890123456"); - + assertNull(request.getVisitCustomVariable(1)); CustomVariable cv = new CustomVariable("visitKey", "visitVal"); request.setVisitCustomVariable(cv, 1); assertEquals("rand=random&idsite=3&rec=1&apiv=1&send_image=0&_cvar={\"1\":[\"visitKey\",\"visitVal\"]}&_id=1234567890123456&url=http://test.com", request.getQueryString()); - + request.setUserCustomVariable("key", "val"); assertEquals(cv, request.getVisitCustomVariable(1)); assertEquals("rand=random&idsite=3&rec=1&apiv=1&send_image=0&_cvar={\"1\":[\"visitKey\",\"visitVal\"],\"2\":[\"key\",\"val\"]}&_id=1234567890123456&url=http://test.com", request.getQueryString()); - + request.setVisitCustomVariable(null, 1); assertNull(request.getVisitCustomVariable(1)); assertEquals("rand=random&idsite=3&rec=1&apiv=1&send_image=0&_cvar={\"2\":[\"key\",\"val\"]}&_id=1234567890123456&url=http://test.com", request.getQueryString()); - + request.setVisitCustomVariable(cv, 2); assertEquals(cv, request.getVisitCustomVariable(2)); assertEquals("rand=random&idsite=3&rec=1&apiv=1&send_image=0&_cvar={\"2\":[\"visitKey\",\"visitVal\"]}&_id=1234567890123456&url=http://test.com", request.getQueryString()); - + request.setUserCustomVariable("visitKey", null); assertEquals("rand=random&idsite=3&rec=1&apiv=1&send_image=0&_id=1234567890123456&url=http://test.com", request.getQueryString()); } @@ -1215,7 +1218,7 @@ public void testVisitCustomVariableCustomVariable(){ * Test of getUserId method, of class PiwikRequest. */ @Test - public void testUserId(){ + public void testUserId() { request.setUserId("id"); assertEquals("id", request.getUserId()); } @@ -1224,24 +1227,25 @@ public void testUserId(){ * Test of getVisitorCity method, of class PiwikRequest. */ @Test - public void testVisitorCityT(){ + public void testVisitorCityT() { request.setAuthToken("12345678901234567890123456789012"); request.setVisitorCity("city"); assertEquals("city", request.getVisitorCity()); } + @Test - public void testVisitorCityTE(){ - try{ + public void testVisitorCityTE() { + try { request.setVisitorCity("city"); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("AuthToken must be set before this value can be set.", e.getLocalizedMessage()); } } + @Test - public void testVisitorCityF(){ + public void testVisitorCityF() { request.setVisitorCity(null); assertNull(request.getVisitorCity()); } @@ -1250,29 +1254,30 @@ public void testVisitorCityF(){ * Test of getVisitorCountry method, of class PiwikRequest. */ @Test - public void testVisitorCountryT(){ + public void testVisitorCountryT() { PiwikLocale country = new PiwikLocale(Locale.US); request.setAuthToken("12345678901234567890123456789012"); request.setVisitorCountry(country); - + assertEquals(country, request.getVisitorCountry()); } + @Test - public void testVisitorCountryTE(){ - try{ + public void testVisitorCountryTE() { + try { PiwikLocale country = new PiwikLocale(Locale.US); request.setVisitorCountry(country); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("AuthToken must be set before this value can be set.", e.getLocalizedMessage()); } } + @Test - public void testVisitorCountryF(){ + public void testVisitorCountryF() { request.setVisitorCountry(null); - + assertNull(request.getVisitorCountry()); } @@ -1280,34 +1285,35 @@ public void testVisitorCountryF(){ * Test of getVisitorCustomId method, of class PiwikRequest. */ @Test - public void testVisitorCustomTT(){ - try{ + public void testVisitorCustomTT() { + try { request.setVisitorCustomId("1"); fail("Exception should have been thrown."); - } - catch(IllegalArgumentException e){ + } catch (IllegalArgumentException e) { assertEquals("1 is not 16 characters long.", e.getLocalizedMessage()); } } + @Test - public void testVisitorCustomTFT(){ - try{ + public void testVisitorCustomTFT() { + try { request.setVisitorCustomId("1234567890abcdeg"); fail("Exception should have been thrown."); - } - catch(IllegalArgumentException e){ + } catch (IllegalArgumentException e) { assertEquals("1234567890abcdeg is not a hexadecimal string.", e.getLocalizedMessage()); } } + @Test - public void testVisitorCustomIdTFF(){ + public void testVisitorCustomIdTFF() { request.setVisitorCustomId("1234567890abcdef"); assertEquals("1234567890abcdef", request.getVisitorCustomId()); } + @Test - public void testVisitorCustomIdF(){ + public void testVisitorCustomIdF() { request.setVisitorCustomId("1234567890abcdef"); request.setVisitorCustomId(null); assertNull(request.getVisitorCustomId()); @@ -1317,7 +1323,7 @@ public void testVisitorCustomIdF(){ * Test of getVisitorFirstVisitTimestamp method, of class PiwikRequest. */ @Test - public void testVisitorFirstVisitTimestamp(){ + public void testVisitorFirstVisitTimestamp() { request.setVisitorFirstVisitTimestamp(1000L); assertEquals(new Long(1000L), request.getVisitorFirstVisitTimestamp()); } @@ -1326,34 +1332,35 @@ public void testVisitorFirstVisitTimestamp(){ * Test of getVisitorId method, of class PiwikRequest. */ @Test - public void testVisitorIdTT(){ - try{ + public void testVisitorIdTT() { + try { request.setVisitorId("1"); fail("Exception should have been thrown."); - } - catch(IllegalArgumentException e){ + } catch (IllegalArgumentException e) { assertEquals("1 is not 16 characters long.", e.getLocalizedMessage()); } } + @Test - public void testVisitorIdTFT(){ - try{ + public void testVisitorIdTFT() { + try { request.setVisitorId("1234567890abcdeg"); fail("Exception should have been thrown."); - } - catch(IllegalArgumentException e){ + } catch (IllegalArgumentException e) { assertEquals("1234567890abcdeg is not a hexadecimal string.", e.getLocalizedMessage()); } } + @Test - public void testVisitorIdTFF(){ + public void testVisitorIdTFF() { request.setVisitorId("1234567890abcdef"); assertEquals("1234567890abcdef", request.getVisitorId()); } + @Test - public void testVisitorIdF(){ + public void testVisitorIdF() { request.setVisitorId("1234567890abcdef"); request.setVisitorId(null); assertNull(request.getVisitorId()); @@ -1363,24 +1370,25 @@ public void testVisitorIdF(){ * Test of getVisitorIp method, of class PiwikRequest. */ @Test - public void testVisitorIpT(){ + public void testVisitorIpT() { request.setAuthToken("12345678901234567890123456789012"); request.setVisitorIp("ip"); assertEquals("ip", request.getVisitorIp()); } + @Test - public void testVisitorIpTE(){ - try{ + public void testVisitorIpTE() { + try { request.setVisitorIp("ip"); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("AuthToken must be set before this value can be set.", e.getLocalizedMessage()); } } + @Test - public void testVisitorIpF(){ + public void testVisitorIpF() { request.setVisitorIp(null); assertNull(request.getVisitorIp()); } @@ -1389,24 +1397,25 @@ public void testVisitorIpF(){ * Test of getVisitorLatitude method, of class PiwikRequest. */ @Test - public void testVisitorLatitudeT(){ + public void testVisitorLatitudeT() { request.setAuthToken("12345678901234567890123456789012"); request.setVisitorLatitude(10.5); assertEquals(new Double(10.5), request.getVisitorLatitude()); } + @Test - public void testVisitorLatitudeTE(){ - try{ + public void testVisitorLatitudeTE() { + try { request.setVisitorLatitude(10.5); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("AuthToken must be set before this value can be set.", e.getLocalizedMessage()); } } + @Test - public void testVisitorLatitudeF(){ + public void testVisitorLatitudeF() { request.setVisitorLatitude(null); assertNull(request.getVisitorLatitude()); } @@ -1415,24 +1424,25 @@ public void testVisitorLatitudeF(){ * Test of getVisitorLongitude method, of class PiwikRequest. */ @Test - public void testVisitorLongitudeT(){ + public void testVisitorLongitudeT() { request.setAuthToken("12345678901234567890123456789012"); request.setVisitorLongitude(20.5); assertEquals(new Double(20.5), request.getVisitorLongitude()); } + @Test - public void testVisitorLongitudeTE(){ - try{ + public void testVisitorLongitudeTE() { + try { request.setVisitorLongitude(20.5); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("AuthToken must be set before this value can be set.", e.getLocalizedMessage()); } } + @Test - public void testVisitorLongitudeF(){ + public void testVisitorLongitudeF() { request.setVisitorLongitude(null); assertNull(request.getVisitorLongitude()); } @@ -1441,7 +1451,7 @@ public void testVisitorLongitudeF(){ * Test of getVisitorPreviousVisitTimestamp method, of class PiwikRequest. */ @Test - public void testVisitorPreviousVisitTimestamp(){ + public void testVisitorPreviousVisitTimestamp() { request.setVisitorPreviousVisitTimestamp(1000L); assertEquals(new Long(1000L), request.getVisitorPreviousVisitTimestamp()); } @@ -1450,27 +1460,28 @@ public void testVisitorPreviousVisitTimestamp(){ * Test of getVisitorRegion method, of class PiwikRequest. */ @Test - public void testVisitorRegionT(){ + public void testVisitorRegionT() { request.setAuthToken("12345678901234567890123456789012"); request.setVisitorRegion("region"); - + assertEquals("region", request.getVisitorRegion()); } + @Test - public void testGetVisitorRegionTE(){ - try{ + public void testGetVisitorRegionTE() { + try { request.setVisitorRegion("region"); fail("Exception should have been thrown."); - } - catch(IllegalStateException e){ + } catch (IllegalStateException e) { assertEquals("AuthToken must be set before this value can be set.", e.getLocalizedMessage()); } } + @Test - public void testVisitorRegionF(){ + public void testVisitorRegionF() { request.setVisitorRegion(null); - + assertNull(request.getVisitorRegion()); } @@ -1478,7 +1489,7 @@ public void testVisitorRegionF(){ * Test of getVisitorVisitCount method, of class PiwikRequest. */ @Test - public void testVisitorVisitCount(){ + public void testVisitorVisitCount() { request.setVisitorVisitCount(100); assertEquals(new Integer(100), request.getVisitorVisitCount()); } @@ -1487,7 +1498,7 @@ public void testVisitorVisitCount(){ * Test of getQueryString method, of class PiwikRequest. */ @Test - public void testGetQueryString(){ + public void testGetQueryString() { request.setRandomValue("random"); request.setVisitorId("1234567890123456"); assertEquals("rand=random&idsite=3&rec=1&apiv=1&send_image=0&_id=1234567890123456&url=http://test.com", request.getQueryString()); @@ -1515,8 +1526,9 @@ public void testGetQueryString(){ request.clearCustomTrackingParameter(); assertEquals("", request.getQueryString()); } + @Test - public void testGetQueryString2(){ + public void testGetQueryString2() { request.setActionUrlWithString("http://test.com"); request.setRandomValue("random"); request.setVisitorId("1234567890123456"); @@ -1527,7 +1539,7 @@ public void testGetQueryString2(){ * Test of getUrlEncodedQueryString method, of class PiwikRequest. */ @Test - public void testGetUrlEncodedQueryString(){ + public void testGetUrlEncodedQueryString() { request.setRandomValue("random"); request.setVisitorId("1234567890123456"); assertEquals("rand=random&idsite=3&rec=1&apiv=1&send_image=0&_id=1234567890123456&url=http%3A%2F%2Ftest.com", request.getUrlEncodedQueryString()); @@ -1550,8 +1562,9 @@ public void testGetUrlEncodedQueryString(){ request.clearCustomTrackingParameter(); assertEquals("", request.getUrlEncodedQueryString()); } + @Test - public void testGetUrlEncodedQueryString2(){ + public void testGetUrlEncodedQueryString2() { request.setActionUrlWithString("http://test.com"); request.setRandomValue("random"); request.setVisitorId("1234567890123456"); @@ -1562,9 +1575,9 @@ public void testGetUrlEncodedQueryString2(){ * Test of getRandomHexString method, of class PiwikRequest. */ @Test - public void testGetRandomHexString(){ + public void testGetRandomHexString() { String s = PiwikRequest.getRandomHexString(10); - + assertEquals(10, s.length()); Long.parseLong(s, 16); } diff --git a/src/test/java/org/piwik/java/tracking/PiwikTrackerTest.java b/src/test/java/org/piwik/java/tracking/PiwikTrackerTest.java index 0a4d27a5..9ad02895 100644 --- a/src/test/java/org/piwik/java/tracking/PiwikTrackerTest.java +++ b/src/test/java/org/piwik/java/tracking/PiwikTrackerTest.java @@ -1,107 +1,86 @@ -/* +/* * Piwik Java Tracker - * + * * @link https://github.com/piwik/piwik-java-tracker * @license https://github.com/piwik/piwik-java-tracker/blob/master/LICENSE BSD-3 Clause */ package org.piwik.java.tracking; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; -import org.junit.After; -import org.junit.AfterClass; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.*; import org.mockito.ArgumentMatcher; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.*; import static org.mockito.Matchers.argThat; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.*; /** - * * @author brettcsorba */ -public class PiwikTrackerTest{ +public class PiwikTrackerTest { PiwikTracker piwikTracker; - - public PiwikTrackerTest(){ + + public PiwikTrackerTest() { } - + @BeforeClass - public static void setUpClass(){ + public static void setUpClass() { } - + @AfterClass - public static void tearDownClass(){ + public static void tearDownClass() { } - + @Before - public void setUp(){ + public void setUp() { piwikTracker = spy(new PiwikTracker("http://test.com")); } - + @After - public void tearDown(){ + public void tearDown() { } /** * Test of addParameter method, of class PiwikTracker. */ @Test - public void testAddParameter(){ + public void testAddParameter() { } /** * Test of sendRequest method, of class PiwikTracker. */ @Test - public void testSendRequest() throws Exception{ + public void testSendRequest() throws Exception { PiwikRequest request = mock(PiwikRequest.class); HttpClient client = mock(HttpClient.class); HttpResponse response = mock(HttpResponse.class); - + doReturn(client).when(piwikTracker).getHttpClient(); doReturn("query").when(request).getQueryString(); doReturn(response).when(client).execute(argThat(new CorrectGetRequest("http://test.com?query"))); - - assertEquals(response, piwikTracker.sendRequest(request)); - } - - class CorrectGetRequest extends ArgumentMatcher{ - String url; - - public CorrectGetRequest(String url){ - this.url = url; - } - @Override - public boolean matches(Object argument){ - HttpGet get = (HttpGet)argument; - return url.equals(get.getURI().toString()); - } + assertEquals(response, piwikTracker.sendRequest(request)); } /** * Test of sendBulkRequest method, of class PiwikTracker. */ @Test - public void testSendBulkRequest_Iterable() throws Exception{ + public void testSendBulkRequest_Iterable() throws Exception { List requests = new ArrayList<>(); HttpResponse response = mock(HttpResponse.class); - + doReturn(response).when(piwikTracker).sendBulkRequest(requests, null); - + assertEquals(response, piwikTracker.sendBulkRequest(requests)); } @@ -109,92 +88,106 @@ public void testSendBulkRequest_Iterable() throws Exception{ * Test of sendBulkRequest method, of class PiwikTracker. */ @Test - public void testSendBulkRequest_Iterable_StringTT() throws Exception{ - try{ + public void testSendBulkRequest_Iterable_StringTT() throws Exception { + try { List requests = new ArrayList<>(); HttpClient client = mock(HttpClient.class); PiwikRequest request = mock(PiwikRequest.class); - + doReturn("query").when(request).getQueryString(); - requests.add(request); + requests.add(request); doReturn(client).when(piwikTracker).getHttpClient(); - + piwikTracker.sendBulkRequest(requests, "1"); fail("Exception should have been thrown."); - } - catch(IllegalArgumentException e){ + } catch (IllegalArgumentException e) { assertEquals("1 is not 32 characters long.", e.getLocalizedMessage()); } } + @Test - public void testSendBulkRequest_Iterable_StringFF() throws Exception{ + public void testSendBulkRequest_Iterable_StringFF() throws Exception { List requests = new ArrayList<>(); HttpClient client = mock(HttpClient.class); PiwikRequest request = mock(PiwikRequest.class); HttpResponse response = mock(HttpResponse.class); - + doReturn("query").when(request).getQueryString(); - requests.add(request); + requests.add(request); doReturn(client).when(piwikTracker).getHttpClient(); doReturn(response).when(client).execute(argThat(new CorrectPostRequest("{\"requests\":[\"?query\"]}"))); - + assertEquals(response, piwikTracker.sendBulkRequest(requests, null)); } + @Test - public void testSendBulkRequest_Iterable_StringFT() throws Exception{ + public void testSendBulkRequest_Iterable_StringFT() throws Exception { List requests = new ArrayList<>(); HttpClient client = mock(HttpClient.class); PiwikRequest request = mock(PiwikRequest.class); HttpResponse response = mock(HttpResponse.class); - + doReturn("query").when(request).getQueryString(); - requests.add(request); + requests.add(request); doReturn(client).when(piwikTracker).getHttpClient(); doReturn(response).when(client).execute(argThat(new CorrectPostRequest("{\"requests\":[\"?query\"],\"token_auth\":\"12345678901234567890123456789012\"}"))); - - assertEquals(response, piwikTracker.sendBulkRequest(requests, "12345678901234567890123456789012")); - } - - class CorrectPostRequest extends ArgumentMatcher{ - String body; - - public CorrectPostRequest(String body){ - this.body = body; - } - @Override - public boolean matches(Object argument){ - try{ - HttpPost post = (HttpPost)argument; - InputStream bais = post.getEntity().getContent(); - byte[] bytes = new byte[bais.available()]; - bais.read(bytes); - String str = new String(bytes); - return body.equals(str); - } - catch(IOException e){ - fail("Exception should not have been throw."); - } - return false; - } + assertEquals(response, piwikTracker.sendBulkRequest(requests, "12345678901234567890123456789012")); } /** * Test of getHttpClient method, of class PiwikTracker. */ @Test - public void testGetHttpClient(){ + public void testGetHttpClient() { assertNotNull(piwikTracker.getHttpClient()); } - + /** * Test of getHttpClient method, of class PiwikTracker, with proxy. */ @Test - public void testGetHttpClientWithProxy(){ + public void testGetHttpClientWithProxy() { piwikTracker = new PiwikTracker("http://test.com", "http://proxy", 8080); HttpClient httpClient = piwikTracker.getHttpClient(); assertNotNull(piwikTracker.getHttpClient()); } + + class CorrectGetRequest extends ArgumentMatcher { + String url; + + public CorrectGetRequest(String url) { + this.url = url; + } + + @Override + public boolean matches(Object argument) { + HttpGet get = (HttpGet) argument; + return url.equals(get.getURI().toString()); + } + } + + class CorrectPostRequest extends ArgumentMatcher { + String body; + + public CorrectPostRequest(String body) { + this.body = body; + } + + @Override + public boolean matches(Object argument) { + try { + HttpPost post = (HttpPost) argument; + InputStream bais = post.getEntity().getContent(); + byte[] bytes = new byte[bais.available()]; + bais.read(bytes); + String str = new String(bytes); + return body.equals(str); + } catch (IOException e) { + fail("Exception should not have been throw."); + } + return false; + } + } } From 1fdb4cf3341a60477d9367cc86d8a154d4cdd6e8 Mon Sep 17 00:00:00 2001 From: Marvin Date: Sat, 15 Dec 2018 18:25:36 +0100 Subject: [PATCH 04/10] Optimize and refactor code Signed-off-by: Marvin --- .../java/tracking/CustomVariableList.java | 28 +--- .../org/piwik/java/tracking/PiwikRequest.java | 123 +++++++----------- 2 files changed, 54 insertions(+), 97 deletions(-) diff --git a/src/main/java/org/piwik/java/tracking/CustomVariableList.java b/src/main/java/org/piwik/java/tracking/CustomVariableList.java index 7575b190..ce4789c0 100644 --- a/src/main/java/org/piwik/java/tracking/CustomVariableList.java +++ b/src/main/java/org/piwik/java/tracking/CustomVariableList.java @@ -10,7 +10,6 @@ import javax.json.JsonArrayBuilder; import javax.json.JsonObjectBuilder; import java.util.HashMap; -import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; @@ -53,14 +52,7 @@ CustomVariable get(int index) { } String get(String key) { - Iterator> i = map.entrySet().iterator(); - while (i.hasNext()) { - CustomVariable value = i.next().getValue(); - if (value.getKey().equals(key)) { - return value.getValue(); - } - } - return null; + return map.values().stream().filter(value -> value.getKey().equals(key)).findFirst().map(CustomVariable::getValue).orElse(null); } void remove(int index) { @@ -68,13 +60,7 @@ void remove(int index) { } void remove(String key) { - Iterator> i = map.entrySet().iterator(); - while (i.hasNext()) { - Entry entry = i.next(); - if (entry.getValue().getKey().equals(key)) { - i.remove(); - } - } + map.entrySet().removeIf(entry -> entry.getValue().getKey().equals(key)); } boolean isEmpty() { @@ -85,12 +71,12 @@ boolean isEmpty() { public String toString() { JsonObjectBuilder ob = Json.createObjectBuilder(); - for (Entry entry : map.entrySet()) { + map.forEach((key, value) -> { JsonArrayBuilder ab = Json.createArrayBuilder(); - ab.add(entry.getValue().getKey()); - ab.add(entry.getValue().getValue()); - ob.add(entry.getKey().toString(), ab); - } + ab.add(value.getKey()); + ab.add(value.getValue()); + ob.add(key.toString(), ab); + }); return ob.build().toString(); } diff --git a/src/main/java/org/piwik/java/tracking/PiwikRequest.java b/src/main/java/org/piwik/java/tracking/PiwikRequest.java index 69237c3a..17695a22 100644 --- a/src/main/java/org/piwik/java/tracking/PiwikRequest.java +++ b/src/main/java/org/piwik/java/tracking/PiwikRequest.java @@ -14,7 +14,7 @@ import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.*; -import java.util.Map.Entry; +import java.util.regex.Pattern; /** * A class that implements the @@ -22,6 +22,7 @@ * * @author brettcsorba */ +@SuppressWarnings({"WeakerAccess", "SameParameterValue", "CharsetObjectCanBeUsed"}) public class PiwikRequest { public static final int ID_LENGTH = 16; public static final int AUTH_TOKEN_LENGTH = 32; @@ -97,9 +98,10 @@ public class PiwikRequest { private static final int RANDOM_VALUE_LENGTH = 20; private static final long REQUEST_DATETIME_AUTH_LIMIT = 14400000L; + private static final Pattern VISITOR_ID_PATTERN = Pattern.compile("[0-9A-Fa-f]+"); private final Map parameters = new HashMap<>(); - private final Map customTrackingParameters = new HashMap<>(); + private final Map> customTrackingParameters = new HashMap<>(); /** * Create a new request from the id of the site being tracked and the full @@ -489,15 +491,15 @@ public void setCurrentSecond(Integer currentSecond) { * @param key the key of the parameter whose list of objects to get. Cannot be null * @return the list of objects currently stored at the specified key */ - public List getCustomTrackingParameter(String key) { + public List getCustomTrackingParameter(String key) { if (key == null) { throw new NullPointerException("Key cannot be null."); } - List l = customTrackingParameters.get(key); + List l = customTrackingParameters.get(key); if (l == null) { - return new ArrayList(0); + return new ArrayList<>(0); } - return new ArrayList(l); + return new ArrayList<>(l); } /** @@ -510,14 +512,14 @@ public List getCustomTrackingParameter(String key) { * @param key the parameter's key. Cannot be null * @param value the parameter's value. Removes the parameter if null */ - public void setCustomTrackingParameter(String key, Object value) { + public void setCustomTrackingParameter(String key, String value) { if (key == null) { throw new NullPointerException("Key cannot be null."); } if (value == null) { customTrackingParameters.remove(key); } else { - List l = new ArrayList(); + List l = new ArrayList<>(); l.add(value); customTrackingParameters.put(key, l); } @@ -531,18 +533,14 @@ public void setCustomTrackingParameter(String key, Object value) { * @param key the parameter's key. Cannot be null * @param value the parameter's value. Cannot be null */ - public void addCustomTrackingParameter(String key, Object value) { + public void addCustomTrackingParameter(String key, String value) { if (key == null) { throw new NullPointerException("Key cannot be null."); } if (value == null) { throw new NullPointerException("Cannot add a null custom tracking parameter."); } else { - List l = customTrackingParameters.get(key); - if (l == null) { - l = new ArrayList(); - customTrackingParameters.put(key, l); - } + List l = customTrackingParameters.computeIfAbsent(key, k -> new ArrayList<>()); l.add(value); } } @@ -1617,16 +1615,7 @@ public String getVisitorCustomId() { * @param visitorCustomId the visitor's custom id to set. A null value will remove this parameter */ public void setVisitorCustomId(String visitorCustomId) { - if (visitorCustomId != null) { - if (visitorCustomId.length() != ID_LENGTH) { - throw new IllegalArgumentException(visitorCustomId + " is not " + ID_LENGTH + " characters long."); - } - // Verify visitorID is a 16 character hexadecimal string - else if (!visitorCustomId.matches("[0-9A-Fa-f]+")) { - throw new IllegalArgumentException(visitorCustomId + " is not a hexadecimal string."); - } - } - setParameter(VISITOR_CUSTOM_ID, visitorCustomId); + setVisitorId(visitorCustomId); } /** @@ -1673,7 +1662,7 @@ public void setVisitorId(String visitorId) { throw new IllegalArgumentException(visitorId + " is not " + ID_LENGTH + " characters long."); } // Verify visitorID is a 16 character hexadecimal string - else if (!visitorId.matches("[0-9A-Fa-f]+")) { + else if (!VISITOR_ID_PATTERN.matcher(visitorId).matches()) { throw new IllegalArgumentException(visitorId + " is not a hexadecimal string."); } } @@ -1822,26 +1811,25 @@ public void setVisitorVisitCount(Integer visitorVisitCount) { * @return the query string represented by this object */ + @SuppressWarnings("Duplicates") public String getQueryString() { StringBuilder sb = new StringBuilder(); - for (Entry parameter : parameters.entrySet()) { + parameters.forEach((key, value) -> { if (sb.length() > 0) { - sb.append("&"); + sb.append('&'); } - sb.append(parameter.getKey()); - sb.append("="); - sb.append(parameter.getValue().toString()); - } - for (Entry customTrackingParameter : customTrackingParameters.entrySet()) { - for (Object o : customTrackingParameter.getValue()) { - if (sb.length() > 0) { - sb.append("&"); - } - sb.append(customTrackingParameter.getKey()); - sb.append("="); - sb.append(o.toString()); + sb.append(key); + sb.append('='); + sb.append(value.toString()); + }); + customTrackingParameters.forEach((key, value) -> value.forEach(o -> { + if (sb.length() > 0) { + sb.append('&'); } - } + sb.append(key); + sb.append('='); + sb.append(o.toString()); + })); return sb.toString(); } @@ -1853,37 +1841,34 @@ public String getQueryString() { */ public String getUrlEncodedQueryString() { StringBuilder sb = new StringBuilder(); - for (Entry parameter : parameters.entrySet()) { + parameters.forEach((key, value) -> { if (sb.length() > 0) { - sb.append("&"); + sb.append('&'); } try { StringBuilder sb2 = new StringBuilder(); - sb2.append(parameter.getKey()); - sb2.append("="); - sb2.append(URLEncoder.encode(parameter.getValue().toString(), "UTF-8")); + sb2.append(key); + sb2.append('='); + sb2.append(URLEncoder.encode(value.toString(), "UTF-8")); sb.append(sb2); } catch (UnsupportedEncodingException e) { System.err.println(e.getMessage()); } - } - for (Entry customTrackingParameter : customTrackingParameters.entrySet()) { - for (Object o : customTrackingParameter.getValue()) { - if (sb.length() > 0) { - sb.append("&"); - } - try { - StringBuilder sb2 = new StringBuilder(); - sb2.append(URLEncoder.encode(customTrackingParameter.getKey(), "UTF-8")); - sb2.append("="); - sb2.append(URLEncoder.encode(o.toString(), "UTF-8")); - sb.append(sb2); - } catch (UnsupportedEncodingException e) { - System.err.println(e.getMessage()); - } + }); + customTrackingParameters.forEach((key, value) -> value.forEach(o -> { + if (sb.length() > 0) { + sb.append('&'); } - } - + try { + StringBuilder sb2 = new StringBuilder(); + sb2.append(URLEncoder.encode(key, "UTF-8")); + sb2.append('='); + sb2.append(URLEncoder.encode(o.toString(), "UTF-8")); + sb.append(sb2); + } catch (UnsupportedEncodingException e) { + System.err.println(e.getMessage()); + } + })); return sb.toString(); } @@ -1969,13 +1954,6 @@ private void setBooleanParameter(String key, Boolean value) { } } - /** - * Get a value that is stored in a json object at the specified parameter. - * - * @param parameter the parameter to retrieve the json object from - * @param key the key of the value. Cannot be null - * @return the value - */ private CustomVariable getCustomVariable(String parameter, int index) { CustomVariableList cvl = (CustomVariableList) parameters.get(parameter); if (cvl == null) { @@ -1998,13 +1976,6 @@ private String getCustomVariable(String parameter, String key) { return cvl.get(key); } - /** - * Store a value in a json object at the specified parameter. - * - * @param parameter the parameter to store the json object at - * @param key the key of the value. Cannot be null - * @param value the value. Removes the parameter if null - */ private void setCustomVariable(String parameter, CustomVariable customVariable, Integer index) { CustomVariableList cvl = (CustomVariableList) parameters.get(parameter); if (cvl == null) { From 4e231c66ae576aa19d4061b766ef503a8c995716 Mon Sep 17 00:00:00 2001 From: Marvin Date: Sat, 15 Dec 2018 18:44:16 +0100 Subject: [PATCH 05/10] Fix setting custom tracking parameters and visitor id Signed-off-by: Marvin --- .../org/piwik/java/tracking/PiwikRequest.java | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/piwik/java/tracking/PiwikRequest.java b/src/main/java/org/piwik/java/tracking/PiwikRequest.java index 17695a22..f92f5675 100644 --- a/src/main/java/org/piwik/java/tracking/PiwikRequest.java +++ b/src/main/java/org/piwik/java/tracking/PiwikRequest.java @@ -512,7 +512,7 @@ public List getCustomTrackingParameter(String key) { * @param key the parameter's key. Cannot be null * @param value the parameter's value. Removes the parameter if null */ - public void setCustomTrackingParameter(String key, String value) { + public void setCustomTrackingParameter(String key, Object value) { if (key == null) { throw new NullPointerException("Key cannot be null."); } @@ -533,7 +533,7 @@ public void setCustomTrackingParameter(String key, String value) { * @param key the parameter's key. Cannot be null * @param value the parameter's value. Cannot be null */ - public void addCustomTrackingParameter(String key, String value) { + public void addCustomTrackingParameter(String key, Object value) { if (key == null) { throw new NullPointerException("Key cannot be null."); } @@ -1614,8 +1614,18 @@ public String getVisitorCustomId() { * * @param visitorCustomId the visitor's custom id to set. A null value will remove this parameter */ + @SuppressWarnings("Duplicates") public void setVisitorCustomId(String visitorCustomId) { - setVisitorId(visitorCustomId); + if (visitorCustomId != null) { + if (visitorCustomId.length() != ID_LENGTH) { + throw new IllegalArgumentException(visitorCustomId + " is not " + ID_LENGTH + " characters long."); + } + // Verify visitorID is a 16 character hexadecimal string + else if (!VISITOR_ID_PATTERN.matcher(visitorCustomId).matches()) { + throw new IllegalArgumentException(visitorCustomId + " is not a hexadecimal string."); + } + } + setParameter(VISITOR_CUSTOM_ID, visitorCustomId); } /** @@ -1656,6 +1666,7 @@ public String getVisitorId() { * * @param visitorId the visitor id to set. A null value will remove this parameter */ + @SuppressWarnings("Duplicates") public void setVisitorId(String visitorId) { if (visitorId != null) { if (visitorId.length() != ID_LENGTH) { From 33c5fe4689c9deb3cdb5523683309d5ea262e339 Mon Sep 17 00:00:00 2001 From: Marvin Date: Sat, 15 Dec 2018 19:49:34 +0100 Subject: [PATCH 06/10] Make release Signed-off-by: Marvin --- pom.xml | 28 +++++++++------------------- 1 file changed, 9 insertions(+), 19 deletions(-) diff --git a/pom.xml b/pom.xml index a1c6c3c7..73a565f2 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.piwik.java.tracking piwik-java-tracker - 1.3-SNAPSHOT + 1.3 jar Piwik Java Tracker @@ -38,15 +38,16 @@ - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - + llamacloud-releases + Phyrone Repo-releases + https://maven.phyrone.de/artifactory/llamacloud-release + + llamacloud-snapshots + Phyrone Repo-snapshots + https://maven.phyrone.de/artifactory/llamacloud-snapshot + @@ -133,17 +134,6 @@ - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.8 - true - - ossrh - https://oss.sonatype.org/ - false - - From 3fab31c2c7003d497129e2d8835d4860ed2fff66 Mon Sep 17 00:00:00 2001 From: Marvin Date: Sat, 15 Dec 2018 19:51:02 +0100 Subject: [PATCH 07/10] Add Jenkinsfile for automated builds Signed-off-by: Marvin --- Jenkinsfile | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Jenkinsfile diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 00000000..3aae794d --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,38 @@ +pipeline { + agent any + tools { + maven 'Maven3' + jdk 'Java11' + } + options { + buildDiscarder logRotator(numToKeepStr: '10') + } + stages { + stage('Clean') { + steps { + sh 'mvn clean' + } + } + stage('Compile') { + steps { + sh 'mvn compile' + } + } + stage('Test') { + steps { + sh 'mvn test' + } + } + stage('Package') { + steps { + sh 'mvn package' + } + } + } + post { + always { + archiveArtifacts artifacts: 'target/*.jar', excludes: 'target/original*', fingerprint: true + junit testResults: 'target/surefire-reports/*.xml', allowEmptyResults: true + } + } +} From 41ba528296b371ebc3fa109016d1ae34365bd1b7 Mon Sep 17 00:00:00 2001 From: Marvin Date: Sat, 15 Dec 2018 20:18:06 +0100 Subject: [PATCH 08/10] Change group id to fix the clash with maven central Signed-off-by: Marvin --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 73a565f2..2cbab742 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - org.piwik.java.tracking + io.llamacloud.piwik.tracking piwik-java-tracker 1.3 jar From 2e0abf545996496a7f534af238b325122befbda6 Mon Sep 17 00:00:00 2001 From: Marvin Date: Sun, 16 Dec 2018 13:59:10 +0100 Subject: [PATCH 09/10] Add clone, hashCode and equals methods Signed-off-by: Marvin --- .../org/piwik/java/tracking/PiwikRequest.java | 25 ++++++++++++++++++- .../piwik/java/tracking/PiwikRequestTest.java | 6 +++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/piwik/java/tracking/PiwikRequest.java b/src/main/java/org/piwik/java/tracking/PiwikRequest.java index f92f5675..4898808c 100644 --- a/src/main/java/org/piwik/java/tracking/PiwikRequest.java +++ b/src/main/java/org/piwik/java/tracking/PiwikRequest.java @@ -23,7 +23,7 @@ * @author brettcsorba */ @SuppressWarnings({"WeakerAccess", "SameParameterValue", "CharsetObjectCanBeUsed"}) -public class PiwikRequest { +public class PiwikRequest implements Cloneable { public static final int ID_LENGTH = 16; public static final int AUTH_TOKEN_LENGTH = 32; @@ -1883,6 +1883,29 @@ public String getUrlEncodedQueryString() { return sb.toString(); } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof PiwikRequest)) return false; + PiwikRequest that = (PiwikRequest) o; + return Objects.equals(parameters, that.parameters) && + Objects.equals(customTrackingParameters, that.customTrackingParameters); + } + + @Override + public int hashCode() { + int result = parameters != null ? parameters.hashCode() : 0; + result = 31 * result + (customTrackingParameters != null ? customTrackingParameters.hashCode() : 0); + return result; + } + + public PiwikRequest clone() { + PiwikRequest clone = new PiwikRequest(getSiteId(), getActionUrl()); + this.parameters.forEach(clone.parameters::put); + this.customTrackingParameters.forEach(clone.customTrackingParameters::put); + return clone; + } + /** * Get a stored parameter. * diff --git a/src/test/java/org/piwik/java/tracking/PiwikRequestTest.java b/src/test/java/org/piwik/java/tracking/PiwikRequestTest.java index 249ae0d0..77136e06 100644 --- a/src/test/java/org/piwik/java/tracking/PiwikRequestTest.java +++ b/src/test/java/org/piwik/java/tracking/PiwikRequestTest.java @@ -1581,4 +1581,10 @@ public void testGetRandomHexString() { assertEquals(10, s.length()); Long.parseLong(s, 16); } + + @Test + public void testClone() { + PiwikRequest clone = request.clone(); + assertEquals(request, clone); + } } From 49b58b830a485af4017d225de692d202308e2d7d Mon Sep 17 00:00:00 2001 From: Marvin Date: Sun, 16 Dec 2018 13:59:27 +0100 Subject: [PATCH 10/10] Bump version Signed-off-by: Marvin --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 2cbab742..ac1231da 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ io.llamacloud.piwik.tracking piwik-java-tracker - 1.3 + 1.4 jar Piwik Java Tracker