Pic-a-daily: Store and Analyze Pictures with Google Native Java Client Libraries

1. Overview

In the first code lab, you will store pictures in a bucket. This will generate a file creation event that will be handled by a service deployed in Cloud Run. The service will make a call to Vision API to do image analysis and save results in a datastore.


What you'll learn

  • Cloud Storage
  • Cloud Run
  • Cloud Vision API
  • Cloud Firestore

2. Setup and Requirements

Self-paced environment setup

  1. Sign-in to the Google Cloud Console and create a new project or reuse an existing one. If you don't already have a Gmail or Google Workspace account, you must create one.




  • The Project name is the display name for this project's participants. It is a character string not used by Google APIs. You can update it at any time.
  • The Project ID must be unique across all Google Cloud projects and is immutable (cannot be changed after it has been set). The Cloud Console auto-generates a unique string; usually you don't care what it is. In most codelabs, you'll need to reference the Project ID (it is typically identified as PROJECT_ID). If you don't like the generated ID, you may generate another random one. Alternatively, you can try your own and see if it's available. It cannot be changed after this step and will remain for the duration of the project.
  • For your information, there is a third value, a Project Number which some APIs use. Learn more about all three of these values in the documentation.
  1. Next, you'll need to enable billing in the Cloud Console to use Cloud resources/APIs. Running through this codelab shouldn't cost much, if anything at all. To shut down resources so you don't incur billing beyond this tutorial, you can delete the resources you created or delete the whole project. New users of Google Cloud are eligible for the $300 USD Free Trial program.

Start Cloud Shell

While Google Cloud can be operated remotely from your laptop, in this codelab you will be using Google Cloud Shell, a command line environment running in the Cloud.

From the Google Cloud Console, click the Cloud Shell icon on the top right toolbar:


It should only take a few moments to provision and connect to the environment. When it is finished, you should see something like this:


This virtual machine is loaded with all the development tools you'll need. It offers a persistent 5GB home directory, and runs on Google Cloud, greatly enhancing network performance and authentication. All of your work in this codelab can be done within a browser. You do not need to install anything.

3. Enable APIs

For this lab, you will be using Cloud Functions and Vision API but first they need to be enabled either in Cloud Console or with gcloud.

To enable Vision API in Cloud Console, search for Cloud Vision API in the search bar:


You will land on the Cloud Vision API page:


Click the ENABLE button.

Alternatively, you can also enable it Cloud Shell using the gcloud command line tool.

Inside Cloud Shell, run the following command:

gcloud services enable vision.googleapis.com

You should see the operation to finish successfully:

Operation "operations/acf.12dba18b-106f-4fd2-942d-fea80ecc5c1c" finished successfully.

Enable Cloud Run and Cloud Build as well:

gcloud services enable cloudbuild.googleapis.com \

4. Create the bucket (console)

Create a storage bucket for the pictures. You can do this from Google Cloud Platform console ( console.cloud.google.com) or with gsutil command line tool from Cloud Shell or your local development environment.

From the "hamburger" (☰) menu, navigate to the Storage page.


Name your bucket

Click on the CREATE BUCKET button.



Choose Location


Create a multi-regional bucket in the region of your choice (here Europe).


Choose default storage class


Choose the Standard storage class for your data.


Set Access Control


As you will be working with publicly accessible images, you want all our pictures stored in this bucket to have the same uniform access control.

Choose the Uniform access control option.


Set Protection/Encryption


Keep default (Google-managed key), as you won't use your own encryption keys.

Click CREATE, to eventually finalize our bucket creation.

Add allUsers as storage viewer

Go to the Permissions tab:


Add an allUsers member to the bucket, with a role of Storage > Storage Object Viewer, as follows:


Click SAVE.

5. Create the bucket (gsutil)

You can also use the gsutil command line tool in Cloud Shell to create buckets.

In Cloud Shell, set a variable for the unique bucket name. Cloud Shell already has GOOGLE_CLOUD_PROJECT set to your unique project id. You can append that to the bucket name.

For example:

export BUCKET_PICTURES=uploaded-pictures-${GOOGLE_CLOUD_PROJECT}

Create a standard multi-region zone in Europe:

