Search in sources :

Example 46 with CollectionReference

use of com.google.cloud.firestore.CollectionReference in project getting-started-java by GoogleCloudPlatform.

the class TranslateServlet method doPost.

// [END getting_started_background_app_list]
/**
 * Handle a posted message from Pubsub.
 *
 * @param req The message Pubsub posts to this process.
 * @param resp Not used.
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    // Block requests that don't contain the proper verification token.
    String pubsubVerificationToken = PUBSUB_VERIFICATION_TOKEN;
    if (req.getParameter("token").compareTo(pubsubVerificationToken) != 0) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    // [START getting_started_background_translate_string]
    String body = req.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
    PubSubMessage pubsubMessage = gson.fromJson(body, PubSubMessage.class);
    TranslateMessage message = pubsubMessage.getMessage();
    // Use Translate service client to translate the message.
    Translate translate = (Translate) this.getServletContext().getAttribute("translate");
    message.setData(decode(message.getData()));
    Translation translation = translate.translate(message.getData(), Translate.TranslateOption.sourceLanguage(message.getAttributes().getSourceLang()), Translate.TranslateOption.targetLanguage(message.getAttributes().getTargetLang()));
    // [END getting_started_background_translate_string]
    message.setTranslatedText(translation.getTranslatedText());
    try {
        // [START getting_started_background_translate]
        // Use Firestore service client to store the translation in Firestore.
        Firestore firestore = (Firestore) this.getServletContext().getAttribute("firestore");
        CollectionReference translations = firestore.collection("translations");
        ApiFuture<WriteResult> setFuture = translations.document().set(message, SetOptions.merge());
        setFuture.get();
        resp.getWriter().write(translation.getTranslatedText());
    // [END getting_started_background_translate]
    } catch (InterruptedException | ExecutionException e) {
        throw new ServletException("Exception storing data in Firestore.", e);
    }
}
Also used : Translation(com.google.cloud.translate.Translation) CollectionReference(com.google.cloud.firestore.CollectionReference) ServletException(javax.servlet.ServletException) WriteResult(com.google.cloud.firestore.WriteResult) Firestore(com.google.cloud.firestore.Firestore) PubSubMessage(com.getstarted.background.objects.PubSubMessage) TranslateMessage(com.getstarted.background.objects.TranslateMessage) ExecutionException(java.util.concurrent.ExecutionException) Translate(com.google.cloud.translate.Translate)

Example 47 with CollectionReference

use of com.google.cloud.firestore.CollectionReference in project jade-data-repo by DataBiosphere.

the class FireStoreDependencyDao method fileHasSnapshotReference.

public boolean fileHasSnapshotReference(Dataset dataset, String fileId) throws InterruptedException {
    DatasetDataProject dataProject = dataLocationService.getProjectOrThrow(dataset);
    FireStoreProject fireStoreProject = FireStoreProject.get(dataProject.getGoogleProjectId());
    String dependencyCollectionName = getDatasetDependencyId(dataset.getId().toString());
    CollectionReference depColl = fireStoreProject.getFirestore().collection(dependencyCollectionName);
    Query query = depColl.whereEqualTo("fileId", fileId);
    return hasReference(query);
}
Also used : Query(com.google.cloud.firestore.Query) DatasetDataProject(bio.terra.service.dataset.DatasetDataProject) CollectionReference(com.google.cloud.firestore.CollectionReference)

Example 48 with CollectionReference

use of com.google.cloud.firestore.CollectionReference in project jade-data-repo by DataBiosphere.

the class FireStoreDependencyDao method getDatasetSnapshotFileIds.

public List<String> getDatasetSnapshotFileIds(Dataset dataset, String snapshotId) throws InterruptedException {
    DatasetDataProject dataProject = dataLocationService.getProjectOrThrow(dataset);
    FireStoreProject fireStoreProject = FireStoreProject.get(dataProject.getGoogleProjectId());
    String dependencyCollectionName = getDatasetDependencyId(dataset.getId().toString());
    CollectionReference depColl = fireStoreProject.getFirestore().collection(dependencyCollectionName);
    Query query = depColl.whereEqualTo("snapshotId", snapshotId);
    ApiFuture<QuerySnapshot> querySnapshot = query.get();
    List<String> fileIds = new ArrayList<>();
    try {
        List<QueryDocumentSnapshot> documents = querySnapshot.get().getDocuments();
        for (DocumentSnapshot docSnap : documents) {
            FireStoreDependency fireStoreDependency = docSnap.toObject(FireStoreDependency.class);
            fileIds.add(fireStoreDependency.getFileId());
        }
        return fileIds;
    } catch (ExecutionException ex) {
        throw new FileSystemExecutionException("get file ids - execution exception", ex);
    }
}
Also used : Query(com.google.cloud.firestore.Query) QueryDocumentSnapshot(com.google.cloud.firestore.QueryDocumentSnapshot) ArrayList(java.util.ArrayList) FileSystemExecutionException(bio.terra.service.filedata.exception.FileSystemExecutionException) DatasetDataProject(bio.terra.service.dataset.DatasetDataProject) CollectionReference(com.google.cloud.firestore.CollectionReference) QuerySnapshot(com.google.cloud.firestore.QuerySnapshot) QueryDocumentSnapshot(com.google.cloud.firestore.QueryDocumentSnapshot) DocumentSnapshot(com.google.cloud.firestore.DocumentSnapshot) FileSystemExecutionException(bio.terra.service.filedata.exception.FileSystemExecutionException) ExecutionException(java.util.concurrent.ExecutionException)

Example 49 with CollectionReference

use of com.google.cloud.firestore.CollectionReference in project jade-data-repo by DataBiosphere.

the class FireStoreDirectoryDao method deleteDirectoryEntry.

// true - directory entry existed and was deleted; false - directory entry did not exist
public boolean deleteDirectoryEntry(Firestore firestore, String collectionId, String fileId) {
    CollectionReference datasetCollection = firestore.collection(collectionId);
    ApiFuture<Boolean> transaction = firestore.runTransaction(xn -> {
        List<DocumentReference> deleteList = new ArrayList<>();
        // Look up the directory entry by id. If it doesn't exist, we're done
        QueryDocumentSnapshot leafSnap = lookupByFileId(firestore, collectionId, fileId, xn);
        if (leafSnap == null) {
            return false;
        }
        deleteList.add(leafSnap.getReference());
        FireStoreDirectoryEntry leafEntry = leafSnap.toObject(FireStoreDirectoryEntry.class);
        String lookupPath = makeLookupPath(leafEntry.getPath());
        while (!lookupPath.isEmpty()) {
            // Count the number of entries with this path as their directory path
            // A value of 1 means that the directory will be empty after its child is
            // deleted, so we should delete it also.
            Query query = datasetCollection.whereEqualTo("path", makePathFromLookupPath(lookupPath));
            ApiFuture<QuerySnapshot> querySnapshot = xn.get(query);
            List<QueryDocumentSnapshot> documents = querySnapshot.get().getDocuments();
            if (documents.size() > 1) {
                break;
            }
            DocumentReference docRef = datasetCollection.document(encodePathAsFirestoreDocumentName(lookupPath));
            deleteList.add(docRef);
            lookupPath = fireStoreUtils.getDirectoryPath(lookupPath);
        }
        for (DocumentReference docRef : deleteList) {
            xn.delete(docRef);
        }
        return true;
    });
    return fireStoreUtils.transactionGet("deleteDirectoryEntry", transaction);
}
Also used : Query(com.google.cloud.firestore.Query) QueryDocumentSnapshot(com.google.cloud.firestore.QueryDocumentSnapshot) ArrayList(java.util.ArrayList) CollectionReference(com.google.cloud.firestore.CollectionReference) QuerySnapshot(com.google.cloud.firestore.QuerySnapshot) DocumentReference(com.google.cloud.firestore.DocumentReference)

Example 50 with CollectionReference

use of com.google.cloud.firestore.CollectionReference in project jade-data-repo by DataBiosphere.

the class FireStoreDirectoryDao method lookupByFileId.

// Returns null if not found
private QueryDocumentSnapshot lookupByFileId(Firestore firestore, String collectionId, String fileId, Transaction xn) {
    try {
        CollectionReference datasetCollection = firestore.collection(collectionId);
        Query query = datasetCollection.whereEqualTo("fileId", fileId);
        ApiFuture<QuerySnapshot> querySnapshot = xn.get(query);
        List<QueryDocumentSnapshot> documents = querySnapshot.get().getDocuments();
        if (documents.size() == 0) {
            return null;
        }
        if (documents.size() != 1) {
            // TODO: We have seen duplicate documents as a result of concurrency issues.
            // The query.get() does not appear to be reliably transactional. That may
            // be a FireStore bug. Regardless, we treat this as a retryable situation.
            // It *might* be corruption bug on our side. If so, the retry will consistently
            // fail and eventually give up. When debugging that case, one will have to understand
            // the purpose of this logic.
            logger.warn("Found too many entries: " + documents.size() + "; for file: " + collectionId + "/" + fileId);
            throw new FileSystemAbortTransactionException("lookupByFileId found too many entries");
        }
        return documents.get(0);
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
        throw new FileSystemExecutionException("lookupByFileId - execution interrupted", ex);
    } catch (AbortedException | ExecutionException ex) {
        throw handleExecutionException("lookupByFileId", ex);
    }
}
Also used : Query(com.google.cloud.firestore.Query) QueryDocumentSnapshot(com.google.cloud.firestore.QueryDocumentSnapshot) AbortedException(com.google.api.gax.rpc.AbortedException) FileSystemExecutionException(bio.terra.service.filedata.exception.FileSystemExecutionException) FileSystemAbortTransactionException(bio.terra.service.filedata.exception.FileSystemAbortTransactionException) FileSystemExecutionException(bio.terra.service.filedata.exception.FileSystemExecutionException) ExecutionException(java.util.concurrent.ExecutionException) CollectionReference(com.google.cloud.firestore.CollectionReference) QuerySnapshot(com.google.cloud.firestore.QuerySnapshot)

Aggregations

CollectionReference (com.google.cloud.firestore.CollectionReference)72 Query (com.google.cloud.firestore.Query)48 QuerySnapshot (com.google.cloud.firestore.QuerySnapshot)16 QueryDocumentSnapshot (com.google.cloud.firestore.QueryDocumentSnapshot)12 DocumentReference (com.google.cloud.firestore.DocumentReference)11 DocumentSnapshot (com.google.cloud.firestore.DocumentSnapshot)11 ArrayList (java.util.ArrayList)11 ExecutionException (java.util.concurrent.ExecutionException)9 Test (org.junit.Test)9 WriteResult (com.google.cloud.firestore.WriteResult)7 DatasetDataProject (bio.terra.service.dataset.DatasetDataProject)6 ApiFuture (com.google.api.core.ApiFuture)6 BaseIntegrationTest (com.example.firestore.BaseIntegrationTest)5 HashMap (java.util.HashMap)5 FileSystemExecutionException (bio.terra.service.filedata.exception.FileSystemExecutionException)4 City (com.example.firestore.snippets.model.City)4 Firestore (com.google.cloud.firestore.Firestore)4 FileSystemCorruptException (bio.terra.service.filedata.exception.FileSystemCorruptException)2 TranslateMessage (com.getstarted.background.objects.TranslateMessage)2 FirestoreOptions (com.google.cloud.firestore.FirestoreOptions)2