com.google.cloud.functions.Context Java Examples

The following examples show how to use com.google.cloud.functions.Context. 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: FirebaseRtdb.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(String json, Context context) {
  logger.info("Function triggered by change to: " + context.resource());

  JsonObject body = gson.fromJson(json, JsonObject.class);

  boolean isAdmin = false;
  if (body != null && body.has("auth")) {
    JsonObject authObj = body.getAsJsonObject("auth");
    isAdmin = authObj.has("admin") && authObj.get("admin").getAsBoolean();
  }

  logger.info("Admin?: " + isAdmin);

  if (body != null && body.has("delta")) {
    logger.info("Delta:");
    logger.info(body.get("delta").toString());
  }
}
 
Example #2
Source File: OcrSaveResult.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(PubSubMessage pubSubMessage, Context context) {
  OcrTranslateApiMessage ocrMessage = OcrTranslateApiMessage.fromPubsubData(
      pubSubMessage.getData().getBytes(StandardCharsets.UTF_8));

  logger.info("Received request to save file " +  ocrMessage.getFilename());

  // [START functions_ocr_rename]
  String newFileName = String.format(
      "%s_to_%s.txt", ocrMessage.getFilename(), ocrMessage.getLang());
  // [END functions_ocr_rename]

  // Save file to RESULT_BUCKET with name newFileNaem
  logger.info(String.format("Saving result to %s in bucket %s", newFileName, RESULT_BUCKET));
  BlobInfo blobInfo = BlobInfo.newBuilder(BlobId.of(RESULT_BUCKET, newFileName)).build();
  STORAGE.create(blobInfo, ocrMessage.getText().getBytes(StandardCharsets.UTF_8));
  logger.info("File saved");
}
 
Example #3
Source File: RetryTimeout.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Background Cloud Function that only executes within
 * a certain time period after the triggering event
 */
@Override
public void accept(PubSubMessage message, Context context) {
  ZonedDateTime utcNow = ZonedDateTime.now(ZoneOffset.UTC);
  ZonedDateTime timestamp = utcNow;

  String data = message.getData();
  JsonObject body = gson.fromJson(data, JsonObject.class);
  if (body != null && body.has("timestamp")) {
    String tz = body.get("timestamp").getAsString();
    timestamp = ZonedDateTime.parse(tz);
  }
  long eventAge = Duration.between(timestamp, utcNow).toMillis();

  // Ignore events that are too old
  if (eventAge > MAX_EVENT_AGE) {
    logger.info(String.format("Dropping event %s.", data));
    return;
  }

  // Process events that are recent enough
  // To retry this invocation, throw an exception here
  logger.info(String.format("Processing event %s.", data));
}
 
Example #4
Source File: RetryPubSub.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(PubSubMessage message, Context context) {
  String bodyJson = new String(
      Base64.getDecoder().decode(message.getData()), StandardCharsets.UTF_8);
  JsonElement bodyElement = gson.fromJson(bodyJson, JsonElement.class);

  // Get the value of the "retry" JSON parameter, if one exists
  boolean retry = false;
  if (bodyElement != null && bodyElement.isJsonObject()) {
    JsonObject body = bodyElement.getAsJsonObject();

    if (body.has("retry") && body.get("retry").getAsBoolean()) {
      retry = true;
    }
  }

  // Retry if appropriate
  if (retry) {
    // Throwing an exception causes the execution to be retried
    throw new RuntimeException("Retrying...");
  } else {
    logger.info("Not retrying...");
  }
}
 
Example #5
Source File: FirebaseFirestore.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(String json, Context context) {
  JsonObject body = gson.fromJson(json, JsonObject.class);
  logger.info("Function triggered by event on: " + context.resource());
  logger.info("Event type: " + context.eventType());

  if (body != null && body.has("oldValue")) {
    logger.info("Old value:");
    logger.info(body.get("oldValue").getAsString());
  }

  if (body != null && body.has("value")) {
    logger.info("New value:");
    logger.info(body.get("value").getAsString());
  }
}
 
Example #6
Source File: FirebaseRemoteConfig.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(String json, Context context) {
  JsonObject body = gson.fromJson(json, JsonObject.class);

  if (body != null) {
    if (body.has("updateType")) {
      logger.info("Update type: " + body.get("updateType").getAsString());
    }
    if (body.has("updateOrigin")) {
      logger.info("Origin: " + body.get("updateOrigin").getAsString());
    }
    if (body.has("versionNumber")) {
      logger.info("Version: " + body.get("versionNumber").getAsString());
    }
  }
}
 
