Search in sources :

Example 1 with LoadBundleTaskProgress

use of com.google.firebase.firestore.LoadBundleTaskProgress in project snippets-android by firebase.

the class SolutionBundles method fetchBundleFrom.

public void fetchBundleFrom() throws IOException {
    final InputStream bundleStream = getBundleStream("https://example.com/createBundle");
    LoadBundleTask loadTask = db.loadBundle(bundleStream);
    // Chain the following tasks
    // 1) Load the bundle
    // 2) Get the named query from the local cache
    // 3) Execute a get() on the named query
    loadTask.continueWithTask(new Continuation<LoadBundleTaskProgress, Task<Query>>() {

        @Override
        public Task<Query> then(@NonNull Task<LoadBundleTaskProgress> task) throws Exception {
            // Close the stream
            bundleStream.close();
            // Calling getResult() propagates errors
            LoadBundleTaskProgress progress = task.getResult(Exception.class);
            // Get the named query from the bundle cache
            return db.getNamedQuery("latest-stories-query");
        }
    }).continueWithTask(new Continuation<Query, Task<QuerySnapshot>>() {

        @Override
        public Task<QuerySnapshot> then(@NonNull Task<Query> task) throws Exception {
            Query query = task.getResult(Exception.class);
            // get() the query results from the cache
            return query.get(Source.CACHE);
        }
    }).addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (!task.isSuccessful()) {
                Log.w(TAG, "Bundle loading failed", task.getException());
                return;
            }
            // Get the QuerySnapshot from the bundle
            QuerySnapshot storiesSnap = task.getResult();
        // Use the results
        // ...
        }
    });
}
Also used : Task(com.google.android.gms.tasks.Task) LoadBundleTask(com.google.firebase.firestore.LoadBundleTask) Continuation(com.google.android.gms.tasks.Continuation) Query(com.google.firebase.firestore.Query) InputStream(java.io.InputStream) IOException(java.io.IOException) QuerySnapshot(com.google.firebase.firestore.QuerySnapshot) NonNull(androidx.annotation.NonNull) LoadBundleTask(com.google.firebase.firestore.LoadBundleTask) LoadBundleTaskProgress(com.google.firebase.firestore.LoadBundleTaskProgress)

Example 2 with LoadBundleTaskProgress

use of com.google.firebase.firestore.LoadBundleTaskProgress in project firebase-android-sdk by firebase.

the class BundleLoader method addElement.

/**
 * Adds an element from the bundle to the loader.
 *
 * <p>Returns a new progress if adding the element leads to a new progress, otherwise returns
 * null.
 */
@Nullable
public LoadBundleTaskProgress addElement(BundleElement bundleElement, long byteSize) {
    Preconditions.checkArgument(!(bundleElement instanceof BundleMetadata), "Unexpected bundle metadata element.");
    int beforeDocumentCount = documents.size();
    if (bundleElement instanceof NamedQuery) {
        queries.add((NamedQuery) bundleElement);
    } else if (bundleElement instanceof BundledDocumentMetadata) {
        BundledDocumentMetadata bundledDocumentMetadata = (BundledDocumentMetadata) bundleElement;
        documentsMetadata.put(bundledDocumentMetadata.getKey(), bundledDocumentMetadata);
        currentMetadata = bundledDocumentMetadata;
        if (!((BundledDocumentMetadata) bundleElement).exists()) {
            documents = documents.insert(bundledDocumentMetadata.getKey(), MutableDocument.newNoDocument(bundledDocumentMetadata.getKey(), bundledDocumentMetadata.getReadTime()).setReadTime(bundledDocumentMetadata.getReadTime()));
            currentMetadata = null;
        }
    } else if (bundleElement instanceof BundleDocument) {
        BundleDocument bundleDocument = (BundleDocument) bundleElement;
        if (currentMetadata == null || !bundleDocument.getKey().equals(currentMetadata.getKey())) {
            throw new IllegalArgumentException("The document being added does not match the stored metadata.");
        }
        documents = documents.insert(bundleDocument.getKey(), bundleDocument.getDocument().setReadTime(currentMetadata.getReadTime()));
        currentMetadata = null;
    }
    bytesLoaded += byteSize;
    return beforeDocumentCount != documents.size() ? new LoadBundleTaskProgress(documents.size(), bundleMetadata.getTotalDocuments(), bytesLoaded, bundleMetadata.getTotalBytes(), null, LoadBundleTaskProgress.TaskState.RUNNING) : null;
}
Also used : LoadBundleTaskProgress(com.google.firebase.firestore.LoadBundleTaskProgress) Nullable(androidx.annotation.Nullable)

Example 3 with LoadBundleTaskProgress

use of com.google.firebase.firestore.LoadBundleTaskProgress in project firebase-android-sdk by firebase.

the class BundleLoaderTest method testLoadsDocuments.

@Test
public void testLoadsDocuments() {
    BundleLoader bundleLoader = new BundleLoader(bundleCallback, createMetadata(/* documents= */
    2));
    LoadBundleTaskProgress progress = bundleLoader.addElement(new BundledDocumentMetadata(key("coll/doc1"), CREATE_TIME, /* exists= */
    true, Collections.emptyList()), 1);
    assertNull(progress);
    progress = bundleLoader.addElement(new BundleDocument(doc("coll/doc1", 1, map())), /* byteSize= */
    4);
    assertProgress(progress, /* documentsLoaded= */
    1, /* totalDocuments= */
    2, /* bytesLoaded= */
    5, /* totalBytes= */
    10);
    progress = bundleLoader.addElement(new BundledDocumentMetadata(key("coll/doc2"), CREATE_TIME, /* exists= */
    true, Collections.emptyList()), 1);
    assertNull(progress);
    progress = bundleLoader.addElement(new BundleDocument(doc("coll/doc2", 1, map())), /* byteSize= */
    4);
    assertProgress(progress, /* documentsLoaded= */
    2, /* totalDocuments= */
    2, /* bytesLoaded= */
    10, /* totalBytes= */
    10);
}
Also used : LoadBundleTaskProgress(com.google.firebase.firestore.LoadBundleTaskProgress) Test(org.junit.Test)

