Search in sources :

Example 1 with ApiCallback

use of com.fitpay.android.api.callbacks.ApiCallback in project fitpay-android-sdk by fitpay.

the class UserEventStreamSyncTest method testWebviewCommunicatorUsesUserEventStream.

@Test
public void testWebviewCommunicatorUsesUserEventStream() throws Exception {
    // setup a user and device
    this.user = getUser();
    assertNotNull(user);
    Device device = createDevice(user, getTestDevice());
    Activity context = Mockito.mock(Activity.class);
    DeviceService deviceService = new DeviceService();
    deviceService.setPaymentDeviceConnector(new MockPaymentDeviceConnector());
    // pretend to launch the webview and act like the user has logged into the WV, this should
    // cause the user event stream subscription to occur
    WebViewCommunicatorImpl wvc = new WebViewCommunicatorImpl(context, -1);
    wvc.setDeviceService(deviceService);
    wvc.sendUserData(null, device.getDeviceIdentifier(), ApiManager.getInstance().getApiService().getToken().getAccessToken(), user.getId());
    boolean subscribed = false;
    for (int i = 0; i < 10; i++) {
        subscribed = UserEventStreamManager.isSubscribed(user.getId());
        if (!subscribed) {
            Thread.sleep(500);
        }
    }
    assertTrue(UserEventStreamManager.isSubscribed(user.getId()));
    // now let's get the platform to initiate a SYNC by adding a card, the automatic sync
    // from user event stream is enabled by default, therefore we should see a sync requeset
    // come out onto the RxBus
    final CountDownLatch syncLatch = new CountDownLatch(1);
    final List<SyncRequest> syncRequests = new ArrayList<>();
    NotificationManager.getInstance().addListener(new Listener() {

        @Override
        public Map<Class, Command> getCommands() {
            mCommands.put(SyncRequest.class, data -> handleSyncRequest((SyncRequest) data));
            return mCommands;
        }

        public void handleSyncRequest(SyncRequest request) {
            syncRequests.add(request);
            syncLatch.countDown();
        }
    });
    CreditCard createdCard = createCreditCard(user, getTestCreditCard("9999504454545450"));
    final CountDownLatch latch = new CountDownLatch(1);
    createdCard.acceptTerms(new ApiCallback<CreditCard>() {

        @Override
        public void onSuccess(CreditCard result) {
            latch.countDown();
        }

        @Override
        public void onFailure(int errorCode, String errorMessage) {
            latch.countDown();
        }
    });
    syncLatch.await(30000, TimeUnit.MILLISECONDS);
    assertTrue(syncRequests.size() > 0);
    SyncRequest syncRequest = syncRequests.get(0);
    assertNotNull(syncRequest.getSyncId());
    assertNotNull(syncRequest.getSyncInfo());
    assertEquals(user.getId(), syncRequest.getSyncInfo().getUserId());
    assertEquals(device.getDeviceIdentifier(), syncRequest.getSyncInfo().getDeviceId());
    assertEquals(SyncInitiator.PLATFORM, syncRequest.getSyncInfo().getInitiator());
    assertEquals(syncRequest.getSyncId(), syncRequest.getSyncInfo().getSyncId());
    assertEquals(ApiManager.getConfig().get("clientId"), syncRequest.getSyncInfo().getClientId());
    assertNotNull(syncRequest.getConnector());
    assertNotNull(syncRequest.getDevice());
    assertEquals(device.getDeviceIdentifier(), syncRequest.getDevice().getDeviceIdentifier());
    assertNotNull(syncRequest.getUser());
    assertEquals(user.getId(), syncRequest.getUser().getId());
    // now let's close the webview and ensure the subscription is removed
    wvc.close();
    assertFalse(UserEventStreamManager.isSubscribed(user.getId()));
}
Also used : Assert.assertEquals(junit.framework.Assert.assertEquals) UserEventStreamManager(com.fitpay.android.api.sse.UserEventStreamManager) WebViewCommunicatorImpl(com.fitpay.android.webview.impl.WebViewCommunicatorImpl) NotificationManager(com.fitpay.android.utils.NotificationManager) ArrayList(java.util.ArrayList) Assert.assertTrue(junit.framework.Assert.assertTrue) UserStreamEvent(com.fitpay.android.api.models.UserStreamEvent) ApiCallback(com.fitpay.android.api.callbacks.ApiCallback) CreditCard(com.fitpay.android.api.models.card.CreditCard) MockPaymentDeviceConnector(com.fitpay.android.paymentdevice.impl.mock.MockPaymentDeviceConnector) Assert.assertNotNull(junit.framework.Assert.assertNotNull) ApiManager(com.fitpay.android.api.ApiManager) DeviceService(com.fitpay.android.paymentdevice.DeviceService) Map(java.util.Map) UserEventStreamListener(com.fitpay.android.api.sse.UserEventStreamListener) Listener(com.fitpay.android.utils.Listener) SyncRequest(com.fitpay.android.paymentdevice.models.SyncRequest) Test(org.junit.Test) Device(com.fitpay.android.api.models.device.Device) TimeUnit(java.util.concurrent.TimeUnit) Mockito(org.mockito.Mockito) CountDownLatch(java.util.concurrent.CountDownLatch) Command(com.fitpay.android.utils.Command) List(java.util.List) SyncInitiator(com.fitpay.android.api.enums.SyncInitiator) Activity(android.app.Activity) Assert.assertFalse(junit.framework.Assert.assertFalse) UserEventStreamListener(com.fitpay.android.api.sse.UserEventStreamListener) Listener(com.fitpay.android.utils.Listener) Device(com.fitpay.android.api.models.device.Device) DeviceService(com.fitpay.android.paymentdevice.DeviceService) MockPaymentDeviceConnector(com.fitpay.android.paymentdevice.impl.mock.MockPaymentDeviceConnector) ArrayList(java.util.ArrayList) Activity(android.app.Activity) CountDownLatch(java.util.concurrent.CountDownLatch) CreditCard(com.fitpay.android.api.models.card.CreditCard) WebViewCommunicatorImpl(com.fitpay.android.webview.impl.WebViewCommunicatorImpl) SyncRequest(com.fitpay.android.paymentdevice.models.SyncRequest) Map(java.util.Map) Test(org.junit.Test)

