Search in sources :

Example 1 with RealmChangeListener

use of io.realm.RealmChangeListener in project realm-java by realm.

the class ManagementRealmTests method create_acceptOffer.

@Ignore("TODO: Test is currently flaky. See https://github.com/realm/realm-java/pull/4066")
@Test
@RunTestInLooperThread
public void create_acceptOffer() {
    SyncUser user1 = UserFactory.createUser(Constants.AUTH_URL, "user1");
    final SyncUser user2 = UserFactory.createUser(Constants.AUTH_URL, "user2");
    // 1. User1 creates Realm that user2 does not have access
    final String user1RealmUrl = "realm://127.0.0.1:9080/" + user1.getIdentity() + "/permission-offer-test";
    SyncConfiguration config1 = new SyncConfiguration.Builder(user1, user1RealmUrl).errorHandler(new SyncSession.ErrorHandler() {

        @Override
        public void onError(SyncSession session, ObjectServerError error) {
            fail("Realm 1 unexpected error: " + error);
        }

        @Override
        public void onClientResetRequired(SyncSession session, ClientResetHandler handler) {
            fail("Client Reset");
        }
    }).build();
    final Realm realm1 = Realm.getInstance(config1);
    looperThread.testRealms.add(realm1);
    realm1.executeTransactionAsync(new Realm.Transaction() {

        @Override
        public void execute(Realm realm) {
            realm.createObject(Dog.class);
        }
    });
    // 2. Create configuration for User2's Realm.
    final SyncConfiguration config2 = new SyncConfiguration.Builder(user2, user1RealmUrl).build();
    // 3. Create PermissionOffer
    final AtomicReference<String> offerId = new AtomicReference<String>(null);
    final Realm user1ManagementRealm = user1.getManagementRealm();
    looperThread.testRealms.add(user1ManagementRealm);
    user1ManagementRealm.executeTransactionAsync(new Realm.Transaction() {

        @Override
        public void execute(Realm realm) {
            boolean readPermission = true;
            boolean readWritePermission = true;
            boolean managePermission = false;
            Date expiresAt = null;
            PermissionOffer offer = new PermissionOffer(user1RealmUrl, readPermission, readWritePermission, managePermission, expiresAt);
            offerId.set(offer.getId());
            realm.copyToRealm(offer);
        }
    }, new Realm.Transaction.OnSuccess() {

        @Override
        public void onSuccess() {
            // 4. Wait for offer to get an token
            RealmLog.error("OfferID: " + offerId.get());
            RealmResults<PermissionOffer> offers = user1ManagementRealm.where(PermissionOffer.class).equalTo("id", offerId.get()).findAllAsync();
            looperThread.keepStrongReference.add(offers);
            offers.addChangeListener(new RealmChangeListener<RealmResults<PermissionOffer>>() {

                @Override
                public void onChange(RealmResults<PermissionOffer> offers) {
                    final PermissionOffer offer = offers.first(null);
                    if (offer != null && offer.isSuccessful() && offer.getToken() != null) {
                        // 5. User2 uses the token to accept the offer
                        final String offerToken = offer.getToken();
                        final AtomicReference<String> offerResponseId = new AtomicReference<String>();
                        final Realm user2ManagementRealm = user2.getManagementRealm();
                        looperThread.testRealms.add(user2ManagementRealm);
                        user2ManagementRealm.executeTransactionAsync(new Realm.Transaction() {

                            @Override
                            public void execute(Realm realm) {
                                PermissionOfferResponse offerResponse = new PermissionOfferResponse(offerToken);
                                offerResponseId.set(offerResponse.getId());
                                realm.copyToRealm(offerResponse);
                            }
                        }, new Realm.Transaction.OnSuccess() {

                            @Override
                            public void onSuccess() {
                                // 6. Wait for the offer response to be accepted
                                RealmResults<PermissionOfferResponse> responses = user2ManagementRealm.where(PermissionOfferResponse.class).equalTo("id", offerResponseId.get()).findAllAsync();
                                looperThread.keepStrongReference.add(responses);
                                responses.addChangeListener(new RealmChangeListener<RealmResults<PermissionOfferResponse>>() {

                                    @Override
                                    public void onChange(RealmResults<PermissionOfferResponse> responses) {
                                        PermissionOfferResponse response = responses.first(null);
                                        if (response != null && response.isSuccessful() && response.getToken().equals(offerToken)) {
                                            // 7. Response accepted. It should now be possible for user2 to access user1's Realm
                                            Realm realm = Realm.getInstance(config2);
                                            looperThread.testRealms.add(realm);
                                            RealmResults<Dog> dogs = realm.where(Dog.class).findAll();
                                            looperThread.keepStrongReference.add(dogs);
                                            dogs.addChangeListener(new RealmChangeListener<RealmResults<Dog>>() {

                                                @Override
                                                public void onChange(RealmResults<Dog> element) {
                                                    assertEquals(1, element.size());
                                                    looperThread.testComplete();
                                                }
                                            });
                                        }
                                    }
                                });
                            }
                        });
                    }
                }
            });
        }
    });
}
Also used : RealmChangeListener(io.realm.RealmChangeListener) SyncUser(io.realm.SyncUser) PermissionOffer(io.realm.permissions.PermissionOffer) AtomicReference(java.util.concurrent.atomic.AtomicReference) ObjectServerError(io.realm.ObjectServerError) Date(java.util.Date) PermissionOfferResponse(io.realm.permissions.PermissionOfferResponse) ClientResetHandler(io.realm.ClientResetHandler) SyncSession(io.realm.SyncSession) Realm(io.realm.Realm) Dog(io.realm.entities.Dog) SyncConfiguration(io.realm.SyncConfiguration) RealmResults(io.realm.RealmResults) Ignore(org.junit.Ignore) RunTestInLooperThread(io.realm.rule.RunTestInLooperThread) Test(org.junit.Test)

