diff --git a/README.md b/README.md index ff2ac35a..86fd2c02 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,16 @@ # Java Analytics for Snowplow -[ ![Build Status] [travis-image] ] [travis] [ ![Release] [release-image] ] [releases] [ ![License] [license-image] ] [license] +[![Build Status][travis-image]][travis] [![Release][release-image]][releases] [![License][license-image]][license] ## Overview -Add analytics to your Java software with the **[Snowplow] [snowplow]** event tracker for **[Java] [java]**. See also: **[Snowplow Android Tracker] [snowplow-android-tracker]**. +Add analytics to your Java software with the **[Snowplow][snowplow]** event tracker for **[Java][java]**. See also: **[Snowplow Android Tracker][snowplow-android-tracker]**. With this tracker you can collect event data from your Java-based desktop and server apps, servlets and games. Supports JDK7+. ## Quickstart -Assuming git, **[Vagrant] [vagrant-install]** and **[VirtualBox] [virtualbox-install]** installed: +Assuming git, **[Vagrant][vagrant-install]** and **[VirtualBox][virtualbox-install]** installed: ```bash host$ git clone https://github.com/snowplow/snowplow-java-tracker.git @@ -25,14 +25,14 @@ guest$ ./gradlew test | Technical Docs | Setup Guide | Roadmap | Contributing | |---------------------------------|---------------------------|-------------------------|-----------------------------------| -| ![i1] [techdocs-image] | ![i2] [setup-image] | ![i3] [roadmap-image] | ![i4] [contributing-image] | -| **[Technical Docs] [techdocs]** | **[Setup Guide] [setup]** | **[Roadmap] [roadmap]** | **[Contributing] [contributing]** | +| ![i1][techdocs-image] | ![i2][setup-image] | ![i3][roadmap-image] | ![i4][contributing-image] | +| **[Technical Docs][techdocs]** | **[Setup Guide][setup]** | **[Roadmap][roadmap]** | **[Contributing][contributing]** | ## Copyright and license The Snowplow Java Tracker is copyright 2014-2015 Snowplow Analytics Ltd. -Licensed under the **[Apache License, Version 2.0] [license]** (the "License"); +Licensed under the **[Apache License, Version 2.0][license]** (the "License"); you may not use this software except in compliance with the License. Unless required by applicable law or agreed to in writing, software diff --git a/build.gradle b/build.gradle index a1c030da..1c867e49 100644 --- a/build.gradle +++ b/build.gradle @@ -69,7 +69,8 @@ dependencies { optional 'com.squareup.okhttp:okhttp:2.2.0' // SLF4J logging API - compile 'org.slf4j:slf4j-simple:1.7.7' + compile 'org.slf4j:slf4j-api:1.7.7' + testRuntime 'org.slf4j:slf4j-simple:1.7.7' // Jackson JSON processor compile 'com.fasterxml.jackson.core:jackson-databind:2.4.1.1' diff --git a/examples/simple-console/.gitignore b/examples/simple-console/.gitignore new file mode 100644 index 00000000..3e2572c2 --- /dev/null +++ b/examples/simple-console/.gitignore @@ -0,0 +1,4 @@ +.idea/ +build/ +out/ + diff --git a/examples/simple-console/README.md b/examples/simple-console/README.md new file mode 100644 index 00000000..7dddded9 --- /dev/null +++ b/examples/simple-console/README.md @@ -0,0 +1,10 @@ +# Simple console sample + +This is a small Java console project that sends PageView events to a given collector. + +## Run + +``` +./gradlew jar + java -jar ./build/libs/simple-console-all-0.0.1.jar "http://" +``` diff --git a/examples/simple-console/build.gradle b/examples/simple-console/build.gradle new file mode 100644 index 00000000..3682679f --- /dev/null +++ b/examples/simple-console/build.gradle @@ -0,0 +1,29 @@ +apply plugin: 'java' +group = 'com.snowplowanalytics' +version = '0.0.1' + +repositories { + mavenCentral() + maven { + url "http://maven.snplow.com/releases" + } +} + +dependencies { + compile 'com.google.code.gson:gson:2.8+' + compile 'com.snowplowanalytics:snowplow-java-tracker:0.8.0' + testCompile 'junit:junit:4.12' +} + +task fatJar(type: Jar) { + manifest { + attributes 'Implementation-Title': 'simple-console', + 'Implementation-Version': version, + 'Main-Class': 'com.snowplowanalytics.Main' + } + baseName = project.name + '-all' + from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } } + with jar +} + +tasks.jar.dependsOn(fatJar) diff --git a/examples/simple-console/gradle/wrapper/gradle-wrapper.properties b/examples/simple-console/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..958d54cd --- /dev/null +++ b/examples/simple-console/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Dec 05 10:27:05 GMT 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-3.5-rc-2-bin.zip diff --git a/examples/simple-console/gradlew b/examples/simple-console/gradlew new file mode 100755 index 00000000..4453ccea --- /dev/null +++ b/examples/simple-console/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save ( ) { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/examples/simple-console/gradlew.bat b/examples/simple-console/gradlew.bat new file mode 100644 index 00000000..e95643d6 --- /dev/null +++ b/examples/simple-console/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/examples/simple-console/src/main/java/com/snowplowanalytics/Main.java b/examples/simple-console/src/main/java/com/snowplowanalytics/Main.java new file mode 100644 index 00000000..2ab1ab48 --- /dev/null +++ b/examples/simple-console/src/main/java/com/snowplowanalytics/Main.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2017 Snowplow Analytics Ltd. All rights reserved. + * + * This program is licensed to you under the Apache License Version 2.0, + * and you may not use this file except in compliance with the Apache License Version 2.0. + * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the Apache License Version 2.0 is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. + */ + +package com.snowplowanalytics; + +import com.snowplowanalytics.snowplow.tracker.DevicePlatform; +import com.snowplowanalytics.snowplow.tracker.Tracker; +import com.snowplowanalytics.snowplow.tracker.emitter.BatchEmitter; +import com.snowplowanalytics.snowplow.tracker.emitter.Emitter; +import com.snowplowanalytics.snowplow.tracker.emitter.RequestCallback; +import com.snowplowanalytics.snowplow.tracker.events.PageView; +import com.snowplowanalytics.snowplow.tracker.http.HttpClientAdapter; +import com.snowplowanalytics.snowplow.tracker.http.OkHttpClientAdapter; +import com.snowplowanalytics.snowplow.tracker.payload.TrackerPayload; +import com.squareup.okhttp.OkHttpClient; + +import java.util.List; +import java.util.concurrent.TimeUnit; + +public class Main { + + private static final int PAGEVIEW_COUNT = 20; + + public static String getUrlFromArgs(String[] args) { + if (args == null || args.length < 1) { + throw new IllegalArgumentException("Collector URL is required"); + } + return args[0]; + } + + public static HttpClientAdapter getClient(String url) { + // use okhttp to send events + OkHttpClient client = new OkHttpClient(); + + client.setConnectTimeout(5, TimeUnit.SECONDS); + client.setReadTimeout(5, TimeUnit.SECONDS); + client.setWriteTimeout(5, TimeUnit.SECONDS); + + return OkHttpClientAdapter.builder() + .url(url) + .httpClient(client) + .build(); + } + + public static void main(String[] args) { + String collectorEndpoint = getUrlFromArgs(args); + + System.out.println("Sending " + PAGEVIEW_COUNT + " events to " + collectorEndpoint); + + // get the client adapter + // this is used by the Java tracker to transmit events to the collector + HttpClientAdapter okHttpClientAdapter = getClient(collectorEndpoint); + + // the application id to attach to events + String appId = "java-tracker-sample-console-app"; + // the namespace to attach to events + String namespace = "demo"; + + // build an emitter, this is used by the tracker to batch and schedule transmission of events + Emitter emitter = BatchEmitter.builder() + .httpClientAdapter(okHttpClientAdapter) + .requestCallback(new RequestCallback() { + // let us know on successes (may be called multiple times) + @Override + public void onSuccess(int successCount) { + System.out.println("Successfully sent " + successCount + " events"); + } + + // let us know if something has gone wrong (may be called multiple times) + @Override + public void onFailure(int successCount, List failedEvents) { + System.err.println("Successfully sent " + successCount + " events; failed to send " + failedEvents.size() + " events"); + } + }) + .bufferSize(1) // send an event every time one is given (no batching). In production this number should be higher, depending on the size/event volume + .build(); + + // now we have the emitter, we need a tracker to turn our events into something a Snowplow collector can understand + Tracker tracker = new Tracker.TrackerBuilder(emitter, namespace, appId) + .base64(true) + .platform(DevicePlatform.ServerSideApp) + .build(); + + // This is a sample page view event, many other event types (such as self-describing events) are available + PageView pageViewEvent = PageView.builder() + .pageTitle("Hello world") + .pageUrl("http://helloworld.com") + .build(); + + for (int i = 0; i < PAGEVIEW_COUNT; i++) { + tracker.track(pageViewEvent); // the .track method schedules the event for delivery to Snowplow + } + + } + +} diff --git a/examples/simple-console/src/test/java/com/snowplowanalytics/MainTest.java b/examples/simple-console/src/test/java/com/snowplowanalytics/MainTest.java new file mode 100644 index 00000000..2a0d8730 --- /dev/null +++ b/examples/simple-console/src/test/java/com/snowplowanalytics/MainTest.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2017 Snowplow Analytics Ltd. All rights reserved. + * + * This program is licensed to you under the Apache License Version 2.0, + * and you may not use this file except in compliance with the Apache License Version 2.0. + * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the Apache License Version 2.0 is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. + */ + +package com.snowplowanalytics; + +import com.snowplowanalytics.snowplow.tracker.http.HttpClientAdapter; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class MainTest { + + @Test + public void testGetUrl() { + String[] sample = {"com.acme", "world"}; + assertEquals("com.acme", Main.getUrlFromArgs(sample)); + } + + @Test(expected = IllegalArgumentException.class) + public void testGetUrlNull() { + Main.getUrlFromArgs(null); + } + + @Test(expected = IllegalArgumentException.class) + public void testGetUrlEmpty() { + Main.getUrlFromArgs(new String[]{}); + } + + + @Test + public void testGetClientAdapter() { + HttpClientAdapter givenClient = Main.getClient("https://acme.com"); + assertNotNull(givenClient); + assertEquals("https://acme.com", givenClient.getUrl()); + } + +} \ No newline at end of file diff --git a/src/main/java/com/snowplowanalytics/snowplow/tracker/Utils.java b/src/main/java/com/snowplowanalytics/snowplow/tracker/Utils.java index b01d8583..49a76286 100644 --- a/src/main/java/com/snowplowanalytics/snowplow/tracker/Utils.java +++ b/src/main/java/com/snowplowanalytics/snowplow/tracker/Utils.java @@ -13,6 +13,7 @@ package com.snowplowanalytics.snowplow.tracker; // Java +import java.nio.charset.Charset; import java.util.*; import java.net.URL; import java.net.URLEncoder; @@ -108,8 +109,8 @@ public static String getTimezone() { * @param string the string too encode * @return a Base64 encoded string */ - public static String base64Encode(String string) { - return encodeBase64String(string.getBytes()); + public static String base64Encode(String string, Charset charset) { + return encodeBase64String(string.getBytes(charset)); } /** diff --git a/src/main/java/com/snowplowanalytics/snowplow/tracker/emitter/BatchEmitter.java b/src/main/java/com/snowplowanalytics/snowplow/tracker/emitter/BatchEmitter.java index 3a069be6..be738b59 100644 --- a/src/main/java/com/snowplowanalytics/snowplow/tracker/emitter/BatchEmitter.java +++ b/src/main/java/com/snowplowanalytics/snowplow/tracker/emitter/BatchEmitter.java @@ -17,6 +17,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.concurrent.TimeUnit; // Google import com.google.common.base.Preconditions; @@ -38,6 +39,8 @@ public class BatchEmitter extends AbstractEmitter implements Closeable { private static final Logger LOGGER = LoggerFactory.getLogger(BatchEmitter.class); + private long closeTimeout = 5; + public static abstract class Builder> extends AbstractEmitter.Builder { private int bufferSize = 50; // Optional @@ -163,5 +166,18 @@ private SelfDescribingJson getFinalPost(List buffer) { @Override public void close() { flushBuffer(); + if (executor != null) { + executor.shutdown(); + try { + if (!executor.awaitTermination(closeTimeout, TimeUnit.SECONDS)) { + executor.shutdownNow(); + if (!executor.awaitTermination(closeTimeout, TimeUnit.SECONDS)) + LOGGER.warn("Executor did not terminate"); + } + } catch (InterruptedException ie) { + executor.shutdownNow(); + Thread.currentThread().interrupt(); + } + } } } diff --git a/src/main/java/com/snowplowanalytics/snowplow/tracker/http/ApacheHttpClientAdapter.java b/src/main/java/com/snowplowanalytics/snowplow/tracker/http/ApacheHttpClientAdapter.java index 3fa1c2c8..2cd7b279 100644 --- a/src/main/java/com/snowplowanalytics/snowplow/tracker/http/ApacheHttpClientAdapter.java +++ b/src/main/java/com/snowplowanalytics/snowplow/tracker/http/ApacheHttpClientAdapter.java @@ -23,6 +23,7 @@ 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.CloseableHttpClient; @@ -121,7 +122,7 @@ public int doPost(String url, String payload) { try { HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Content-Type", Constants.POST_CONTENT_TYPE); - StringEntity params = new StringEntity(payload); + StringEntity params = new StringEntity(payload, ContentType.APPLICATION_JSON); httpPost.setEntity(params); HttpResponse httpResponse = httpClient.execute(httpPost); httpPost.releaseConnection(); diff --git a/src/main/java/com/snowplowanalytics/snowplow/tracker/http/OkHttpClientAdapter.java b/src/main/java/com/snowplowanalytics/snowplow/tracker/http/OkHttpClientAdapter.java index 91b08a7a..11a157eb 100644 --- a/src/main/java/com/snowplowanalytics/snowplow/tracker/http/OkHttpClientAdapter.java +++ b/src/main/java/com/snowplowanalytics/snowplow/tracker/http/OkHttpClientAdapter.java @@ -13,8 +13,7 @@ package com.snowplowanalytics.snowplow.tracker.http; // Java -import java.util.Iterator; -import java.util.Map; +import java.io.IOException; // Google import com.google.common.base.Preconditions; @@ -27,6 +26,7 @@ import com.squareup.okhttp.RequestBody; // Slf4j +import org.apache.http.HttpHeaders; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -96,41 +96,70 @@ public Object getHttpClient() { * GET request to the configured endpoint. * * @param url the URL send - * @return the HttpResponse for the Request + * @return the HttpResponse code for the Request or -1 if exception is caught */ public int doGet(String url) { + + Response response = null; + int returnValue = -1; + Request request = new Request.Builder().url(url).build(); try { - Response response = httpClient.newCall(request).execute(); - return response.code(); + response = httpClient.newCall(request).execute(); + returnValue = response.code(); } catch (Exception e) { LOGGER.error("OkHttpClient GET Request failed: {}", e.getMessage()); - return -1; + } finally { + closeResponseBody(response); } + + return returnValue; } + /** * Attempts to send a group of payloads with a * POST request to the configured endpoint. * * @param url the URL to send to * @param payload the payload to send - * @return the HttpResponse for the Request + * @return the HttpResponse code for the Request or -1 if exception is caught */ public int doPost(String url, String payload) { + Response response = null; + int returnValue = -1; + try { RequestBody body = RequestBody.create(JSON, payload); Request request = new Request.Builder() .url(url) - .addHeader("Content-Type", Constants.POST_CONTENT_TYPE) + .addHeader(HttpHeaders.CONTENT_TYPE, Constants.POST_CONTENT_TYPE) .post(body) .build(); - Response response = httpClient.newCall(request).execute(); - return response.code(); + response = httpClient.newCall(request).execute(); + returnValue = response.code(); } catch (Exception e) { LOGGER.error("OkHttpClient POST Request failed: {}", e.getMessage()); - return -1; + } finally { + closeResponseBody(response); } + + return returnValue; + } + + + /** + * Closes response body as required by OkHttpClient documentation + * + * @param response OkHttpClient response + */ + private void closeResponseBody(Response response) { + if (response != null && response.body() != null) + try { + response.body().close(); + } catch (IOException e) { + LOGGER.error("OkHttpClient response body closing failed: {}", e.getMessage()); + } } -} +} \ No newline at end of file diff --git a/src/main/java/com/snowplowanalytics/snowplow/tracker/payload/TrackerPayload.java b/src/main/java/com/snowplowanalytics/snowplow/tracker/payload/TrackerPayload.java index 0a48f442..b581be42 100644 --- a/src/main/java/com/snowplowanalytics/snowplow/tracker/payload/TrackerPayload.java +++ b/src/main/java/com/snowplowanalytics/snowplow/tracker/payload/TrackerPayload.java @@ -13,6 +13,7 @@ package com.snowplowanalytics.snowplow.tracker.payload; // Java +import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import java.util.Map; @@ -88,7 +89,7 @@ public void addMap(Map map, boolean base64Encoded, String typeEncoded, String ty LOGGER.info("Adding new map: {}", map); if (base64Encoded) { - add(typeEncoded, Utils.base64Encode(mapString)); + add(typeEncoded, Utils.base64Encode(mapString, StandardCharsets.UTF_8)); } else { add(typeNotEncoded, mapString); } diff --git a/src/test/java/com/snowplowanalytics/snowplow/tracker/UtilsTest.java b/src/test/java/com/snowplowanalytics/snowplow/tracker/UtilsTest.java index c5bd629a..f1074e3f 100644 --- a/src/test/java/com/snowplowanalytics/snowplow/tracker/UtilsTest.java +++ b/src/test/java/com/snowplowanalytics/snowplow/tracker/UtilsTest.java @@ -19,6 +19,7 @@ import static org.junit.Assert.assertTrue; // Java +import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import java.util.Map; @@ -85,9 +86,10 @@ public void testGetTimezone() { @Test public void testBase64Encode() { - String expected = "aGVsbG93b3JsZHRlc3RiNjQ="; - String b64encoded = Utils.base64Encode("helloworldtestb64"); + String expected = "aGVsbG93b3JsZHRlc3RiNjR3aXRodXRmOGNoYXJzw7TDqcOgw6c="; + String b64encoded = Utils.base64Encode("helloworldtestb64withutf8charsôéàç", StandardCharsets.UTF_8); assertEquals(expected, b64encoded); + } @Test