Example 2 with ApiCallback

use of com.fitpay.android.api.callbacks.ApiCallback in project fitpay-android-sdk by fitpay.

the class WebViewCommunicatorImpl method getUserAndDevice.

private void getUserAndDevice(final String deviceId, final String callbackId) {
    ApiManager.getInstance().getUser(new ApiCallback<User>() {

        @Override
        public void onSuccess(User result) {
            if (result == null) {
                onTaskError(EventCallback.USER_CREATED, callbackId, "getUser failed: result is null");
                return;
            }
            WebViewCommunicatorImpl.this.user = result;
            RxBus.getInstance().post(new UserReceived(user.getId(), user.getUsername()));
            EventCallback eventCallback = new EventCallback.Builder().setCommand(EventCallback.USER_CREATED).setStatus(EventCallback.STATUS_OK).build();
            eventCallback.send();
            result.getDevice(deviceId, new ApiCallback<Device>() {

                @Override
                public void onSuccess(Device result) {
                    WebViewCommunicatorImpl.this.device = result;
                    String token = ApiManager.getPushToken();
                    String deviceToken = device.getNotificationToken();
                    final Runnable onSuccess = () -> onTaskSuccess(EventCallback.GET_USER_AND_DEVICE, callbackId);
                    boolean automaticallySubscribeToUserEventStream = true;
                    if (ApiManager.getConfig().containsKey(ApiManager.PROPERTY_AUTOMATICALLY_SUBSCRIBE_TO_USER_EVENT_STREAM)) {
                        automaticallySubscribeToUserEventStream = "true".equals(ApiManager.getConfig().get(ApiManager.PROPERTY_AUTOMATICALLY_SUBSCRIBE_TO_USER_EVENT_STREAM));
                    }
                    if (automaticallySubscribeToUserEventStream) {
                        try {
                            UserEventStreamManager.subscribe(user.getId());
                        } catch (IOException e) {
                            FPLog.e(e);
                        }
                        boolean automaticSyncThroughUserEventStream = true;
                        if (ApiManager.getConfig().containsKey(ApiManager.PROPERTY_AUTOMATICALLY_SYNC_FROM_USER_EVENT_STREAM)) {
                            automaticSyncThroughUserEventStream = "true".equals(ApiManager.getConfig().get(ApiManager.PROPERTY_AUTOMATICALLY_SYNC_FROM_USER_EVENT_STREAM));
                        }
                        if (automaticSyncThroughUserEventStream) {
                            userEventStreamSyncListener = new UserEventStreamListener() {

                                @Override
                                public void onUserEvent(UserStreamEvent event) {
                                    if ("SYNC".equals(event.getType())) {
                                        SyncInfo syncInfo = gson.fromJson(event.getPayload(), SyncInfo.class);
                                        syncInfo.setInitiator(SyncInitiator.PLATFORM);
                                        SyncRequest syncRequest = new SyncRequest.Builder().setSyncId(syncInfo.getSyncId()).setSyncInfo(syncInfo).setConnector(deviceService.getPaymentDeviceConnector()).setDevice(device).setUser(user).build();
                                        RxBus.getInstance().post(syncRequest);
                                    }
                                }
                            };
                            NotificationManager.getInstance().addListener(userEventStreamSyncListener);
                        }
                    }
                    if (deviceToken == null || !deviceToken.equals(token)) {
                        Device updatedDevice = new Device.Builder().setNotificationToken(token).build();
                        device.updateToken(updatedDevice, deviceToken == null, new ApiCallback<Device>() {

                            @Override
                            public void onSuccess(Device result) {
                                WebViewCommunicatorImpl.this.device = result;
                                onSuccess.run();
                            }

                            @Override
                            public void onFailure(@ResultCode.Code int errorCode, String errorMessage) {
                                onTaskError(EventCallback.GET_USER_AND_DEVICE, callbackId, "update device failed:" + errorMessage);
                            }
                        });
                    } else {
                        onSuccess.run();
                    }
                }

                @Override
                public void onFailure(@ResultCode.Code int errorCode, String errorMessage) {
                    onTaskError(EventCallback.GET_USER_AND_DEVICE, callbackId, "getDevice failed " + errorMessage);
                }
            });
        }

        @Override
        public void onFailure(@ResultCode.Code int errorCode, String errorMessage) {
            onTaskError(EventCallback.USER_CREATED, callbackId, "getUser failed " + errorMessage);
        }
    });
}
Also used : User(com.fitpay.android.api.models.user.User) ApiCallback(com.fitpay.android.api.callbacks.ApiCallback) Device(com.fitpay.android.api.models.device.Device) UserStreamEvent(com.fitpay.android.api.models.UserStreamEvent) UserEventStreamListener(com.fitpay.android.api.sse.UserEventStreamListener) EventCallback(com.fitpay.android.utils.EventCallback) IOException(java.io.IOException) SyncRequest(com.fitpay.android.paymentdevice.models.SyncRequest) NotificationSyncRequest(com.fitpay.android.paymentdevice.events.NotificationSyncRequest) SyncInfo(com.fitpay.android.paymentdevice.models.SyncInfo) UserReceived(com.fitpay.android.webview.events.UserReceived)