Example 2 with RealmChangeListener

use of io.realm.RealmChangeListener in project realm-java by realm.

the class ProcessCommitTests method expectALot.

// FIXME: Ignore for now. They do still not work. It might be caused by two processes each creating
// a Sync Client, but it needs to be investigated.
//TODO send string from service and match
//     replicate integration tests from Cocoa
//     add gradle task to start the sh script automatically (create pid file, ==> run or kill existing process
//     check the requirement for the issue again
@Test
@Ignore
public void expectALot() throws Throwable {
    final Throwable[] exception = new Throwable[1];
    final CountDownLatch testFinished = new CountDownLatch(1);
    ExecutorService service = Executors.newSingleThreadExecutor();
    service.submit(new Runnable() {

        @Override
        public void run() {
            try {
                Looper.prepare();
                Context targetContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
                SyncUser user = UserFactory.createDefaultUser(Constants.AUTH_URL);
                String realmUrl = Constants.SYNC_SERVER_URL_2;
                final SyncConfiguration syncConfig = new SyncConfiguration.Builder(user, realmUrl).name(SendsALot.class.getSimpleName()).errorHandler(new SyncSession.ErrorHandler() {

                    @Override
                    public void onError(SyncSession session, ObjectServerError error) {
                        fail("Sync failure: " + error);
                    }

                    @Override
                    public void onClientResetRequired(SyncSession session, ClientResetHandler handler) {
                        fail("Client Reset");
                    }
                }).build();
                //TODO do this in Rule as async tests
                Realm.deleteRealm(syncConfig);
                final Realm realm = Realm.getInstance(syncConfig);
                Intent intent = new Intent(targetContext, SendsALot.class);
                targetContext.startService(intent);
                final RealmResults<TestObject> all = realm.where(TestObject.class).findAllSorted("intProp");
                all.addChangeListener(new RealmChangeListener<RealmResults<TestObject>>() {

                    @Override
                    public void onChange(RealmResults<TestObject> element) {
                        assertEquals(100, element.size());
                        for (int i = 0; i < 100; i++) {
                            assertEquals(i, element.get(i).getIntProp());
                            assertEquals("property " + i, element.get(i).getStringProp());
                        }
                        testFinished.countDown();
                    }
                });
                Looper.loop();
            } catch (Throwable e) {
                exception[0] = e;
                testFinished.countDown();
            }
        }
    });
    boolean testTimedOut = testFinished.await(30, TimeUnit.SECONDS);
    if (exception[0] != null) {
        throw exception[0];
    } else if (!testTimedOut) {
        fail("Test timed out ");
    }
}
Also used : Context(android.content.Context) RealmChangeListener(io.realm.RealmChangeListener) SyncUser(io.realm.SyncUser) TestObject(io.realm.objectserver.model.TestObject) Intent(android.content.Intent) CountDownLatch(java.util.concurrent.CountDownLatch) ObjectServerError(io.realm.ObjectServerError) ClientResetHandler(io.realm.ClientResetHandler) SendsALot(io.realm.objectserver.service.SendsALot) ExecutorService(java.util.concurrent.ExecutorService) SyncSession(io.realm.SyncSession) Realm(io.realm.Realm) SyncConfiguration(io.realm.SyncConfiguration) RealmResults(io.realm.RealmResults) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 3 with RealmChangeListener