Example #7
Source File: FirebaseAuth.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(String json, Context context) {
  JsonObject body = gson.fromJson(json, JsonObject.class);

  if (body != null && body.has("uid")) {
    logger.info("Function triggered by change to user: " + body.get("uid").getAsString());
  }

  if (body != null && body.has("metadata")) {
    JsonObject metadata = body.get("metadata").getAsJsonObject();
    logger.info("Created at: " + metadata.get("createdAt").getAsString());
  }

  if (body != null && body.has("email")) {
    logger.info("Email: " + body.get("email").getAsString());
  }
}
 
Example #8
Source File: FirebaseFirestoreReactive.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(String json, Context context) {
  // Get the recently-written value
  JsonObject body = gson.fromJson(json, JsonObject.class);
  JsonObject tempJson = body.getAsJsonObject("value");

  // Verify that value.fields.original.stringValue exists
  String currentValue = null;
  if (tempJson != null) {
    tempJson = tempJson.getAsJsonObject("fields");
  }
  if (tempJson != null) {
    tempJson = tempJson.getAsJsonObject("original");
  }
  if (tempJson != null && tempJson.has("stringValue")) {
    currentValue = tempJson.get("stringValue").getAsString();
  }
  if (currentValue == null) {
    throw new IllegalArgumentException("Malformed JSON: " + json);
  }

  // Convert recently-written value to ALL CAPS
  String newValue = currentValue.toUpperCase(Locale.getDefault());

  // Update Firestore DB with ALL CAPS value
  Map<String, String> newFields = Map.of("original", newValue);

  String affectedDoc = context.resource().split("/documents/")[1].replace("\"", "");

  logger.info(String.format("Replacing value: %s --> %s", currentValue, newValue));
  try {
    FIRESTORE.document(affectedDoc).set(newFields, SetOptions.merge()).get();
  } catch (ExecutionException | InterruptedException e) {
    logger.log(Level.SEVERE, "Error updating Firestore document: " + e.getMessage(), e);
  }
}
 
Example #9
Source File: HelloGcs.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(GcsEvent event, Context context) {
  if ("google.storage.object.finalize".equals(context.eventType())) {
    // Default event type for GCS-triggered functions
    logger.info(String.format("File %s uploaded.", event.getName()));
  } else {
    logger.warning(String.format("Unsupported event type: %s", context.eventType()));
  }
}
 
Example #10
Source File: HelloPubSub.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(PubSubMessage message, Context context) {
  String name = "world";
  if (message != null && message.getData() != null) {
    name = new String(
        Base64.getDecoder().decode(message.getData().getBytes(StandardCharsets.UTF_8)),
        StandardCharsets.UTF_8);
  }
  logger.info(String.format("Hello %s!", name));
  return;
}
 
Example #11
Source File: HelloGcsGeneric.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(GcsEvent event, Context context) {
  logger.info("Event: " + context.eventId());
  logger.info("Event Type: " + context.eventType());
  logger.info("Bucket: " + event.getBucket());
  logger.info("File: " + event.getName());
  logger.info("Metageneration: " + event.getMetageneration());
  logger.info("Created: " + event.getTimeCreated());
  logger.info("Updated: " + event.getUpdated());
}
 
Example #12
Source File: SubscribeToTopic.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(PubSubMessage message, Context context) {
  if (message.getData() == null) {
    logger.info("No message provided");
    return;
  }

  String messageString = new String(
      Base64.getDecoder().decode(message.getData().getBytes(StandardCharsets.UTF_8)),
      StandardCharsets.UTF_8);
  logger.info(messageString);
}
 
Example #13
Source File: OcrProcessImage.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(GcsEvent gcsEvent, Context context) {

  // Validate parameters
  String bucket = gcsEvent.getBucket();
  if (bucket == null) {
    throw new IllegalArgumentException("Missing bucket parameter");
  }
  String filename = gcsEvent.getName();
  if (filename == null) {
    throw new IllegalArgumentException("Missing name parameter");
  }

  detectText(bucket, filename);
}
 
Example #14
Source File: FunctionInvoker.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
/**
 * The implementation of a GCF {@link RawBackgroundFunction} that will be used as the
 * entry point from GCF.
 * @param json the payload.
 * @param context event context.
 * @since 3.0.5
 */
@Override
public void accept(String json, Context context) {

	Function<Message<String>, Message<byte[]>> function = lookupFunction();
	Message<String> message = getInputType() == Void.class ? null
			: MessageBuilder.withPayload(json).setHeader("gcf_context", context).build();

	Message<byte[]> result = function.apply(message);

	if (result != null) {
		log.info("Dropping background function result: " + new String(result.getPayload()));
	}
}
 