Example 3 with ApiCallback

use of com.fitpay.android.api.callbacks.ApiCallback in project fitpay-android-sdk by fitpay.

the class Device method getAllCommits.

/**
 * Retrieves 'all' events that should be committed to this device.
 *
 * @param lastCommitId last commit id
 * @return observable
 */
public Observable<Collections.CommitsCollection> getAllCommits(final String lastCommitId) {
    return Observable.create(new Observable.OnSubscribe<Collections.CommitsCollection>() {

        @Override
        public void call(Subscriber<? super Collections.CommitsCollection> subscriber) {
            getAllCommits(lastCommitId, new ApiCallback<Collections.CommitsCollection>() {

                @Override
                public void onSuccess(Collections.CommitsCollection result) {
                    if (result == null) {
                        subscriber.onError(new Exception("commits result is null"));
                        return;
                    }
                    subscriber.onNext(result);
                    subscriber.onCompleted();
                }

                @Override
                public void onFailure(@ResultCode.Code int errorCode, String errorMessage) {
                    subscriber.onError(new DeviceOperationException(errorMessage, errorCode));
                }
            });
        }
    });
}
Also used : ApiCallback(com.fitpay.android.api.callbacks.ApiCallback) Collections(com.fitpay.android.api.models.collection.Collections) Observable(rx.Observable) DeviceOperationException(com.fitpay.android.paymentdevice.DeviceOperationException) DeviceOperationException(com.fitpay.android.paymentdevice.DeviceOperationException)