use of io.realm.RealmChangeListener in project realm-java by realm.

the class ProcessCommitTests method expectServerCommit.

// FIXME: Ignore for now. They do still not work. It might be caused by two processes each creating
// a Sync Client, but it needs to be investigated.
@Test
@Ignore
public void expectServerCommit() throws Throwable {
    final Throwable[] exception = new Throwable[1];
    final CountDownLatch testFinished = new CountDownLatch(1);
    ExecutorService service = Executors.newSingleThreadExecutor();
    service.submit(new Runnable() {

        @Override
        public void run() {
            try {
                Looper.prepare();
                Context targetContext = InstrumentationRegistry.getTargetContext();
                SyncUser user = UserFactory.createDefaultUser(Constants.AUTH_URL);
                String realmUrl = Constants.SYNC_SERVER_URL;
                final SyncConfiguration syncConfig = new SyncConfiguration.Builder(user, realmUrl).name(SendOneCommit.class.getSimpleName()).errorHandler(new SyncSession.ErrorHandler() {

                    @Override
                    public void onError(SyncSession session, ObjectServerError error) {
                        fail("Sync failure: " + error);
                    }

                    @Override
                    public void onClientResetRequired(SyncSession session, ClientResetHandler handler) {
                        fail("Client Reset");
                    }
                }).build();
                //TODO do this in Rule as async tests
                Realm.deleteRealm(syncConfig);
                final Realm realm = Realm.getInstance(syncConfig);
                Intent intent = new Intent(targetContext, SendOneCommit.class);
                targetContext.startService(intent);
                final RealmResults<ProcessInfo> all = realm.where(ProcessInfo.class).findAll();
                all.addChangeListener(new RealmChangeListener<RealmResults<ProcessInfo>>() {

                    @Override
                    public void onChange(RealmResults<ProcessInfo> element) {
                        assertEquals(1, all.size());
                        assertEquals("Background_Process1", all.get(0).getName());
                        testFinished.countDown();
                    }
                });
                Looper.loop();
            } catch (Throwable e) {
                exception[0] = e;
                testFinished.countDown();
            }
        }
    });
    boolean testTimedOut = testFinished.await(300, TimeUnit.SECONDS);
    if (exception[0] != null) {
        throw exception[0];
    } else if (!testTimedOut) {
        fail("Test timed out ");
    }
}
Also used : Context(android.content.Context) RealmChangeListener(io.realm.RealmChangeListener) SyncUser(io.realm.SyncUser) Intent(android.content.Intent) SendOneCommit(io.realm.objectserver.service.SendOneCommit) ProcessInfo(io.realm.objectserver.model.ProcessInfo) CountDownLatch(java.util.concurrent.CountDownLatch) ObjectServerError(io.realm.ObjectServerError) ClientResetHandler(io.realm.ClientResetHandler) ExecutorService(java.util.concurrent.ExecutorService) SyncSession(io.realm.SyncSession) Realm(io.realm.Realm) SyncConfiguration(io.realm.SyncConfiguration) RealmResults(io.realm.RealmResults) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

ClientResetHandler (io.realm.ClientResetHandler)3 ObjectServerError (io.realm.ObjectServerError)3 Realm (io.realm.Realm)3 RealmChangeListener (io.realm.RealmChangeListener)3 RealmResults (io.realm.RealmResults)3 SyncConfiguration (io.realm.SyncConfiguration)3 SyncSession (io.realm.SyncSession)3 SyncUser (io.realm.SyncUser)3 Ignore (org.junit.Ignore)3 Test (org.junit.Test)3 Context (android.content.Context)2 Intent (android.content.Intent)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 ExecutorService (java.util.concurrent.ExecutorService)2 Dog (io.realm.entities.Dog)1 ProcessInfo (io.realm.objectserver.model.ProcessInfo)1 TestObject (io.realm.objectserver.model.TestObject)1 SendOneCommit (io.realm.objectserver.service.SendOneCommit)1 SendsALot (io.realm.objectserver.service.SendsALot)1 PermissionOffer (io.realm.permissions.PermissionOffer)1