Example 4 with LoadBundleTaskProgress

use of com.google.firebase.firestore.LoadBundleTaskProgress in project firebase-android-sdk by firebase.

the class BundleLoaderTest method testLoadsDeletedDocuments.

@Test
public void testLoadsDeletedDocuments() {
    BundleLoader bundleLoader = new BundleLoader(bundleCallback, createMetadata(/* documents= */
    1));
    LoadBundleTaskProgress progress = bundleLoader.addElement(new BundledDocumentMetadata(key("coll/doc1"), CREATE_TIME, /* exists= */
    false, Collections.emptyList()), 10);
    assertProgress(progress, /* documentsLoaded= */
    1, /* totalDocuments= */
    1, /* bytesLoaded= */
    10, /* totalBytes= */
    10);
}
Also used : LoadBundleTaskProgress(com.google.firebase.firestore.LoadBundleTaskProgress) Test(org.junit.Test)

Example 5 with LoadBundleTaskProgress

use of com.google.firebase.firestore.LoadBundleTaskProgress in project firebase-android-sdk by firebase.

the class SyncEngine method loadBundle.

public void loadBundle(BundleReader bundleReader, LoadBundleTask resultTask) {
    try {
        BundleMetadata bundleMetadata = bundleReader.getBundleMetadata();
        boolean hasNewerBundle = localStore.hasNewerBundle(bundleMetadata);
        if (hasNewerBundle) {
            resultTask.setResult(LoadBundleTaskProgress.forSuccess(bundleMetadata));
            return;
        }
        @Nullable LoadBundleTaskProgress progress = LoadBundleTaskProgress.forInitial(bundleMetadata);
        resultTask.updateProgress(progress);
        BundleLoader bundleLoader = new BundleLoader(localStore, bundleMetadata);
        long currentBytesRead = 0;
        BundleElement bundleElement;
        while ((bundleElement = bundleReader.getNextElement()) != null) {
            long oldBytesRead = currentBytesRead;
            currentBytesRead = bundleReader.getBytesRead();
            progress = bundleLoader.addElement(bundleElement, currentBytesRead - oldBytesRead);
            if (progress != null) {
                resultTask.updateProgress(progress);
            }
        }
        ImmutableSortedMap<DocumentKey, Document> changes = bundleLoader.applyChanges();
        // TODO(b/160876443): This currently raises snapshots with `fromCache=false` if users already
        // listen to some queries and bundles has newer version.
        emitNewSnapsAndNotifyLocalStore(changes, /* remoteEvent= */
        null);
        // Save metadata, so loading the same bundle will skip.
        localStore.saveBundle(bundleMetadata);
        resultTask.setResult(LoadBundleTaskProgress.forSuccess(bundleMetadata));
    } catch (Exception e) {
        Logger.warn("Firestore", "Loading bundle failed : %s", e);
        resultTask.setException(new FirebaseFirestoreException("Bundle failed to load", FirebaseFirestoreException.Code.INVALID_ARGUMENT, e));
    } finally {
        try {
            bundleReader.close();
        } catch (IOException e) {
            Logger.warn("SyncEngine", "Exception while closing bundle", e);
        }
    }
}
Also used : BundleElement(com.google.firebase.firestore.bundle.BundleElement) FirebaseFirestoreException(com.google.firebase.firestore.FirebaseFirestoreException) IOException(java.io.IOException) Document(com.google.firebase.firestore.model.Document) MutableDocument(com.google.firebase.firestore.model.MutableDocument) FirebaseFirestoreException(com.google.firebase.firestore.FirebaseFirestoreException) IOException(java.io.IOException) BundleMetadata(com.google.firebase.firestore.bundle.BundleMetadata) DocumentKey(com.google.firebase.firestore.model.DocumentKey) LoadBundleTaskProgress(com.google.firebase.firestore.LoadBundleTaskProgress) Nullable(androidx.annotation.Nullable) BundleLoader(com.google.firebase.firestore.bundle.BundleLoader)

Aggregations

LoadBundleTaskProgress (com.google.firebase.firestore.LoadBundleTaskProgress)5 Nullable (androidx.annotation.Nullable)2 IOException (java.io.IOException)2 Test (org.junit.Test)2 NonNull (androidx.annotation.NonNull)1 Continuation (com.google.android.gms.tasks.Continuation)1 Task (com.google.android.gms.tasks.Task)1 FirebaseFirestoreException (com.google.firebase.firestore.FirebaseFirestoreException)1 LoadBundleTask (com.google.firebase.firestore.LoadBundleTask)1 Query (com.google.firebase.firestore.Query)1 QuerySnapshot (com.google.firebase.firestore.QuerySnapshot)1 BundleElement (com.google.firebase.firestore.bundle.BundleElement)1 BundleLoader (com.google.firebase.firestore.bundle.BundleLoader)1 BundleMetadata (com.google.firebase.firestore.bundle.BundleMetadata)1 Document (com.google.firebase.firestore.model.Document)1 DocumentKey (com.google.firebase.firestore.model.DocumentKey)1 MutableDocument (com.google.firebase.firestore.model.MutableDocument)1 InputStream (java.io.InputStream)1