gsutil mb -l EU gs://${BUCKET_PICTURES}

Ensure uniform bucket level access:

gsutil uniformbucketlevelaccess set on gs://${BUCKET_PICTURES}

Make the bucket public:

gsutil iam ch allUsers:objectViewer gs://${BUCKET_PICTURES}

If you go to Cloud Storage section of the console, you should have a public uploaded-pictures bucket:


Test that you can upload pictures to the bucket and the uploaded pictures are publicly available, as explained in the previous step.

6. Test public access to the bucket

Going back to the storage browser, you'll see your bucket in the list, with "Public" access (including a warning sign reminding you that anyone has access to the content of that bucket).


Your bucket is now ready to receive pictures.

If you click on the bucket name, you'll see the bucket details.


There, you can try the Upload files button, to test that you can add a picture to the bucket. A file chooser popup will ask you to select a file. Once selected, it'll be uploaded to your bucket, and you will see again the public access that has been automatically attributed to this new file.


Along the Public access label, you will also see a little link icon. When clicking on it, your browser will navigate to the public URL of that image, which will be of the form:


With BUCKET_NAME being the globally unique name you have chosen for your bucket, and then the file name of your picture.

By clicking on the check box along the picture name, the DELETE button will be enabled, and you can delete this first image.

7. Prepare the database

You will store information about the picture given by the Vision API into the Cloud Firestore database, a fast, fully managed, serverless, cloud-native NoSQL document database. Prepare your database by going to the Firestore section of the Cloud Console:


Two options are offered: Native mode or Datastore mode. Use the native mode, which offers extra features like offline support and real-time synchronization.



Pick a multi-region (here in Europe, but ideally at least the same region your function and storage bucket are).

Click the CREATE DATABASE button.

Once the database is created, you should see the following:


Create a new collection by clicking the + START COLLECTION button.

Name collection pictures.


You don't need to create a document. You'll add them programmatically as new pictures are stored in Cloud Storage and analysed by the Vision API.

Click Save.

Firestore creates a first default document in the newly created collection, you can safely delete that document as it doesn't contain any useful information:


