Java Code Examples for com.google.api.core.ApiFuture#get()
The following examples show how to use
com.google.api.core.ApiFuture#get() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Guestbook.java From java-docs-samples with Apache License 2.0 | 6 votes |
/** Query Firstore for Guestbook greetings */ public List<Greeting> getGreetings() { // Initialize a List for Greetings. ImmutableList.Builder<Greeting> greetings = new ImmutableList.Builder<Greeting>(); // Construct query. ApiFuture<QuerySnapshot> query = bookRef.collection("Greetings").orderBy("date", Direction.DESCENDING).get(); try { // Get query documents. QuerySnapshot querySnapshot = query.get(); for (QueryDocumentSnapshot greeting : querySnapshot.getDocuments()) { greetings.add(greeting.toObject(Greeting.class)); } } catch (Exception e) { System.out.println(e.getMessage()); } return greetings.build(); }
Example 2
Source File: ComputeExample.java From google-cloud-java with Apache License 2.0 | 6 votes |
/** Use an callable object to make an addresses.insert method call. */ private static void insertAddressUsingCallable(AddressClient client, String newAddressName) throws InterruptedException, ExecutionException { // Begin samplegen code for insertAddress(). ProjectRegionName region = ProjectRegionName.of(PROJECT_NAME, REGION); Address address = Address.newBuilder().build(); InsertAddressHttpRequest request = InsertAddressHttpRequest.newBuilder() .setRegion(region.toString()) .setAddressResource(address) .build(); ApiFuture<Operation> future = client.insertAddressCallable().futureCall(request); // Do something Operation response = future.get(); // End samplegen code for insertAddress(). System.out.format("Result of insert: %s\n", response.toString()); }
Example 3
Source File: Quickstart.java From java-docs-samples with Apache License 2.0 | 6 votes |
void retrieveAllDocuments() throws Exception { // [START fs_get_all] // asynchronously retrieve all users ApiFuture<QuerySnapshot> query = db.collection("users").get(); // ... // query.get() blocks on response QuerySnapshot querySnapshot = query.get(); List<QueryDocumentSnapshot> documents = querySnapshot.getDocuments(); for (QueryDocumentSnapshot document : documents) { System.out.println("User: " + document.getId()); System.out.println("First: " + document.getString("first")); if (document.contains("middle")) { System.out.println("Middle: " + document.getString("middle")); } System.out.println("Last: " + document.getString("last")); System.out.println("Born: " + document.getLong("born")); } // [END fs_get_all] }
Example 4
Source File: MyDataStore.java From smart-home-java with Apache License 2.0 | 6 votes |
public String getUserId(String token) throws ExecutionException, InterruptedException { if (token == null) { token = "Bearer 123access"; } ApiFuture<QuerySnapshot> userQuery = database.collection("users").whereEqualTo("fakeAccessToken", token.substring(7)).get(); QuerySnapshot usersSnapshot = userQuery.get(); List<QueryDocumentSnapshot> users = usersSnapshot.getDocuments(); DocumentSnapshot user; try { user = users.get(0); } catch (Exception e) { LOGGER.error("no user found!"); throw e; } return user.getId(); }
Example 5
Source File: ManageDataSnippets.java From java-docs-samples with Apache License 2.0 | 6 votes |
/** * Return information from a conditional transaction. * * * @param population : set initial population. */ String returnInfoFromTransaction(long population) throws Exception { Map<String, Object> map = new HashMap<>(); map.put("population", population); // Block until transaction is complete is using transaction.get() db.collection("cities").document("SF").set(map).get(); // [START fs_return_info_transaction] final DocumentReference docRef = db.collection("cities").document("SF"); ApiFuture<String> futureTransaction = db.runTransaction(transaction -> { DocumentSnapshot snapshot = transaction.get(docRef).get(); Long newPopulation = snapshot.getLong("population") + 1; // conditionally update based on current population if (newPopulation <= 1000000L) { transaction.update(docRef, "population", newPopulation); return "Population increased to " + newPopulation; } else { throw new Exception("Sorry! Population is too big."); } }); // Print information retrieved from transaction System.out.println(futureTransaction.get()); // [END fs_return_info_transaction] return futureTransaction.get(); }
Example 6
Source File: ManageDataSnippets.java From java-docs-samples with Apache License 2.0 | 5 votes |
/** Partially update a document using the .update(field1, value1..) method. */ void updateSimpleDocument() throws Exception { db.collection("cities").document("DC").set(new City("Washington D.C.")).get(); // [START fs_update_doc] // Update an existing document DocumentReference docRef = db.collection("cities").document("DC"); // (async) Update one field ApiFuture<WriteResult> future = docRef.update("capital", true); // ... WriteResult result = future.get(); System.out.println("Write result: " + result); // [END fs_update_doc] }
Example 7
Source File: RetrieveDataSnippetsIT.java From java-docs-samples with Apache License 2.0 | 5 votes |
private static void deleteAllDocuments() throws Exception { ApiFuture<QuerySnapshot> future = db.collection("cities").get(); QuerySnapshot querySnapshot = future.get(); for (DocumentSnapshot doc : querySnapshot.getDocuments()) { // block on delete operation db.collection("cities").document(doc.getId()).delete().get(); } }
Example 8
Source File: ManageDataSnippetsIT.java From java-docs-samples with Apache License 2.0 | 5 votes |
@Test public void testSimpleTransaction() throws Exception { DocumentReference docRef = db.collection("cities").document("SF"); ApiFuture<Void> future = manageDataSnippets.runSimpleTransaction(); future.get(); Map<String, Object> data = getDocumentDataAsMap(docRef); assertEquals(data.get("population"), 860000L + 1L); }
Example 9
Source File: QueryDataSnippetsIT.java From java-docs-samples with Apache License 2.0 | 5 votes |
private List<String> getResults(Query query) throws Exception { // asynchronously retrieve query results ApiFuture<QuerySnapshot> future = query.get(); // block on response QuerySnapshot querySnapshot = future.get(); List<String> docIds = new ArrayList<>(); for (DocumentSnapshot document : querySnapshot.getDocuments()) { docIds.add(document.getId()); } return docIds; }
Example 10
Source File: QuickstartIT.java From java-docs-samples with Apache License 2.0 | 5 votes |
private void deleteAllDocuments() throws Exception { ApiFuture<QuerySnapshot> future = db.collection("users").get(); QuerySnapshot querySnapshot = future.get(); for (DocumentSnapshot doc : querySnapshot.getDocuments()) { // block on delete operation db.document("users/" + doc.getId()).delete().get(); } }
Example 11
Source File: BaseIntegrationTest.java From java-docs-samples with Apache License 2.0 | 5 votes |
protected static void deleteAllDocuments(Firestore db) throws Exception { ApiFuture<QuerySnapshot> future = db.collection("cities").get(); QuerySnapshot querySnapshot = future.get(); for (DocumentSnapshot doc : querySnapshot.getDocuments()) { // block on delete operation db.collection("cities").document(doc.getId()).delete().get(); } }
Example 12
Source File: ManageDataSnippets.java From java-docs-samples with Apache License 2.0 | 5 votes |
/** Write documents in a batch. */ void writeBatch() throws Exception { db.collection("cities").document("SF").set(new City()).get(); db.collection("cities").document("LA").set(new City()).get(); // [START fs_write_batch] // Get a new write batch WriteBatch batch = db.batch(); // Set the value of 'NYC' DocumentReference nycRef = db.collection("cities").document("NYC"); batch.set(nycRef, new City()); // Update the population of 'SF' DocumentReference sfRef = db.collection("cities").document("SF"); batch.update(sfRef, "population", 1000000L); // Delete the city 'LA' DocumentReference laRef = db.collection("cities").document("LA"); batch.delete(laRef); // asynchronously commit the batch ApiFuture<List<WriteResult>> future = batch.commit(); // ... // future.get() blocks on batch commit operation for (WriteResult result :future.get()) { System.out.println("Update time : " + result.getUpdateTime()); } // [END fs_write_batch] }
Example 13
Source File: ManageDataSnippets.java From java-docs-samples with Apache License 2.0 | 5 votes |
/** Partial update nested fields of a document. */ void updateNestedFields() throws Exception { //CHECKSTYLE OFF: VariableDeclarationUsageDistance // [START fs_update_nested_fields] // Create an initial document to update DocumentReference frankDocRef = db.collection("users").document("frank"); Map<String, Object> initialData = new HashMap<>(); initialData.put("name", "Frank"); initialData.put("age", 12); Map<String, Object> favorites = new HashMap<>(); favorites.put("food", "Pizza"); favorites.put("color", "Blue"); favorites.put("subject", "Recess"); initialData.put("favorites", favorites); ApiFuture<WriteResult> initialResult = frankDocRef.set(initialData); // Confirm that data has been successfully saved by blocking on the operation initialResult.get(); // Update age and favorite color Map<String, Object> updates = new HashMap<>(); updates.put("age", 13); updates.put("favorites.color", "Red"); // Async update document ApiFuture<WriteResult> writeResult = frankDocRef.update(updates); // ... System.out.println("Update time : " + writeResult.get().getUpdateTime()); // [END fs_update_nested_fields] //CHECKSTYLE ON: VariableDeclarationUsageDistance }
Example 14
Source File: QueryDataSnippets.java From java-docs-samples with Apache License 2.0 | 5 votes |
/** * Create a query using a snapshot as a start point. * * @return query */ Query createStartAtSnapshotQueryCursor() throws InterruptedException, ExecutionException, TimeoutException { // [START fs_document_snapshot_cursor] // Fetch the snapshot with an API call, waiting for a maximum of 30 seconds for a result. ApiFuture<DocumentSnapshot> future = db.collection("cities").document("SF").get(); DocumentSnapshot snapshot = future.get(30, TimeUnit.SECONDS); // Construct the query Query query = db.collection("cities").orderBy("population").startAt(snapshot); // [END fs_document_snapshot_cursor] return query; }
Example 15
Source File: TranslateSnippetsBeta.java From google-cloud-java with Apache License 2.0 | 5 votes |
/** * Lists all the supported language codes. * * @param projectId - Id of the project. * @param location - location name. */ // [START translate_list_codes_beta] static SupportedLanguages listSupportedLanguages(String projectId, String location) { try (TranslationServiceClient translationServiceClient = TranslationServiceClient.create()) { LocationName locationName = LocationName.newBuilder().setProject(projectId).setLocation(location).build(); GetSupportedLanguagesRequest getSupportedLanguagesRequest = GetSupportedLanguagesRequest.newBuilder().setParent(locationName.toString()).build(); // Call the API ApiFuture<SupportedLanguages> future = translationServiceClient .getSupportedLanguagesCallable() .futureCall(getSupportedLanguagesRequest); SupportedLanguages response = future.get(); List<SupportedLanguage> languages = response.getLanguagesList(); for (SupportedLanguage language : languages) { System.out.printf("Code: %s\n", language.getLanguageCode()); } return response; } catch (Exception e) { throw new RuntimeException("Couldn't create client.", e); } }
Example 16
Source File: FirebaseAuthenticationProvider.java From spring-security-firebase with MIT License | 5 votes |
@Override protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { final FirebaseAuthenticationToken authenticationToken = (FirebaseAuthenticationToken) authentication; ApiFuture<FirebaseToken> task = firebaseAuth.verifyIdTokenAsync(authenticationToken.getToken()); try { FirebaseToken token = task.get(); return new FirebaseUserDetails(token.getEmail(), token.getUid()); } catch (InterruptedException | ExecutionException e) { throw new SessionAuthenticationException(e.getMessage()); } }
Example 17
Source File: AlbumDemo.java From java-photoslibrary with Apache License 2.0 | 5 votes |
private static Runnable getOnUploadFinished( PhotosLibraryClient client, PhotoListView photoListView, ApiFuture<UploadMediaItemResponse> uploadResponseFuture, Album album, String fileName) { return () -> { try { UploadMediaItemResponse uploadResponse = uploadResponseFuture.get(); // Check if the upload is successful if (uploadResponse.getUploadToken().isPresent()) { BatchCreateMediaItemsRequest.Builder createRequestBuilder = BatchCreateMediaItemsRequest.newBuilder(); createRequestBuilder.setAlbumId(album.getId()); createRequestBuilder .addNewMediaItemsBuilder() .getSimpleMediaItemBuilder() .setFileName(fileName) .setUploadToken(uploadResponse.getUploadToken().get()); client.batchCreateMediaItems(createRequestBuilder.build()); // Hide loading dialog after finishing creating LoadingView.getLoadingView().hideView(); photoListView.updateView(); } else { LoadingView.getLoadingView().hideView(); JOptionPane.showMessageDialog(photoListView, uploadResponse.getError()); } } catch (Exception e) { LoadingView.getLoadingView().hideView(); JOptionPane.showMessageDialog(photoListView, e.getMessage()); } }; }
Example 18
Source File: PubSubPusher.java From daq with Apache License 2.0 | 5 votes |
public String sendMessage(Map<String, String> attributes, String body) { try { PubsubMessage message = PubsubMessage.newBuilder() .setData(ByteString.copyFrom(body, Charset.defaultCharset())) .putAllAttributes(attributes) .build(); ApiFuture<String> publish = publisher.publish(message); return publish.get(); } catch (Exception e) { throw new RuntimeException("While sending to topic " + registrar_topic, e); } }
Example 19
Source File: TranslateServlet.java From getting-started-java with Apache License 2.0 | 4 votes |
/** * 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); } }
Example 20
Source File: DetectBatchAnnotateFilesGcs.java From java-docs-samples with Apache License 2.0 | 4 votes |
public static void detectBatchAnnotateFilesGcs(String gcsPath) { // String gcsPath = "gs://Your_BUCKET_ID/path_to_your_data"; try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { // Annotate the first two pages and the last one (max 5 pages) // First page starts at 1, and not 0. Last page is -1. List<Integer> pages = Arrays.asList(1, 2, -1); GcsSource gcsSource = GcsSource.newBuilder().setUri(gcsPath).build(); Feature feat = Feature.newBuilder().setType(Type.DOCUMENT_TEXT_DETECTION).build(); // Other supported mime types : 'image/tiff' or 'image/gif' InputConfig inputConfig = InputConfig.newBuilder().setMimeType("application/pdf").setGcsSource(gcsSource).build(); AnnotateFileRequest request = AnnotateFileRequest.newBuilder() .addFeatures(feat) .setInputConfig(inputConfig) .addAllPages(pages) .build(); List<AnnotateFileRequest> requests = new ArrayList<>(); requests.add(request); BatchAnnotateFilesRequest batchAnnotateFilesRequest = BatchAnnotateFilesRequest.newBuilder().addAllRequests(requests).build(); ApiFuture<BatchAnnotateFilesResponse> future = client.batchAnnotateFilesCallable().futureCall(batchAnnotateFilesRequest); BatchAnnotateFilesResponse response = future.get(); // Getting the first response AnnotateFileResponse annotateFileResponse = response.getResponses(0); // For full list of available annotations, see http://g.co/cloud/vision/docs TextAnnotation textAnnotation = annotateFileResponse.getResponses(0).getFullTextAnnotation(); for (Page page : textAnnotation.getPagesList()) { String pageText = ""; for (Block block : page.getBlocksList()) { String blockText = ""; for (Paragraph para : block.getParagraphsList()) { String paraText = ""; for (Word word : para.getWordsList()) { String wordText = ""; for (Symbol symbol : word.getSymbolsList()) { wordText = wordText + symbol.getText(); System.out.format( "Symbol text: %s (Confidence: %f)\n", symbol.getText(), symbol.getConfidence()); } System.out.format( "Word text: %s (Confidence: %f)\n\n", wordText, word.getConfidence()); paraText = String.format("%s %s", paraText, wordText); } // Output Example using Paragraph: System.out.println("\nParagraph: \n" + paraText); System.out.format("Paragraph Confidence: %f\n", para.getConfidence()); blockText = blockText + paraText; } pageText = pageText + blockText; } } System.out.println("\nComplete annotation:"); System.out.println(textAnnotation.getText()); } catch (Exception e) { System.out.println("Error during detectPdfText: \n" + e.toString()); } }