Example 4 with ApiCallback

use of com.fitpay.android.api.callbacks.ApiCallback in project fitpay-android-sdk by fitpay.

the class Device method getLastAckCommit.

/**
 * Retrieves last event that was committed to this device.
 *
 * @return observable
 */
public Observable<Commit> getLastAckCommit() {
    return Observable.create(subscriber -> getLastAckCommit(new ApiCallback<Commit>() {

        @Override
        public void onSuccess(Commit result) {
            subscriber.onNext(result);
            subscriber.onCompleted();
        }

        @Override
        public void onFailure(@ResultCode.Code int errorCode, String errorMessage) {
            subscriber.onError(new DeviceOperationException(errorMessage, errorCode));
        }
    }));
}
Also used : ApiCallback(com.fitpay.android.api.callbacks.ApiCallback) DeviceOperationException(com.fitpay.android.paymentdevice.DeviceOperationException)

Example 5 with ApiCallback

use of com.fitpay.android.api.callbacks.ApiCallback in project fitpay-android-sdk by fitpay.

the class KeysManager method updateECCKey.

public void updateECCKey(@KeyType final int type, @NonNull final Runnable successRunnable, final ApiCallback callback) {
    try {
        ECCKeyPair keyPair = createPairForType(type);
        ApiCallback<ECCKeyPair> apiCallback = new ApiCallback<ECCKeyPair>() {

            @Override
            public void onSuccess(ECCKeyPair result) {
                result.setPrivateKey(mKeysMap.get(type).getPrivateKey());
                mKeysMap.put(type, result);
                if (successRunnable != null) {
                    successRunnable.run();
                }
            }

            @Override
            public void onFailure(@ResultCode.Code int errorCode, String errorMessage) {
                if (callback != null) {
                    callback.onFailure(errorCode, errorMessage);
                }
            }
        };
        Call<ECCKeyPair> getKeyCall = ApiManager.getInstance().getClient().createEncryptionKey(keyPair);
        getKeyCall.enqueue(new CallbackWrapper<>(apiCallback));
    } catch (Exception e) {
        FPLog.e(TAG, e);
        callback.onFailure(ResultCode.REQUEST_FAILED, e.toString());
    }
}
Also used : ApiCallback(com.fitpay.android.api.callbacks.ApiCallback) ECCKeyPair(com.fitpay.android.api.models.security.ECCKeyPair)

Aggregations

ApiCallback (com.fitpay.android.api.callbacks.ApiCallback)6 DeviceOperationException (com.fitpay.android.paymentdevice.DeviceOperationException)3 UserStreamEvent (com.fitpay.android.api.models.UserStreamEvent)2 Collections (com.fitpay.android.api.models.collection.Collections)2 Device (com.fitpay.android.api.models.device.Device)2 UserEventStreamListener (com.fitpay.android.api.sse.UserEventStreamListener)2 SyncRequest (com.fitpay.android.paymentdevice.models.SyncRequest)2 Observable (rx.Observable)2 Activity (android.app.Activity)1 ApiManager (com.fitpay.android.api.ApiManager)1 SyncInitiator (com.fitpay.android.api.enums.SyncInitiator)1 CreditCard (com.fitpay.android.api.models.card.CreditCard)1 ECCKeyPair (com.fitpay.android.api.models.security.ECCKeyPair)1 User (com.fitpay.android.api.models.user.User)1 UserEventStreamManager (com.fitpay.android.api.sse.UserEventStreamManager)1 DeviceService (com.fitpay.android.paymentdevice.DeviceService)1 NotificationSyncRequest (com.fitpay.android.paymentdevice.events.NotificationSyncRequest)1 MockPaymentDeviceConnector (com.fitpay.android.paymentdevice.impl.mock.MockPaymentDeviceConnector)1 SyncInfo (com.fitpay.android.paymentdevice.models.SyncInfo)1 Command (com.fitpay.android.utils.Command)1