The documents that will be created programmatically in our collection will contain 4 fields:

  • name (string): the file name of the uploaded picture, which is also he key of the document
  • labels (array of strings): the labels of recognised items by the Vision API
  • color (string): the hexadecimal color code of the dominant color (ie. #ab12ef)
  • created (date): the timestamp of when this image's metadata was stored
  • thumbnail (boolean): an optional field that will be present and be true if a thumbnail image has been generated for this picture

As we will be searching in Firestore to find pictures that have thumbnails available, and sorting along the creation date, we'll need to create a search index.

You can create the index with the following command in Cloud Shell:

gcloud firestore indexes composite create \
  --collection-group=pictures \
  --field-config field-path=thumbnail,order=descending \
  --field-config field-path=created,order=descending

Or you can also do it from the Cloud Console, by clicking on Indexes, in the navigation column on the left, and then creating a composite index as shown below:


Click Create. Index creation can take a few minutes.

8. Clone the code

Clone the code, if you haven't already in the previous code lab:

git clone https://github.com/GoogleCloudPlatform/serverless-photosharing-workshop

You can then go to the directory containing the service to start building the lab:

cd serverless-photosharing-workshop/services/image-analysis/java

You will have the following file layout for the service:


9. Explore the service code

You start by looking at how the Java Client Libraries are enabled in the pom.xml using a BOM:

First, edit the pom.xml file which lists the dependencies of our Java function. Update the code to add the Cloud Vision API Maven dependency:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">




The functionality is implemented in the EventController class. Each time a new image is being uploaded to the bucket, the service will receive a notification to process:

public class EventController {
  private static final Logger logger = Logger.getLogger(EventController.class.getName());
  private static final List<String> requiredFields = Arrays.asList("ce-id", "ce-source", "ce-type", "ce-specversion");

  @RequestMapping(value = "/", method = RequestMethod.POST)
  public ResponseEntity<String> receiveMessage(
    @RequestBody Map<String, Object> body, @RequestHeader Map<String, String> headers) throws IOException, InterruptedException, ExecutionException {

The code will proceed to validate the Cloud Events headers:

System.out.println("Header elements");
for (String field : requiredFields) {
    if (headers.get(field) == null) {
    String msg = String.format("Missing expected header: %s.", field);
    return new ResponseEntity<String>(msg, HttpStatus.BAD_REQUEST);
    } else {
    System.out.println(field + " : " + headers.get(field));

System.out.println("Body elements");
for (String bodyField : body.keySet()) {
    System.out.println(bodyField + " : " + body.get(bodyField));

if (headers.get("ce-subject") == null) {
    String msg = "Missing expected header: ce-subject.";
    return new ResponseEntity<String>(msg, HttpStatus.BAD_REQUEST);

A request can now be built and the code will prepare one such request to be sent to the Vision API:

try (ImageAnnotatorClient vision = ImageAnnotatorClient.create()) {
    List<AnnotateImageRequest> requests = new ArrayList<>();
    ImageSource imageSource = ImageSource.newBuilder()
        .setGcsImageUri("gs://" + bucketName + "/" + fileName)

    Image image = Image.newBuilder()

    Feature featureLabel = Feature.newBuilder()
    Feature featureImageProps = Feature.newBuilder()
    Feature featureSafeSearch = Feature.newBuilder()
    AnnotateImageRequest request = AnnotateImageRequest.newBuilder()

We're asking for 3 key capabilities of the Vision API:

  • Label detection: to understand what's in those pictures
  • Image properties: to give interesting attributes of the picture (we're interested in the dominant color of the picture)
  • Safe search: to know if the image is safe to show (it shouldn't contain adult / medical / racy / violent content)

At this point, we can make the call to the Vision API:

logger.info("Calling the Vision API...");
BatchAnnotateImagesResponse result = vision.batchAnnotateImages(requests);
List<AnnotateImageResponse> responses = result.getResponsesList();

For reference, here's what the response from the Vision API looks like:

  "faceAnnotations": [],
  "landmarkAnnotations": [],
  "logoAnnotations": [],
  "labelAnnotations": [
      "locations": [],
      "properties": [],
      "mid": "/m/01yrx",
      "locale": "",
      "description": "Cat",
      "score": 0.9959855675697327,
      "confidence": 0,
      "topicality": 0.9959855675697327,
      "boundingPoly": null
    ✄ - - - ✄
  "textAnnotations": [],
  "localizedObjectAnnotations": [],
  "safeSearchAnnotation": {
    "adult": "VERY_UNLIKELY",
    "spoof": "UNLIKELY",
    "medical": "VERY_UNLIKELY",
    "violence": "VERY_UNLIKELY",
    "racy": "VERY_UNLIKELY",
    "adultConfidence": 0,
    "spoofConfidence": 0,
    "medicalConfidence": 0,
    "violenceConfidence": 0,
    "racyConfidence": 0,
    "nsfwConfidence": 0
  "imagePropertiesAnnotation": {
    "dominantColors": {
      "colors": [
          "color": {
            "red": 203,
            "green": 201,
            "blue": 201,
            "alpha": null
          "score": 0.4175916016101837,
          "pixelFraction": 0.44456374645233154
        ✄ - - - ✄
  "error": null,
  "cropHintsAnnotation": {
    "cropHints": [
        "boundingPoly": {
          "vertices": [
            { "x": 0, "y": 118 },
            { "x": 1177, "y": 118 },
            { "x": 1177, "y": 783 },
            { "x": 0, "y": 783 }
          "normalizedVertices": []
        "confidence": 0.41695669293403625,
        "importanceFraction": 1
  "fullTextAnnotation": null,
  "webDetection": null,
  "productSearchResults": null,
  "context": null

If there's no error returned, we can move on, hence why we have this if block:

if (responses.size() == 0) {
    logger.info("No response received from Vision API.");
    return new ResponseEntity<String>(msg, HttpStatus.BAD_REQUEST);

AnnotateImageResponse response = responses.get(0);
if (response.hasError()) {
    logger.info("Error: " + response.getError().getMessage());
    return new ResponseEntity<String>(msg, HttpStatus.BAD_REQUEST);

We are going to get the labels of the things, categories or themes recognised in the picture:

List<String> labels = response.getLabelAnnotationsList().stream()
    .map(annotation -> annotation.getDescription())
logger.info("Annotations found:");
for (String label: labels) {
    logger.info("- " + label);

We're interested in knowing the dominant color of the picture:

String mainColor = "#FFFFFF";
ImageProperties imgProps = response.getImagePropertiesAnnotation();
if (imgProps.hasDominantColors()) {
    DominantColorsAnnotation colorsAnn = imgProps.getDominantColors();
    ColorInfo colorInfo = colorsAnn.getColors(0);

    mainColor = rgbHex(

    logger.info("Color: " + mainColor);

Let's check if the picture is safe to show:

boolean isSafe = false;
if (response.hasSafeSearchAnnotation()) {
    SafeSearchAnnotation safeSearch = response.getSafeSearchAnnotation();

    isSafe = Stream.of(
        safeSearch.getAdult(), safeSearch.getMedical(), safeSearch.getRacy(),
        safeSearch.getSpoof(), safeSearch.getViolence())
    .allMatch( likelihood -> 
        likelihood != Likelihood.LIKELY && likelihood != Likelihood.VERY_LIKELY

    logger.info("Safe? " + isSafe);

We're checking the adult / spoof / medical / violence / racy characteristics to see if they are not likely or very likely.

If the result of the safe search is okay, we can store metadata in Firestore:

// Saving result to Firestore
if (isSafe) {
    FirestoreOptions firestoreOptions = FirestoreOptions.getDefaultInstance();
    Firestore pictureStore = firestoreOptions.getService();

    DocumentReference doc = pictureStore.collection("pictures").document(fileName);

    Map<String, Object> data = new HashMap<>();
    data.put("labels", labels);
    data.put("color", mainColor);
    data.put("created", new Date());

    ApiFuture<WriteResult> writeResult = doc.set(data, SetOptions.merge());

    logger.info("Picture metadata saved in Firestore at " + writeResult.get().getUpdateTime());

10. Build App Images with GraalVM (optional)

In this optional step, you will build a JIT(JVM) based app image, then a AOT(Native) Java app image, using GraalVM.

To run the build, you will need to ensure that you have an appropriate JDK and the native-image builder installed and configured. There are several options available.

To start, download the GraalVM 22.2.x Community Edition and follow the instructions on the GraalVM installation page.

This process can be greatly simplified with the help of SDKMAN!

To install the appropriate JDK distribution with SDKman, start by using the install command:

sdk install java 22.2.r17-grl

Instruct SDKman to use this version, for both JIT and AOT builds:

sdk use java 22.2.0.r17-grl

Install the native-image utility for GraalVM:

gu install native-image

In Cloudshell, for your convenience, you can install GraalVM and the native-image utility with these simple commands:

# install GraalVM in your home directory
cd ~

# download GraalVM
wget https://github.com/graalvm/graalvm-ce-builds/releases/download/vm-22.2.0/graalvm-ce-java17-linux-amd64-22.2.0.tar.gz
tar -xzvf graalvm-ce-java17-linux-amd64-22.2.0.tar.gz

# configure Java 17 and GraalVM 22.2
echo Existing JVM: $JAVA_HOME
cd graalvm-ce-java17-22.2.0
cd bin
export PATH=$PWD:$PATH

echo PATH: $PATH

# install the native image utility
java -version
gu install native-image

cd ../..

First, set the GCP project environment variables:

export GOOGLE_CLOUD_PROJECT=$(gcloud config get-value project)

You can then go to the directory containing the service to start building the lab:

cd serverless-photosharing-workshop/services/image-analysis/java

Build the JIT(JVM) application image:

./mvnw package -Pjvm

Observe the build log in the terminal:

[INFO] --- spring-boot-maven-plugin:2.7.3:repackage (repackage) @ image-analysis ---
[INFO] Replacing main artifact with repackaged archive
[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  24.009 s
[INFO] Finished at: 2022-09-26T22:17:32-04:00
[INFO] ------------------------------------------------------------------------

Build the AOT(Native) image:.

./mvnw package -Pnative -DskipTests

Observe the build log in the terminal, including the native image build logs:

Note that the build takes quite a bit longer, depending on the machine you are testing on.

[2/7] Performing analysis...  [**********]                                                              (95.4s @ 3.57GB)
  23,346 (94.42%) of 24,725 classes reachable
  44,625 (68.71%) of 64,945 fields reachable
 163,759 (70.79%) of 231,322 methods reachable
     989 classes, 1,402 fields, and 11,032 methods registered for reflection
      63 classes,    69 fields, and    55 methods registered for JNI access
       5 native libraries: -framework CoreServices, -framework Foundation, dl, pthread, z
[3/7] Building universe...                                                                              (10.0s @ 5.35GB)
[4/7] Parsing methods...      [***]                                                                      (9.7s @ 3.13GB)
[5/7] Inlining methods...     [***]                                                                      (4.5s @ 3.29GB)
[6/7] Compiling methods...    [[6/7] Compiling methods...    [********]                                                                (67.6s @ 5.72GB)
[7/7] Creating image...                                                                                  (8.7s @ 4.59GB)
  62.21MB (54.80%) for code area:   100,371 compilation units
  50.98MB (44.91%) for image heap:  465,035 objects and 365 resources
 337.09KB ( 0.29%) for other data
 113.52MB in total
Top 10 packages in code area:                               Top 10 object types in image heap:
   2.36MB com.google.protobuf                                 12.70MB byte[] for code metadata
   1.90MB i.g.xds.shaded.io.envoyproxy.envoy.config.core.v3    6.66MB java.lang.Class
   1.73MB i.g.x.shaded.io.envoyproxy.envoy.config.route.v3     6.47MB byte[] for embedded resources
   1.67MB sun.security.ssl                                     4.61MB byte[] for java.lang.String
   1.54MB com.google.cloud.vision.v1                           4.37MB java.lang.String
   1.46MB com.google.firestore.v1                              3.38MB byte[] for general heap data
   1.37MB io.grpc.xds.shaded.io.envoyproxy.envoy.api.v2.core   1.96MB com.oracle.svm.core.hub.DynamicHubCompanion
   1.32MB i.g.xds.shaded.io.envoyproxy.envoy.api.v2.route      1.80MB byte[] for reflection metadata
   1.09MB java.util                                          911.80KB java.lang.String[]
   1.08MB com.google.re2j                                    826.48KB c.o.svm.core.hub.DynamicHub$ReflectionMetadata
  45.91MB for 772 more packages                                6.45MB for 3913 more object types
                        15.1s (6.8% of total time) in 56 GCs | Peak RSS: 7.72GB | CPU load: 4.37
Produced artifacts:
 /Users/ddobrin/work/dan/serverless-photosharing-workshop/services/image-analysis/java/target/image-analysis (executable)
 /Users/ddobrin/work/dan/serverless-photosharing-workshop/services/image-analysis/java/target/image-analysis.build_artifacts.txt (txt)
Finished generating 'image-analysis' in 3m 41s.
[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  03:56 min
[INFO] Finished at: 2022-09-26T22:22:29-04:00
[INFO] ------------------------------------------------------------------------

11. Build and Publish Container Images

Let's build a container image in two different versions: one as a JIT(JVM) image and the other as an AOT(Native) Java image.

First, set the GCP project environment variables:

export GOOGLE_CLOUD_PROJECT=$(gcloud config get-value project)

Build the JIT(JVM) image:.

./mvnw package -Pjvm-image

Observe the build log in the terminal:

[INFO]     [creator]     Adding layer 'process-types'
[INFO]     [creator]     Adding label 'io.buildpacks.lifecycle.metadata'
[INFO]     [creator]     Adding label 'io.buildpacks.build.metadata'
[INFO]     [creator]     Adding label 'io.buildpacks.project.metadata'
[INFO]     [creator]     Adding label 'org.opencontainers.image.title'
[INFO]     [creator]     Adding label 'org.opencontainers.image.version'
[INFO]     [creator]     Adding label 'org.springframework.boot.version'
[INFO]     [creator]     Setting default process type 'web'
[INFO]     [creator]     Saving docker.io/library/image-analysis-jvm:r17...
[INFO]     [creator]     *** Images (03a44112456e):
[INFO]     [creator]           docker.io/library/image-analysis-jvm:r17
[INFO]     [creator]     Adding cache layer 'paketo-buildpacks/syft:syft'
[INFO]     [creator]     Adding cache layer 'cache.sbom'
[INFO] Successfully built image 'docker.io/library/image-analysis-jvm:r17'
[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  02:11 min
[INFO] Finished at: 2022-09-26T13:09:34-04:00
[INFO] ------------------------------------------------------------------------

Build the AOT(Native) image:.

./mvnw package -Pnative-image

Observe the build log in the terminal, including the native image build logs and image compression using UPX.

Note that the build takes quite a bit longer, depending on the machine you are testing on

[INFO]     [creator]     [2/7] Performing analysis...  [***********]                    (147.6s @ 3.10GB)
[INFO]     [creator]       23,362 (94.34%) of 24,763 classes reachable
[INFO]     [creator]       44,657 (68.67%) of 65,029 fields reachable
[INFO]     [creator]      163,926 (70.76%) of 231,656 methods reachable
[INFO]     [creator]          981 classes, 1,402 fields, and 11,026 methods registered for reflection
[INFO]     [creator]           63 classes,    68 fields, and    55 methods registered for JNI access
[INFO]     [creator]            4 native libraries: dl, pthread, rt, z
[INFO]     [creator]     [3/7] Building universe...                                      (21.1s @ 2.66GB)
[INFO]     [creator]     [4/7] Parsing methods...      [****]                            (13.7s @ 4.16GB)
[INFO]     [creator]     [5/7] Inlining methods...     [***]                              (9.6s @ 4.20GB)
[INFO]     [creator]     [6/7] Compiling methods...    [**********]                     (107.6s @ 3.36GB)
[INFO]     [creator]     [7/7] Creating image...                                         (14.7s @ 4.87GB)
[INFO]     [creator]       62.24MB (51.35%) for code area:   100,499 compilation units
[INFO]     [creator]       51.99MB (42.89%) for image heap:  473,948 objects and 473 resources
[INFO]     [creator]        6.98MB ( 5.76%) for other data
[INFO]     [creator]      121.21MB in total
[INFO]     [creator]     --------------------------------------------------------------------------------
[INFO]     [creator]     Top 10 packages in code area:           Top 10 object types in image heap:
[INFO]     [creator]        2.36MB com.google.protobuf             12.71MB byte[] for code metadata
[INFO]     [creator]        1.90MB i.g.x.s.i.e.e.config.core.v3     7.59MB byte[] for embedded resources
[INFO]     [creator]        1.73MB i.g.x.s.i.e.e.config.route.v3    6.66MB java.lang.Class
[INFO]     [creator]        1.67MB sun.security.ssl                 4.62MB byte[] for java.lang.String
[INFO]     [creator]        1.54MB com.google.cloud.vision.v1       4.39MB java.lang.String
[INFO]     [creator]        1.46MB com.google.firestore.v1          3.66MB byte[] for general heap data
[INFO]     [creator]        1.37MB i.g.x.s.i.e.envoy.api.v2.core    1.96MB c.o.s.c.h.DynamicHubCompanion
[INFO]     [creator]        1.32MB i.g.x.s.i.e.e.api.v2.route       1.80MB byte[] for reflection metadata
[INFO]     [creator]        1.09MB java.util                      910.41KB java.lang.String[]
[INFO]     [creator]        1.08MB com.google.re2j                826.95KB c.o.s.c.h.DynamicHu~onMetadata
[INFO]     [creator]       45.94MB for 776 more packages            6.69MB for 3916 more object types
[INFO]     [creator]     --------------------------------------------------------------------------------
[INFO]     [creator]         20.4s (5.6% of total time) in 81 GCs | Peak RSS: 6.75GB | CPU load: 4.53
[INFO]     [creator]     --------------------------------------------------------------------------------
[INFO]     [creator]     Produced artifacts:
[INFO]     [creator]      /layers/paketo-buildpacks_native-image/native-image/services.ImageAnalysisApplication (executable)
[INFO]     [creator]      /layers/paketo-buildpacks_native-image/native-image/services.ImageAnalysisApplication.build_artifacts.txt (txt)
[INFO]     [creator]     ================================================================================
[INFO]     [creator]     Finished generating '/layers/paketo-buildpacks_native-image/native-image/services.ImageAnalysisApplication' in 5m 59s.
[INFO]     [creator]         Executing upx to compress native image
[INFO]     [creator]                            Ultimate Packer for eXecutables
[INFO]     [creator]                               Copyright (C) 1996 - 2020
[INFO]     [creator]     UPX 3.96        Markus Oberhumer, Laszlo Molnar & John Reiser   Jan 23rd 2020
[INFO]     [creator]     
[INFO]     [creator]             File size         Ratio      Format      Name
[INFO]     [creator]        --------------------   ------   -----------   -----------
 127099880 ->  32416676   25.50%   linux/amd64   services.ImageAnalysisApplication
[INFO]     [creator]     ===> EXPORTING
[INFO]     [creator]     Adding cache layer 'paketo-buildpacks/native-image:native-image'
[INFO]     [creator]     Adding cache layer 'cache.sbom'
[INFO] Successfully built image 'docker.io/library/image-analysis-native:r17'
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  05:28 min
[INFO] Finished at: 2022-09-26T13:19:53-04:00
[INFO] ------------------------------------------------------------------------

Validate that the images have been built:

docker images | grep image-analysis

Tag and push the two images to GCR:

# JIT(JVM) image
docker tag image-analysis-jvm:r17 gcr.io/${GOOGLE_CLOUD_PROJECT}/image-analysis-jvm:r17
docker push gcr.io/${GOOGLE_CLOUD_PROJECT}/image-analysis-jvm:r17

# AOT(Native) image
docker tag image-analysis-native:r17 gcr.io/${GOOGLE_CLOUD_PROJECT}/image-analysis-native:r17
docker push  gcr.io/${GOOGLE_CLOUD_PROJECT}/image-analysis-native:r17

12. Deploy to Cloud Run

Time to deploy the service.

You will deploy service twice, once using the JIT(JVM) image and the second time using the AOT(Native) image. Both service deployments will process the same image from the bucket in parallel, for comparison purposes.

First, set the GCP project environment variables:

export GOOGLE_CLOUD_PROJECT=$(gcloud config get-value project)
gcloud config set project ${GOOGLE_CLOUD_PROJECT}
gcloud config set run/region 
gcloud config set run/platform managed
gcloud config set eventarc/location europe-west1

Deploy the JIT(JVM) image and observe the deployment log in the console:

gcloud run deploy image-analysis-jvm \
     --image gcr.io/${GOOGLE_CLOUD_PROJECT}/image-analysis-jvm:r17 \
     --region europe-west1 \
     --memory 2Gi --allow-unauthenticated

Deploying container to Cloud Run service [image-analysis-jvm] in project [...] region [europe-west1]
✓ Deploying... Done.                                                                                                                                                               
  ✓ Creating Revision...                                                                                                                                                           
  ✓ Routing traffic...                                                                                                                                                             
  ✓ Setting IAM Policy...                                                                                                                                                          
Service [image-analysis-jvm] revision [image-analysis-jvm-00009-huc] has been deployed and is serving 100 percent of traffic.
Service URL: https://image-analysis-jvm-...-ew.a.run.app

Deploy the AOT(Native) image and observe the deployment log in the console:

gcloud run deploy image-analysis-native \
     --image gcr.io/${GOOGLE_CLOUD_PROJECT}/image-analysis-native:r17 \
     --region europe-west1 \
     --memory 2Gi --allow-unauthenticated 
Deploying container to Cloud Run service [image-analysis-native] in project [...] region [europe-west1]
✓ Deploying... Done.                                                                                                                                                               
  ✓ Creating Revision...                                                                                                                                                           
  ✓ Routing traffic...                                                                                                                                                             
  ✓ Setting IAM Policy...                                                                                                                                                          
Service [image-analysis-native] revision [image-analysis-native-00005-ben] has been deployed and is serving 100 percent of traffic.
Service URL: https://image-analysis-native-...-ew.a.run.app

13. Setup Eventarc Triggers

Eventarc offers a standardized solution to manage the flow of state changes, called events, between decoupled microservices. When triggered, Eventarc routes these events through Pub/Sub subscriptions to various destinations (in this document, see Event destinations) while managing delivery, security, authorization, observability, and error-handling for you.

You can create an Eventarc trigger so that your Cloud Run service receives notifications of a specified event or set of events. By specifying filters for the trigger, you can configure the routing of the event, including the event source and the target Cloud Run service.

First, set the GCP project environment variables:

export GOOGLE_CLOUD_PROJECT=$(gcloud config get-value project)
gcloud config set project ${GOOGLE_CLOUD_PROJECT}
gcloud config set run/region 
gcloud config set run/platform managed
gcloud config set eventarc/location europe-west1

Grant pubsub.publisher to the Cloud Storage service account:

SERVICE_ACCOUNT="$(gsutil kms serviceaccount -p ${GOOGLE_CLOUD_PROJECT})"

gcloud projects add-iam-policy-binding ${GOOGLE_CLOUD_PROJECT} \
    --member="serviceAccount:${SERVICE_ACCOUNT}" \

Set up Eventarc triggers for both JVM(JIT) and AOT(Native) service images to process the image:

gcloud eventarc triggers list --location=eu

gcloud eventarc triggers create image-analysis-jvm-trigger \
     --destination-run-service=image-analysis-jvm \
     --destination-run-region=europe-west1 \
     --location=eu \
     --event-filters="type=google.cloud.storage.object.v1.finalized" \
     --event-filters="bucket=uploaded-pictures-${GOOGLE_CLOUD_PROJECT}" \

gcloud eventarc triggers create image-analysis-native-trigger \
     --destination-run-service=image-analysis-native \
     --destination-run-region=europe-west1 \
     --location=eu \
     --event-filters="type=google.cloud.storage.object.v1.finalized" \
     --event-filters="bucket=uploaded-pictures-${GOOGLE_CLOUD_PROJECT}" \

Observe that the two triggers have been created:

gcloud eventarc triggers list --location=eu

14. Test Service Versions

Once the service deployments are successful, you will post a picture to Cloud Storage, see if our services were invoked, what the Vision API returns, and if metadata is stored in Firestore.

Navigate back to Cloud Storage, and click on the bucket we created at the beginning of the lab:


Once in the bucket details page, click on the Upload files button to upload a picture.

For example, a GeekHour.jpeg image is provided with your codebase under /services/image-analysis/java. Select an image and press the Open button:


You can now check the execution of the service, starting with image-analysis-jvm, followed by image-analysis-native.

From the "hamburger" (☰) menu, navigate to the Cloud Run > image-analysis-jvm service.

Click on Logs and observe the output:


And indeed, in the list of logs, I can see that the JIT(JVM) service image-analysis-jvm was invoked.

The logs indicate the start and end of the service execution. And in between, we can see the logs we put in our function with the log statements at INFO level. We see:

  • The details of the event triggering our function,
  • The raw results from the Vision API call,
  • The labels that were found in the picture we uploaded,
  • The dominant colors information,
  • Whether the picture is safe to show,
  • And eventually those metadata about the picture have been stored in Firestore.

You will repeat the process for the image-analysis-native service.

From the "hamburger" (☰) menu, navigate to the Cloud Run > image-analysis-native service.

Click on Logs and observe the output:


You will want to observe now whether the image metadata has been stored in Fiorestore.

Again from the "hamburger" (☰) menu, go to the Firestore section. In the Data subsection (shown by default), you should see the pictures collection with a new document added, corresponding to the picture you just uploaded:


15. Clean up (Optional)

If you don't intend to continue with the other labs in the series, you can clean up resources to save costs and to be an overall good cloud citizen. You can clean up resources individually as follows.

Delete the bucket:

gsutil rb gs://${BUCKET_PICTURES}

Delete the function:

gcloud functions delete picture-uploaded --region europe-west1 -q

Delete the Firestore collection by selecting Delete collection from the collection:


Alternatively, you can delete the whole project:

gcloud projects delete ${GOOGLE_CLOUD_PROJECT} 

16. Congratulations!

Congratulations! You've successfully implemented the first key service of the project!

What we've covered

  • Cloud Storage
  • Cloud Run
  • Cloud Vision API
  • Cloud Firestore
  • Native Java Images

Next Steps