Example #15
Source File: StackdriverLogging.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(PubSubMessage message, Context context) {
  String name = "World";

  if (!message.getData().isEmpty()) {
    name = new String(Base64.getDecoder().decode(
        message.getData().getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8);
  }
  String res = String.format("Hello, %s", name);
  logger.info(res);
}
 
Example #16
Source File: QuarkusBackgroundFunction.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(String event, Context context) throws Exception {
    if (!started) {
        throw new IOException(deploymentStatus);
    }

    // TODO maybe we can check this at static init
    if ((delegate == null && rawDelegate == null) || (delegate != null && rawDelegate != null)) {
        throw new IOException("We didn't found any BackgroundFunction or RawBackgroundFunction to run " +
                "(or there is multiple one and none selected inside your application.properties)");
    }

    if (rawDelegate != null) {
        rawDelegate.accept(event, context);
    } else {
        // here we emulate a BackgroundFunction from a RawBackgroundFunction
        // so we need to un-marshall the JSON into the delegate parameter type
        // this is done via Gson as it's the library that GCF uses internally for the same purpose
        // see NewBackgroundFunctionExecutor.TypedFunctionExecutor<T>
        // from the functions-framework-java https://github.com/GoogleCloudPlatform/functions-framework-java
        Gson gson = new Gson();
        try {
            Object eventObj = gson.fromJson(event, parameterType);
            delegate.accept(eventObj, context);
        } catch (JsonParseException e) {
            throw new RuntimeException("Could not parse received event payload into type "
                    + parameterType.getCanonicalName(), e);
        }
    }
}
 
Example #17
Source File: ImageMagick.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
@Override
// Blurs uploaded images that are flagged as Adult or Violence.
public void accept(GcsEvent gcsEvent, Context context) {
  // Validate parameters
  if (gcsEvent.getBucket() == null || gcsEvent.getName() == null) {
    logger.severe("Error: Malformed GCS event.");
    return;
  }

  BlobInfo blobInfo = BlobInfo.newBuilder(gcsEvent.getBucket(), gcsEvent.getName()).build();

  // Construct URI to GCS bucket and file.
  String gcsPath = String.format("gs://%s/%s", gcsEvent.getBucket(), gcsEvent.getName());
  logger.info(String.format("Analyzing %s", gcsEvent.getName()));

  // Construct request.
  ImageSource imgSource = ImageSource.newBuilder().setImageUri(gcsPath).build();
  Image img = Image.newBuilder().setSource(imgSource).build();
  Feature feature = Feature.newBuilder().setType(Type.SAFE_SEARCH_DETECTION).build();
  AnnotateImageRequest request =
      AnnotateImageRequest.newBuilder().addFeatures(feature).setImage(img).build();
  List<AnnotateImageRequest> requests = List.of(request);

  // Send request to the Vision API.
  try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
    BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
    List<AnnotateImageResponse> responses = response.getResponsesList();
    for (AnnotateImageResponse res : responses) {
      if (res.hasError()) {
        logger.info(String.format("Error: %s", res.getError().getMessage()));
        return;
      }
      // Get Safe Search Annotations
      SafeSearchAnnotation annotation = res.getSafeSearchAnnotation();
      if (annotation.getAdultValue() == 5 || annotation.getViolenceValue() == 5) {
        logger.info(String.format("Detected %s as inappropriate.", gcsEvent.getName()));
        blur(blobInfo);
      } else {
        logger.info(String.format("Detected %s as OK.", gcsEvent.getName()));
      }
    }
  } catch (IOException e) {
    logger.log(Level.SEVERE, "Error with Vision API: " + e.getMessage(), e);
  }
}
 
Example #18
Source File: BackgroundFunctionStorageTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public void accept(StorageEvent event, Context context) throws Exception {
    System.out.println("Receive event on file: " + event.name);
    System.out.println("Be polite, say " + greetingService.hello());
}
 
Example #19
Source File: GcfJarLauncher.java    From spring-cloud-function with Apache License 2.0 4 votes vote down vote up
@Override
public void accept(String json, Context context) {
	Thread.currentThread().setContextClassLoader(this.loader);
	((RawBackgroundFunction) delegate).accept(json, context);
}
 
Example #20
Source File: RawBackgroundFunctionPubSubTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public void accept(String event, Context context) throws Exception {
    System.out.println("PubSub event: " + event);
    System.out.println("Be polite, say " + greetingService.hello());
}