diff --git a/iterable-extension/src/main/java/com/mparticle/ext/iterable/IterableExtension.java b/iterable-extension/src/main/java/com/mparticle/ext/iterable/IterableExtension.java index 32b90d2..28e00ca 100644 --- a/iterable-extension/src/main/java/com/mparticle/ext/iterable/IterableExtension.java +++ b/iterable-extension/src/main/java/com/mparticle/ext/iterable/IterableExtension.java @@ -10,7 +10,7 @@ import com.mparticle.sdk.model.audienceprocessing.UserProfile; import com.mparticle.sdk.model.eventprocessing.*; import com.mparticle.sdk.model.registration.*; -import retrofit.Response; +import retrofit2.Response; import java.io.IOException; import java.util.*; @@ -29,9 +29,7 @@ public class IterableExtension extends MessageProcessor { @Override public EventProcessingResponse processEventProcessingRequest(EventProcessingRequest request) throws IOException { if (iterableService == null) { - Account account = request.getAccount(); - String apiKey = account.getStringSetting(SETTING_API_KEY, true, null); - iterableService = IterableService.newInstance(apiKey); + iterableService = IterableService.newInstance(); } Collections.sort( request.getEvents(), @@ -42,6 +40,21 @@ public EventProcessingResponse processEventProcessingRequest(EventProcessingRequ return super.processEventProcessingRequest(request); } + private static String getApiKey(Event event) { + Account account = event.getContext().getAccount(); + return account.getStringSetting(SETTING_API_KEY, true, null); + } + + private static String getApiKey(EventProcessingRequest event) { + Account account = event.getAccount(); + return account.getStringSetting(SETTING_API_KEY, true, null); + } + + private static String getApiKey(AudienceMembershipChangeRequest event) { + Account account = event.getAccount(); + return account.getStringSetting(SETTING_API_KEY, true, null); + } + /** * Verify that there's an email present, create a placeholder if not. * @@ -92,17 +105,16 @@ public void processPushSubscriptionEvent(PushSubscriptionEvent event) throws IOE .filter(t -> t.getType().equals(UserIdentity.Type.EMAIL)) .findFirst() .get(); - request.email = email.getValue(); } catch (NoSuchElementException e) { throw new IOException("Unable to construct Iterable RegisterDeviceTokenRequest - no user email."); } - Response response = iterableService.registerToken(request).execute(); - if (response.isSuccess() && !response.body().isSuccess()) { + Response response = iterableService.registerToken(getApiKey(event), request).execute(); + if (response.isSuccessful() && !response.body().isSuccess()) { throw new IOException(response.body().toString()); - } else if (!response.isSuccess()) { - throw new IOException("Error sending push subscription to Iterable: HTTP " + response.code()); + } else if (!response.isSuccessful()) { + throw new IOException("Error sending push subscription to Iterable: " + response.body().toString()); } } @@ -137,8 +149,8 @@ void updateUser(EventProcessingRequest request) throws IOException { updateEmailRequest.currentEmail = placeholderEmail; //this is safe due to the filters above updateEmailRequest.newEmail = changeEvent.getAdded().get(0).getValue(); - Response response = iterableService.updateEmail(updateEmailRequest).execute(); - if (response.isSuccess()) { + Response response = iterableService.updateEmail(getApiKey(request), updateEmailRequest).execute(); + if (response.isSuccessful()) { IterableApiResponse apiResponse = response.body(); if (apiResponse != null && !apiResponse.isSuccess()) { throw new IOException("Error while calling updateEmail() on iterable: HTTP " + apiResponse.code); @@ -152,8 +164,8 @@ void updateUser(EventProcessingRequest request) throws IOException { //these are safe due to the filters above updateEmailRequest.currentEmail = changeEvent.getRemoved().get(0).getValue(); updateEmailRequest.newEmail = changeEvent.getAdded().get(0).getValue(); - Response response = iterableService.updateEmail(updateEmailRequest).execute(); - if (response.isSuccess()) { + Response response = iterableService.updateEmail(getApiKey(request), updateEmailRequest).execute(); + if (response.isSuccessful()) { IterableApiResponse apiResponse = response.body(); if (apiResponse != null && !apiResponse.isSuccess()) { throw new IOException("Error while calling updateEmail() on iterable: HTTP " + apiResponse.code); @@ -174,8 +186,8 @@ void updateUser(EventProcessingRequest request) throws IOException { } if (!isEmpty(userUpdateRequest.email) || !isEmpty(userUpdateRequest.userId)) { userUpdateRequest.dataFields = context.getUserAttributes(); - Response response = iterableService.userUpdate(userUpdateRequest).execute(); - if (response.isSuccess()) { + Response response = iterableService.userUpdate(getApiKey(request), userUpdateRequest).execute(); + if (response.isSuccessful()) { IterableApiResponse apiResponse = response.body(); if (apiResponse != null && !apiResponse.isSuccess()) { throw new IOException("Error while calling updateUser() on iterable: HTTP " + apiResponse.code); @@ -214,10 +226,10 @@ public void processProductActionEvent(ProductActionEvent event) throws IOExcepti .collect(Collectors.toList()); } - Response response = iterableService.trackPurchase(purchaseRequest).execute(); - if (response.isSuccess() && !response.body().isSuccess()) { + Response response = iterableService.trackPurchase(getApiKey(event), purchaseRequest).execute(); + if (response.isSuccessful() && !response.body().isSuccess()) { throw new IOException(response.body().toString()); - } else if (!response.isSuccess()) { + } else if (!response.isSuccessful()) { throw new IOException("Error sending custom event to Iterable: HTTP " + response.code()); } } @@ -426,10 +438,10 @@ public void processCustomEvent(CustomEvent event) throws IOException { //request.campaignId = event.getCustomFlags().... //request.templateId = event.getCustomFlags().... - Response response = iterableService.track(request).execute(); - if (response.isSuccess() && !response.body().isSuccess()) { + Response response = iterableService.track(getApiKey(event), request).execute(); + if (response.isSuccessful() && !response.body().isSuccess()) { throw new IOException(response.body().toString()); - } else if (!response.isSuccess()) { + } else if (!response.isSuccessful()) { throw new IOException("Error sending custom event to Iterable: HTTP " + response.code()); } } @@ -503,25 +515,17 @@ public void processPushMessageReceiptEvent(PushMessageReceiptEvent event) throws request.messageId = mapper.writeValueAsString(((Map) payload.get("itbl")).get("messageId")); } request.createdAt = (int) (event.getTimestamp() / 1000.0); - Response response = iterableService.trackPushOpen(request).execute(); - if (response.isSuccess() && !response.body().isSuccess()) { + Response response = iterableService.trackPushOpen(getApiKey(event), request).execute(); + if (response.isSuccessful() && !response.body().isSuccess()) { throw new IOException(response.body().toString()); - } else if (!response.isSuccess()) { + } else if (!response.isSuccessful()) { throw new IOException("Error sending push-open to Iterable: HTTP " + response.code()); } } } } - @Override public AudienceMembershipChangeResponse processAudienceMembershipChangeRequest(AudienceMembershipChangeRequest request) throws IOException { - Map settings = request.getAccount().getAccountSettings(); - String apiKey = settings.get(SETTING_API_KEY); - IterableService service = IterableService.newInstance(apiKey); - return processAudienceMembershipChangeRequest(request, service); - } - - public AudienceMembershipChangeResponse processAudienceMembershipChangeRequest(AudienceMembershipChangeRequest request, IterableService service) throws IOException { HashMap> additions = new HashMap<>(); HashMap> removals = new HashMap<>(); for (UserProfile profile : request.getUserProfiles()) { @@ -569,13 +573,13 @@ public AudienceMembershipChangeResponse processAudienceMembershipChangeRequest(A subscribeRequest.listId = entry.getKey(); subscribeRequest.subscribers = entry.getValue(); try { - Response response = service.listSubscribe(subscribeRequest).execute(); - if (response.isSuccess()) { + Response response = iterableService.listSubscribe(getApiKey(request), subscribeRequest).execute(); + if (response.isSuccessful()) { ListResponse listResponse = response.body(); if (listResponse.failCount > 0) { throw new IOException("Iterable list subscribe had positive fail count: " + listResponse.failCount); } - } else if (!response.isSuccess()) { + } else if (!response.isSuccessful()) { throw new IOException("Error sending list subscribe to Iterable: HTTP " + response.code()); } } catch (Exception e) { @@ -588,13 +592,13 @@ public AudienceMembershipChangeResponse processAudienceMembershipChangeRequest(A unsubscribeRequest.listId = entry.getKey(); unsubscribeRequest.subscribers = entry.getValue(); try { - Response response = service.listUnsubscribe(unsubscribeRequest).execute(); - if (response.isSuccess()) { + Response response = iterableService.listUnsubscribe(getApiKey(request), unsubscribeRequest).execute(); + if (response.isSuccessful()) { ListResponse listResponse = response.body(); if (listResponse.failCount > 0) { throw new IOException("Iterable list unsubscribe had positive fail count: " + listResponse.failCount); } - } else if (!response.isSuccess()) { + } else if (!response.isSuccessful()) { throw new IOException("Error sending list unsubscribe to Iterable: HTTP " + response.code()); } } catch (Exception e) { diff --git a/iterable-extension/src/main/java/com/mparticle/ext/iterable/IterableLambdaEndpoint.java b/iterable-extension/src/main/java/com/mparticle/ext/iterable/IterableLambdaEndpoint.java index 61fa42d..fd4220b 100644 --- a/iterable-extension/src/main/java/com/mparticle/ext/iterable/IterableLambdaEndpoint.java +++ b/iterable-extension/src/main/java/com/mparticle/ext/iterable/IterableLambdaEndpoint.java @@ -13,11 +13,11 @@ public class IterableLambdaEndpoint implements RequestStreamHandler { - MessageSerializer serializer = new MessageSerializer(); + static MessageSerializer serializer = new MessageSerializer(); + static IterableExtension processor = new IterableExtension(); @Override public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException { - IterableExtension processor = new IterableExtension(); Message request = serializer.deserialize(input, Message.class); Message response = processor.processMessage(request); serializer.serialize(output, response); diff --git a/iterable-extension/src/test/java/com/mparticle/ext/iterable/IterableExtensionTest.java b/iterable-extension/src/test/java/com/mparticle/ext/iterable/IterableExtensionTest.java index ae99ced..d21275f 100644 --- a/iterable-extension/src/test/java/com/mparticle/ext/iterable/IterableExtensionTest.java +++ b/iterable-extension/src/test/java/com/mparticle/ext/iterable/IterableExtensionTest.java @@ -12,13 +12,14 @@ import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import retrofit.Call; -import retrofit.Response; +import retrofit2.Call; +import retrofit2.Response; import java.io.IOException; import java.math.BigDecimal; import java.util.*; +import static com.mparticle.ext.iterable.IterableExtension.SETTING_API_KEY; import static org.junit.Assert.*; public class IterableExtensionTest { @@ -46,7 +47,7 @@ public void testProcessEventProcessingRequest() throws Exception { request.setEvents(events); Account account = new Account(); HashMap settings = new HashMap(); - settings.put(IterableExtension.SETTING_API_KEY, "cool api key"); + settings.put(SETTING_API_KEY, "cool api key"); account.setAccountSettings(settings); request.setAccount(account); extension.processEventProcessingRequest(request); @@ -63,25 +64,29 @@ public void testUpdateUser() throws Exception { IterableExtension extension = new IterableExtension(); extension.iterableService = Mockito.mock(IterableService.class); Call callMock = Mockito.mock(Call.class); - Mockito.when(extension.iterableService.userUpdate(Mockito.any())) + Mockito.when(extension.iterableService.userUpdate(Mockito.any(), Mockito.any())) .thenReturn(callMock); IterableApiResponse apiResponse = new IterableApiResponse(); apiResponse.code = IterableApiResponse.SUCCESS_MESSAGE; Response response = Response.success(apiResponse); Mockito.when(callMock.execute()).thenReturn(response); EventProcessingRequest request = new EventProcessingRequest(); - + Account account = new Account(); + Map settings = new HashMap<>(); + settings.put(SETTING_API_KEY, "foo api key"); + account.setAccountSettings(settings); + request.setAccount(account); //no user identities, no API call extension.updateUser(request); UserUpdateRequest userUpdateRequest = new UserUpdateRequest(); - Mockito.verify(extension.iterableService, Mockito.never()).userUpdate(userUpdateRequest); + Mockito.verify(extension.iterableService, Mockito.never()).userUpdate("foo api key", userUpdateRequest); //user identities but no email/userid, no API call List identities = new LinkedList<>(); identities.add(new UserIdentity(UserIdentity.Type.FACEBOOK, Identity.Encoding.RAW, "123456")); request.setUserIdentities(identities); extension.updateUser(request); - Mockito.verify(extension.iterableService, Mockito.never()).userUpdate(userUpdateRequest); + Mockito.verify(extension.iterableService, Mockito.never()).userUpdate("foo api key", userUpdateRequest); //ok, now we should get a single API call identities.add(new UserIdentity(UserIdentity.Type.EMAIL, Identity.Encoding.RAW, "mptest@mparticle.com")); @@ -94,7 +99,9 @@ public void testUpdateUser() throws Exception { extension.updateUser(request); ArgumentCaptor argument = ArgumentCaptor.forClass(UserUpdateRequest.class); - Mockito.verify(extension.iterableService).userUpdate(argument.capture()); + ArgumentCaptor apiArg = ArgumentCaptor.forClass(String.class); + Mockito.verify(extension.iterableService).userUpdate(apiArg.capture(), argument.capture()); + assertEquals("foo api key", apiArg.getValue()); assertEquals("mptest@mparticle.com", argument.getValue().email); assertEquals("123456", argument.getValue().userId); assertEquals(argument.getValue().dataFields.get("some attribute key"), "some attribute value"); @@ -117,7 +124,7 @@ public void testProcessUserAttributeChangeEvent() throws Exception { IterableExtension extension = new IterableExtension(); extension.iterableService = Mockito.mock(IterableService.class); extension.processUserAttributeChangeEvent(new UserAttributeChangeEvent()); - Mockito.verify(extension.iterableService, Mockito.never()).userUpdate(Mockito.any()); + Mockito.verify(extension.iterableService, Mockito.never()).userUpdate(Mockito.any(), Mockito.any()); } /** @@ -160,7 +167,7 @@ public void testProcessCustomEvent() throws Exception { IterableExtension extension = new IterableExtension(); extension.iterableService = Mockito.mock(IterableService.class); Call callMock = Mockito.mock(Call.class); - Mockito.when(extension.iterableService.track(Mockito.any())) + Mockito.when(extension.iterableService.track(Mockito.any(), Mockito.any())) .thenReturn(callMock); IterableApiResponse apiResponse = new IterableApiResponse(); apiResponse.code = IterableApiResponse.SUCCESS_MESSAGE; @@ -172,6 +179,11 @@ public void testProcessCustomEvent() throws Exception { event.setTimestamp(timeStamp); event.setName("My Event Name"); EventProcessingRequest request = new EventProcessingRequest(); + Account account = new Account(); + Map settings = new HashMap<>(); + settings.put(SETTING_API_KEY, "foo"); + account.setAccountSettings(settings); + request.setAccount(account); List userIdentities = new LinkedList<>(); userIdentities.add(new UserIdentity(UserIdentity.Type.EMAIL, Identity.Encoding.RAW, "mptest@mparticle.com")); userIdentities.add(new UserIdentity(UserIdentity.Type.CUSTOMER, Identity.Encoding.RAW, "123456")); @@ -185,7 +197,7 @@ public void testProcessCustomEvent() throws Exception { extension.processCustomEvent(event); ArgumentCaptor argument = ArgumentCaptor.forClass(TrackRequest.class); - Mockito.verify(extension.iterableService).track(argument.capture()); + Mockito.verify(extension.iterableService).track(Mockito.any(), argument.capture()); assertEquals("My Event Name", argument.getValue().getEventName()); assertEquals("mptest@mparticle.com", argument.getValue().email); assertEquals("123456", argument.getValue().userId); @@ -208,13 +220,18 @@ public void testProcessAndroidPushMessageReceiptEvent() throws Exception { IterableExtension extension = new IterableExtension(); extension.iterableService = Mockito.mock(IterableService.class); Call callMock = Mockito.mock(Call.class); - Mockito.when(extension.iterableService.trackPushOpen(Mockito.any())) + Mockito.when(extension.iterableService.trackPushOpen(Mockito.any(), Mockito.any())) .thenReturn(callMock); IterableApiResponse apiResponse = new IterableApiResponse(); apiResponse.code = IterableApiResponse.SUCCESS_MESSAGE; Response response = Response.success(apiResponse); Mockito.when(callMock.execute()).thenReturn(response); EventProcessingRequest eventProcessingRequest = new EventProcessingRequest(); + Account account = new Account(); + Map settings = new HashMap<>(); + settings.put(SETTING_API_KEY, "foo"); + account.setAccountSettings(settings); + eventProcessingRequest.setAccount(account); eventProcessingRequest.setUserIdentities(new LinkedList<>()); PushMessageReceiptEvent event = new PushMessageReceiptEvent(); event.setContext(new Event.Context(eventProcessingRequest)); @@ -241,7 +258,7 @@ public void testProcessAndroidPushMessageReceiptEvent() throws Exception { extension.processPushMessageReceiptEvent(event); ArgumentCaptor argument = ArgumentCaptor.forClass(TrackPushOpenRequest.class); - Mockito.verify(extension.iterableService).trackPushOpen(argument.capture()); + Mockito.verify(extension.iterableService).trackPushOpen(Mockito.any(), argument.capture()); assertEquals("mptest@mparticle.com", argument.getValue().email); assertEquals("123456", argument.getValue().userId); assertEquals(12345, argument.getValue().campaignId + 0); @@ -266,7 +283,7 @@ public void testProcessiOSPushMessageReceiptEvent() throws Exception { IterableExtension extension = new IterableExtension(); extension.iterableService = Mockito.mock(IterableService.class); Call callMock = Mockito.mock(Call.class); - Mockito.when(extension.iterableService.trackPushOpen(Mockito.any())) + Mockito.when(extension.iterableService.trackPushOpen(Mockito.any(), Mockito.any())) .thenReturn(callMock); IterableApiResponse apiResponse = new IterableApiResponse(); apiResponse.code = IterableApiResponse.SUCCESS_MESSAGE; @@ -275,6 +292,11 @@ public void testProcessiOSPushMessageReceiptEvent() throws Exception { EventProcessingRequest eventProcessingRequest = new EventProcessingRequest(); eventProcessingRequest.setUserIdentities(new LinkedList<>()); PushMessageReceiptEvent event = new PushMessageReceiptEvent(); + Account account = new Account(); + Map settings = new HashMap<>(); + settings.put(SETTING_API_KEY, "foo"); + account.setAccountSettings(settings); + eventProcessingRequest.setAccount(account); event.setContext(new Event.Context(eventProcessingRequest)); IOException exception = null; event.setPayload("anything to get past null check"); @@ -300,7 +322,7 @@ public void testProcessiOSPushMessageReceiptEvent() throws Exception { extension.processPushMessageReceiptEvent(event); ArgumentCaptor argument = ArgumentCaptor.forClass(TrackPushOpenRequest.class); - Mockito.verify(extension.iterableService).trackPushOpen(argument.capture()); + Mockito.verify(extension.iterableService).trackPushOpen(Mockito.any(), argument.capture()); assertEquals("mptest@mparticle.com", argument.getValue().email); assertEquals("123456", argument.getValue().userId); assertEquals(12345, argument.getValue().campaignId + 0); @@ -332,8 +354,9 @@ public void testProcessiOSPushMessageReceiptEvent() throws Exception { public void testProcessAudienceMembershipChangeRequest() throws Exception { IterableExtension extension = new IterableExtension(); IterableService service = Mockito.mock(IterableService.class); + extension.iterableService = service; Call callMock = Mockito.mock(Call.class); - Mockito.when(service.trackPushOpen(Mockito.any())) + Mockito.when(service.trackPushOpen(Mockito.any(), Mockito.any())) .thenReturn(callMock); IterableApiResponse apiResponse = new IterableApiResponse(); apiResponse.code = IterableApiResponse.SUCCESS_MESSAGE; @@ -384,15 +407,18 @@ public void testProcessAudienceMembershipChangeRequest() throws Exception { AudienceMembershipChangeRequest request = new AudienceMembershipChangeRequest(); Account account = new Account(); Map settings = new HashMap<>(); - settings.put(IterableExtension.SETTING_API_KEY, "some api key"); + settings.put(SETTING_API_KEY, "some api key"); account.setAccountSettings(settings); request.setAccount(account); request.setUserProfiles(profiles); - extension.processAudienceMembershipChangeRequest(request, service); + extension.processAudienceMembershipChangeRequest(request); ArgumentCaptor argument = ArgumentCaptor.forClass(SubscribeRequest.class); - Mockito.verify(service, Mockito.times(3)).listSubscribe(argument.capture()); + ArgumentCaptor apiArgument = ArgumentCaptor.forClass(String.class); + Mockito.verify(service, Mockito.times(3)).listSubscribe(apiArgument.capture(), argument.capture()); + String apiKey = apiArgument.getValue(); + assertEquals("some api key", apiKey); List subscribeRequests = argument.getAllValues(); int i = 0; for (SubscribeRequest subscribeRequest : subscribeRequests) { @@ -414,7 +440,7 @@ public void testProcessAudienceMembershipChangeRequest() throws Exception { assertEquals(3, i); ArgumentCaptor unsubArg = ArgumentCaptor.forClass(UnsubscribeRequest.class); - Mockito.verify(service, Mockito.times(3)).listUnsubscribe(unsubArg.capture()); + Mockito.verify(service, Mockito.times(3)).listUnsubscribe(Mockito.any(), unsubArg.capture()); List unsubscribeRequests = unsubArg.getAllValues(); i = 0; for (UnsubscribeRequest unsubscribeRequest : unsubscribeRequests) { @@ -461,7 +487,7 @@ public void testProcessProductActionEvent() throws Exception { IterableExtension extension = new IterableExtension(); extension.iterableService = Mockito.mock(IterableService.class); Call callMock = Mockito.mock(Call.class); - Mockito.when(extension.iterableService.trackPurchase(Mockito.any())) + Mockito.when(extension.iterableService.trackPurchase(Mockito.any(), Mockito.any())) .thenReturn(callMock); IterableApiResponse apiResponse = new IterableApiResponse(); apiResponse.code = IterableApiResponse.SUCCESS_MESSAGE; @@ -472,6 +498,11 @@ public void testProcessProductActionEvent() throws Exception { event.setTimestamp(timeStamp); EventProcessingRequest request = new EventProcessingRequest(); + Account account = new Account(); + Map settings = new HashMap<>(); + settings.put(SETTING_API_KEY, "foo"); + account.setAccountSettings(settings); + request.setAccount(account); List userIdentities = new LinkedList<>(); userIdentities.add(new UserIdentity(UserIdentity.Type.EMAIL, Identity.Encoding.RAW, "mptest@mparticle.com")); userIdentities.add(new UserIdentity(UserIdentity.Type.CUSTOMER, Identity.Encoding.RAW, "123456")); @@ -499,7 +530,7 @@ public void testProcessProductActionEvent() throws Exception { event.setAction(ProductActionEvent.Action.PURCHASE); extension.processProductActionEvent(event); ArgumentCaptor purchaseArgs = ArgumentCaptor.forClass(TrackPurchaseRequest.class); - Mockito.verify(extension.iterableService, Mockito.times(1)).trackPurchase(purchaseArgs.capture()); + Mockito.verify(extension.iterableService, Mockito.times(1)).trackPurchase(Mockito.any(), purchaseArgs.capture()); TrackPurchaseRequest trackPurchaseRequest = purchaseArgs.getValue(); assertEquals(trackPurchaseRequest.user.email, "mptest@mparticle.com"); assertEquals(trackPurchaseRequest.user.userId, "123456"); diff --git a/iterable-java-sdk/build.gradle b/iterable-java-sdk/build.gradle index b55a712..64c3df9 100644 --- a/iterable-java-sdk/build.gradle +++ b/iterable-java-sdk/build.gradle @@ -8,8 +8,8 @@ repositories { } dependencies { - compile 'com.squareup.retrofit:retrofit:2.0.0-beta2' - compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2' + compile 'com.squareup.retrofit2:retrofit:2.3.0' + compile 'com.squareup.retrofit2:converter-gson:2.3.0' testCompile('junit:junit:4.12') testCompile('org.mockito:mockito-core:1.10.19') } diff --git a/iterable-java-sdk/src/main/java/com/mparticle/iterable/IterableService.java b/iterable-java-sdk/src/main/java/com/mparticle/iterable/IterableService.java index 4d4b62b..9ef0013 100644 --- a/iterable-java-sdk/src/main/java/com/mparticle/iterable/IterableService.java +++ b/iterable-java-sdk/src/main/java/com/mparticle/iterable/IterableService.java @@ -1,15 +1,16 @@ package com.mparticle.iterable; -import com.squareup.okhttp.HttpUrl; -import com.squareup.okhttp.Interceptor; -import com.squareup.okhttp.OkHttpClient; -import com.squareup.okhttp.Response; -import retrofit.Call; -import retrofit.GsonConverterFactory; -import retrofit.Retrofit; -import retrofit.http.Body; -import retrofit.http.GET; -import retrofit.http.POST; + + +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import retrofit2.Call; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.POST; +import retrofit2.http.Query; import java.io.IOException; import java.util.concurrent.TimeUnit; @@ -24,30 +25,31 @@ public interface IterableService { String HOST = "api.iterable.com"; String PARAM_API_KEY = "api_key"; + long SERVICE_TIMEOUT_MILLIS = 300; @POST("api/events/track") - Call track(@Body TrackRequest trackRequest); + Call track(@Query(IterableService.PARAM_API_KEY) String apiKey, @Body TrackRequest trackRequest); @POST("api/events/trackPushOpen") - Call trackPushOpen(@Body TrackPushOpenRequest registerRequest); + Call trackPushOpen(@Query(IterableService.PARAM_API_KEY) String apiKey, @Body TrackPushOpenRequest registerRequest); @POST("api/users/update") - Call userUpdate(@Body UserUpdateRequest trackRequest); + Call userUpdate(@Query(IterableService.PARAM_API_KEY) String apiKey, @Body UserUpdateRequest trackRequest); @POST("api/users/updateEmail") - Call updateEmail(@Body UpdateEmailRequest updateEmailRequest); + Call updateEmail(@Query(IterableService.PARAM_API_KEY) String apiKey, @Body UpdateEmailRequest updateEmailRequest); @POST("api/users/registerDeviceToken") - Call registerToken(@Body RegisterDeviceTokenRequest registerRequest); + Call registerToken(@Query(IterableService.PARAM_API_KEY) String apiKey, @Body RegisterDeviceTokenRequest registerRequest); @POST("api/lists/subscribe") - Call listSubscribe(@Body SubscribeRequest subscribeRequest); + Call listSubscribe(@Query(IterableService.PARAM_API_KEY) String apiKey, @Body SubscribeRequest subscribeRequest); @POST("api/lists/unsubscribe") - Call listUnsubscribe(@Body UnsubscribeRequest unsubscribeRequest); + Call listUnsubscribe(@Query(IterableService.PARAM_API_KEY) String apiKey, @Body UnsubscribeRequest unsubscribeRequest); @POST("api/commerce/trackPurchase") - Call trackPurchase(@Body TrackPurchaseRequest purchaseRequest); + Call trackPurchase(@Query(IterableService.PARAM_API_KEY) String apiKey, @Body TrackPurchaseRequest purchaseRequest); /** * At the moment this is only used for unit testing the list subscribe/unsubscribe API calls @@ -55,32 +57,20 @@ public interface IterableService { @GET("api/lists") Call lists(); - static IterableService newInstance(String apiKey) { - //all of this intercepter/chain stuff is just so callers don't - //have to pass the API key into every single method/api call - OkHttpClient client = new OkHttpClient(); - client.setReadTimeout(500, TimeUnit.MILLISECONDS); - client.setConnectTimeout(500, TimeUnit.MILLISECONDS); - client.interceptors().add( - chain -> chain.proceed(chain.request().newBuilder().url( - chain.request() - .httpUrl() - .newBuilder() - .addQueryParameter(IterableService.PARAM_API_KEY, apiKey) - .build() - ).build() - )); - HttpUrl url = new HttpUrl.Builder() + static IterableService newInstance() { + final OkHttpClient client = new OkHttpClient.Builder() + .connectTimeout(SERVICE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS) + .readTimeout(SERVICE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS) + .build(); + final HttpUrl url = new HttpUrl.Builder() .scheme("https") .host(IterableService.HOST) - .addQueryParameter(IterableService.PARAM_API_KEY, apiKey) .build(); - Retrofit retrofit = new Retrofit.Builder() + final Retrofit retrofit = new Retrofit.Builder() .baseUrl(url) .client(client) .addConverterFactory(GsonConverterFactory.create()) .build(); return retrofit.create(IterableService.class); } - -} +} \ No newline at end of file diff --git a/iterable-java-sdk/src/test/java/com/mparticle/iterable/IterableServiceTest.java b/iterable-java-sdk/src/test/java/com/mparticle/iterable/IterableServiceTest.java index 7f869d8..3269ef0 100644 --- a/iterable-java-sdk/src/test/java/com/mparticle/iterable/IterableServiceTest.java +++ b/iterable-java-sdk/src/test/java/com/mparticle/iterable/IterableServiceTest.java @@ -2,8 +2,8 @@ import org.junit.Before; import org.mockito.Mockito; -import retrofit.Call; -import retrofit.Response; +import retrofit2.Call; +import retrofit2.Response; import java.math.BigDecimal; import java.util.HashMap; @@ -23,26 +23,26 @@ public class IterableServiceTest { private static final String TEST_EMAIL = "testing@mparticle.com"; private static final String TEST_USER_ID = "123456"; + private static final String ITERABLE_API_KEY = ""; //put your API key here private IterableService iterableService; @Before public void setUp() throws Exception { - String iterableApiKey = ""; //put your API key here - if (iterableApiKey == null || iterableApiKey.length() == 0) { + if (ITERABLE_API_KEY == null || ITERABLE_API_KEY.length() == 0) { iterableService = Mockito.mock(IterableService.class); Call callMock = Mockito.mock(Call.class); - Mockito.when(iterableService.userUpdate(Mockito.any())) + Mockito.when(iterableService.userUpdate(Mockito.any(), Mockito.any())) .thenReturn(callMock); - Mockito.when(iterableService.track(Mockito.any())) + Mockito.when(iterableService.track(Mockito.any(),Mockito.any())) .thenReturn(callMock); - Mockito.when(iterableService.registerToken(Mockito.any())) + Mockito.when(iterableService.registerToken(Mockito.any(), Mockito.any())) .thenReturn(callMock); - Mockito.when(iterableService.trackPushOpen(Mockito.any())) + Mockito.when(iterableService.trackPushOpen(Mockito.any(), Mockito.any())) .thenReturn(callMock); - Mockito.when(iterableService.trackPurchase(Mockito.any())) + Mockito.when(iterableService.trackPurchase(Mockito.any(), Mockito.any())) .thenReturn(callMock); IterableApiResponse apiResponse = new IterableApiResponse(); apiResponse.code = IterableApiResponse.SUCCESS_MESSAGE; @@ -54,12 +54,12 @@ public void setUp() throws Exception { successlistResponse.successCount = 1; Response listResponse = Response.success(successlistResponse); Mockito.when(listCallMock.execute()).thenReturn(listResponse); - Mockito.when(iterableService.listSubscribe(Mockito.any())) + Mockito.when(iterableService.listSubscribe(Mockito.any(), Mockito.any())) .thenReturn(listCallMock); - Mockito.when(iterableService.listUnsubscribe(Mockito.any())) + Mockito.when(iterableService.listUnsubscribe(Mockito.any(), Mockito.any())) .thenReturn(listCallMock); } else { - iterableService = IterableService.newInstance(iterableApiKey); + iterableService = IterableService.newInstance(); } } @@ -68,8 +68,8 @@ public void testTrack() throws Exception { TrackRequest trackRequest = new TrackRequest("Test Event"); trackRequest.email = TEST_EMAIL; trackRequest.userId = TEST_USER_ID; - Response response = iterableService.track(trackRequest).execute(); - assertTrue("Retrofit request not successful:\nMessage: " + response.message() + "\nCode: " + response.code(), response.isSuccess()); + Response response = iterableService.track(ITERABLE_API_KEY, trackRequest).execute(); + assertTrue("Retrofit request not successful:\nMessage: " + response.message() + "\nCode: " + response.code(), response.isSuccessful()); assertTrue("Iterable response was not successful:\n" + response.body().toString(), response.body().isSuccess()); } @@ -83,8 +83,8 @@ public void testTrackPushOpen() throws Exception { Map attributes = new HashMap(); attributes.put("test push open attribute key", "test push open attribute value"); pushOpenRequest.dataFields = attributes; - Response response = iterableService.trackPushOpen(pushOpenRequest).execute(); - assertTrue("Retrofit request not successful:\nMessage: " + response.message() + "\nCode: " + response.code(), response.isSuccess()); + Response response = iterableService.trackPushOpen(ITERABLE_API_KEY, pushOpenRequest).execute(); + assertTrue("Retrofit request not successful:\nMessage: " + response.message() + "\nCode: " + response.code(), response.isSuccessful()); assertTrue("Iterable response was not successful:\n" + response.body().toString(), response.body().isSuccess()); } @@ -96,8 +96,8 @@ public void testUserUpdate() throws Exception { Map attributes = new HashMap(); attributes.put("test attribute key", "test attribute value"); userUpdateRequest.dataFields = attributes; - Response response = iterableService.userUpdate(userUpdateRequest).execute(); - assertTrue("Retrofit request not successful:\nMessage: " + response.message() + "\nCode: " + response.code(), response.isSuccess()); + Response response = iterableService.userUpdate(ITERABLE_API_KEY, userUpdateRequest).execute(); + assertTrue("Retrofit request not successful:\nMessage: " + response.message() + "\nCode: " + response.code(), response.isSuccessful()); assertTrue("Iterable response was not successful:\n" + response.body().toString(), response.body().isSuccess()); } @@ -107,17 +107,17 @@ public void testRegisterToken() throws Exception { registerRequest.email = TEST_EMAIL; registerRequest.device = new Device(); registerRequest.device.platform = Device.PLATFORM_GCM; - registerRequest.device.applicationName = "mparticletestintegration"; + registerRequest.device.applicationName = "test"; registerRequest.device.token = "thisisatestGCMtoken"; - Response response = iterableService.registerToken(registerRequest).execute(); - assertTrue("Retrofit request not successful:\nMessage: " + response.message() + "\nCode: " + response.code(), response.isSuccess()); + Response response = iterableService.registerToken(ITERABLE_API_KEY, registerRequest).execute(); + assertTrue("Retrofit request not successful:\nMessage: " + response.message() + "\nCode: " + response.code(), response.isSuccessful()); assertTrue("Iterable response was not successful:\n" + response.body().toString(), response.body().isSuccess()); } @org.junit.Test public void testListSubscribe() throws Exception { SubscribeRequest subscribeRequest = new SubscribeRequest(); - subscribeRequest.listId = 7110; + subscribeRequest.listId = 81935; subscribeRequest.subscribers = new LinkedList<>(); String userId1 = System.currentTimeMillis() + ""; @@ -139,21 +139,21 @@ public void testListSubscribe() throws Exception { subscribeRequest.subscribers.add(user1); subscribeRequest.subscribers.add(user2); - Response response = iterableService.listSubscribe(subscribeRequest).execute(); - assertTrue("Retrofit request not successful:\nMessage: " + response.message() + "\nCode: " + response.code(), response.isSuccess()); + Response response = iterableService.listSubscribe(ITERABLE_API_KEY, subscribeRequest).execute(); + assertTrue("Retrofit request not successful:\nMessage: " + response.message() + "\nCode: " + response.code(), response.isSuccessful()); assertTrue("Iterable response was not successful:\nSuccess Count: " + response.body().successCount + "\nFail Count: " + response.body().failCount, response.body().failCount < 1); } @org.junit.Test public void testListUnsubscribe() throws Exception { UnsubscribeRequest unsubscribeRequest = new UnsubscribeRequest(); - unsubscribeRequest.listId = 7110; + unsubscribeRequest.listId = 81935; Unsubscriber user = new Unsubscriber(); user.email = "newtestsubscriber@mparticle.com"; unsubscribeRequest.subscribers = new LinkedList<>(); unsubscribeRequest.subscribers.add(user); - Response response = iterableService.listUnsubscribe(unsubscribeRequest).execute(); - assertTrue("Retrofit request not successful:\nMessage: " + response.message() + "\nCode: " + response.code(), response.isSuccess()); + Response response = iterableService.listUnsubscribe(ITERABLE_API_KEY, unsubscribeRequest).execute(); + assertTrue("Retrofit request not successful:\nMessage: " + response.message() + "\nCode: " + response.code(), response.isSuccessful()); //just check for 200 since it's not feasible in an automated test to wait for Iterable to update its lists such an an unsubscribe will always work. // assertTrue("Iterable response was not successful:\nSuccess Count: " + response.body().successCount + "\nFail Count: " + response.body().failCount, response.body().failCount < 1); } @@ -174,8 +174,8 @@ public void testTrackPurchase() throws Exception { item.name = "test product name"; request.items.add(item); request.total = new BigDecimal(100d); - Response response = iterableService.trackPurchase(request).execute(); - assertTrue("Retrofit request not successful:\nMessage: " + response.message() + "\nCode: " + response.code(), response.isSuccess()); + Response response = iterableService.trackPurchase(ITERABLE_API_KEY, request).execute(); + assertTrue("Retrofit request not successful:\nMessage: " + response.message() + "\nCode: " + response.code(), response.isSuccessful()); assertTrue("Iterable response was not successful:\n" + response.body().toString(), response.body().isSuccess()); } }