Skip to content

Commit

Permalink
Add support for anonymizing user ip address with config #57
Browse files Browse the repository at this point in the history
  • Loading branch information
brsanthu committed May 20, 2019
1 parent 0e5ade8 commit e73a989
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ public class GoogleAnalyticsConfig {
private RequestParameterDiscoverer requestParameterDiscoverer = new DefaultRequestParameterDiscoverer();
private GoogleAnalyticsExceptionHandler exceptionHandler;
private boolean autoQueueTimeEnabled = true;
private boolean anonymizeUserIp = false;

public RequestParameterDiscoverer getRequestParameterDiscoverer() {
return requestParameterDiscoverer;
Expand Down Expand Up @@ -413,6 +414,8 @@ public GoogleAnalyticsExceptionHandler getExceptionHandler() {
/**
* Set an exception handler which will implement the behavior in case of any exceptions. If not set, default
* behavior is to log a warning message.
*
* @since 2.1
*/
public GoogleAnalyticsConfig setExceptionHandler(GoogleAnalyticsExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
Expand All @@ -434,4 +437,23 @@ public GoogleAnalyticsConfig setAutoQueueTimeEnabled(boolean autoQueueTimeEnable
return this;
}

public boolean isAnonymizeUserIp() {
return anonymizeUserIp;
}

/**
* If true, and if <code>userIp</code> GA parameter is set, then that ip will be anonymized using same logic that is
* used at GA end. Defaults to <code>false</code>.
* <p>
* See for more info:
* <ul>
* <li>https://github.com/brsanthu/google-analytics-java/issues/57
* <li>https://support.google.com/analytics/answer/2763052?hl=en
* </ul>
*/
public GoogleAnalyticsConfig setAnonymizeUserIp(boolean anonymizeUserIp) {
this.anonymizeUserIp = anonymizeUserIp;
return this;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import static com.brsanthu.googleanalytics.internal.GaUtils.isEmpty;
import static com.brsanthu.googleanalytics.request.GoogleAnalyticsParameter.QUEUE_TIME;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
Expand Down Expand Up @@ -241,9 +243,9 @@ private HttpRequest createHttpRequest(GoogleAnalyticsRequest<?> gaReq) {
return httpReq;
}

protected void processParameters(GoogleAnalyticsRequest<?> request, HttpRequest req) {
protected void processParameters(GoogleAnalyticsRequest<?> gaReq, HttpRequest httpReq) {

Map<GoogleAnalyticsParameter, String> requestParms = request.getParameters();
Map<GoogleAnalyticsParameter, String> requestParms = gaReq.getParameters();
Map<GoogleAnalyticsParameter, String> defaultParms = defaultRequest.getParameters();

for (GoogleAnalyticsParameter parm : defaultParms.keySet()) {
Expand All @@ -256,8 +258,29 @@ protected void processParameters(GoogleAnalyticsRequest<?> request, HttpRequest
}
}

anonymizeUserIp(gaReq, httpReq);

for (GoogleAnalyticsParameter key : requestParms.keySet()) {
req.addBodyParam(key.getParameterName(), requestParms.get(key));
httpReq.addBodyParam(key.getParameterName(), requestParms.get(key));
}
}

private void anonymizeUserIp(GoogleAnalyticsRequest<?> gaReq, HttpRequest httpReq) {
if (config.isAnonymizeUserIp() && gaReq.userIp() != null) {
try {
InetAddress ip = InetAddress.getByName(gaReq.userIp());
byte[] address = ip.getAddress();
int anonymizedBytes = ip instanceof Inet6Address ? 10 : 1;

for (int i = 0; i < anonymizedBytes; ++i) {
address[address.length - i - 1] = 0;
}

String anonymizedIp = InetAddress.getByAddress(address).getHostAddress();
gaReq.userIp(anonymizedIp);
} catch (Exception e) {
logger.warn("Error anonymizing user ip", e);
}
}
}

Expand Down
28 changes: 18 additions & 10 deletions src/test/java/com/brsanthu/googleanalytics/GoogleAnalyticsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,13 @@
public class GoogleAnalyticsTest {

private static GoogleAnalytics ga = null;
private static HttpClient client;

@BeforeAll
public static void setup() {
ga = GoogleAnalytics.builder().withTrackingId(TEST_TRACKING_ID).withAppName("Junit Test").withAppVersion("1.0.0").build();
client = mock(HttpClient.class);
when(client.post(ArgumentMatchers.any())).thenReturn(new HttpResponse().setStatusCode(200));
}

@Test
Expand Down Expand Up @@ -163,10 +166,6 @@ void testExceptionHandler() throws Exception {

@Test
void testAutoQueueTime() throws Exception {

HttpClient client = mock(HttpClient.class);
when(client.post(ArgumentMatchers.any())).thenReturn(new HttpResponse().setStatusCode(200));

// By default queue time is added based on when hit was created and posted. In this test case, it should be
// close to 0
GoogleAnalytics gaAutoTimeEnabled = GoogleAnalytics.builder().withHttpClient(client).withConfig(new GoogleAnalyticsConfig()).build();
Expand Down Expand Up @@ -198,9 +197,6 @@ void testAutoQueueTime() throws Exception {

@Test
void testAutoQueueTimeBatch() throws Exception {
HttpClient client = mock(HttpClient.class);
when(client.post(ArgumentMatchers.any())).thenReturn(new HttpResponse().setStatusCode(200));

GoogleAnalytics gaAutoTimeEnabled = GoogleAnalytics.builder().withHttpClient(client).withConfig(
new GoogleAnalyticsConfig().setBatchingEnabled(true).setBatchSize(2)).build();

Expand Down Expand Up @@ -230,9 +226,6 @@ void testDeepClone() throws Exception {

@Test
void testStats() throws Exception {
HttpClient client = mock(HttpClient.class);
when(client.post(ArgumentMatchers.any())).thenReturn(new HttpResponse().setStatusCode(200));

GoogleAnalytics ga = GoogleAnalytics.builder().withHttpClient(client).withConfig(
new GoogleAnalyticsConfig().setGatherStats(true).setBatchingEnabled(true).setBatchSize(2)).build();

Expand Down Expand Up @@ -268,4 +261,19 @@ void testAnyHit() throws Exception {
anyhit2.adwordsId("adsid789");
assertThat(sv.adwordsId()).isNotEqualTo(anyhit2.adwordsId());
}

@Test
void testAnonymizeUserIp() throws Exception {
String userIp = "176.134.201.004";

GoogleAnalytics ga = GoogleAnalytics.builder().withHttpClient(client).withConfig(new GoogleAnalyticsConfig()).build();
GoogleAnalyticsResponse resp = ga.screenView().userIp(userIp).send();
assertThat(resp.getRequestParams().get(GoogleAnalyticsParameter.USER_IP.getParameterName())).isEqualTo(userIp);

GoogleAnalytics ga2 = GoogleAnalytics.builder().withHttpClient(client).withConfig(
new GoogleAnalyticsConfig().setAnonymizeUserIp(true)).build();
GoogleAnalyticsResponse resp2 = ga2.screenView().userIp(userIp).send();
assertThat(resp2.getRequestParams().get(GoogleAnalyticsParameter.USER_IP.getParameterName())).isEqualTo("176.134.201.0");

}
}

0 comments on commit e73a989

Please sign in to comment.