
Before you begin
- Labs create a Google Cloud project and resources for a fixed time
- Labs have a time limit and no pause feature. If you end the lab, you'll have to restart from the beginning.
- On the top left of your screen, click Start lab to begin
In this lab, you develop a backend service for an online Quiz application to process user feedback and save scores.
The Quiz application has two parts, the web application that will run in the first Cloud shell window and the worker application that runs in the second Cloud Shell window.
This process takes advantage of Google Cloud Platform (GCP) products and services:
In this lab, you will learn how to perform the following tasks:
For each lab, you get a new Google Cloud project and set of resources for a fixed time at no cost.
Sign in to Qwiklabs using an incognito window.
Note the lab's access time (for example, 1:15:00
), and make sure you can finish within that time.
There is no pause feature. You can restart if needed, but you have to start at the beginning.
When ready, click Start lab.
Note your lab credentials (Username and Password). You will use them to sign in to the Google Cloud Console.
Click Open Google Console.
Click Use another account and copy/paste credentials for this lab into the prompts.
If you use other credentials, you'll receive errors or incur charges.
Accept the terms and skip the recovery resource page.
Google Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud.
Google Cloud Shell provides command-line access to your Google Cloud resources.
In Cloud console, on the top right toolbar, click the Open Cloud Shell button.
Click Continue.
It takes a few moments to provision and connect to the environment. When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. For example:
gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.
Output:
Example output:
Output:
Example output:
In this section, you access Cloud Shell, clone the git repository containing the Quiz application, configure environment variables, and run the application.
In this section you'll configure dependencies and run the web application.
Navigate to the directory that contains the sample files for this lab:
Update the App Engine region using the sed
command.
Configure the web application:
This script file:
GCLOUD_PROJECT
and GCLOUD_BUCKET.
mvn clean install.
You can run this application when you see output similar to the following:
Run the web application:
The application is running when you see output similar to the following:
Click Open a new tab on the right of the Cloud Shell tab to open a second Cloud Shell window.
Enter the following command to change the working directory:
Prepare the environment in the second Cloud Shell window:
This script file:
GCLOUD_PROJECT
and GCLOUD_BUCKET
.Now start the worker application:
Still in the second Cloud Shell window, click Web preview > Preview on port 8080 to preview the Quiz application.
In the navigation bar, click Take Test.
Click Places.
Answer the question.
After you answer the question, you should see a final screen inviting you to submit feedback.
Quiz takers can select a rating and enter feedback.
Return Cloud Shell. Press Ctrl+C in the first and second windows to stop the web and worker applications.
In this section you examine the file structure and the files that impact the Quiz application.
In this lab you'll view and edit files. You can use the shell editors that are installed on Cloud Shell, such as nano
or vim
, or use the Cloud Shell code editor. This lab uses the Cloud Shell code editor.
Navigate to the /pubsub-languageapi-spanner/start
folder using the file browser panel on the left side of the editor.
Now expand the /src/main/java/com/google/training/appdev
folder. All Java code paths are relative to this folder.
Select the Feedback.java
file in the .../services/gcp/domain
folder.
This file contains a model class that represents the feedback submitted by quiz takers.
PublishService.java
file in the .../services/gcp/pubsub
folder.This file contains a service class that allows applications to publish feedback messages to a Cloud Pub/Sub topic.
LanguageService.java
file in the .../services/gcp/languageapi
folder.This file contains a service class that allows users to send text to the Cloud Natural Language ML API and to receive the sentiment score from the API.
SpannerService.java
file in the .../services/gcp/spanner
folder.This file contains a service class that allows users to save the feedback and Natural Language API response data in a Cloud Spanner database instance.
QuizEndpoint.java
file in the .../api
folder.The handler for POST messages sent to the /api/quizzes/feedback/:quiz
route publishes the feedback data received from the client to Pub/Sub.
ConsoleApp.java
file in the .../backend
folder.This file runs as a separate console application to consume the messages delivered to a Pub/Sub subscription.
The Quiz application uses a Pub/Sub function to retrieve answers and feedback that a user inputs through the quiz interface.
In this section, you create a Cloud Pub/Sub topic and subscription in your GCP project, then publish and retrieve a message.
In the Console, open the Navigation menu > View All Products. In the Analytics section, click Pub/Sub > Topics, and then click Create topic.
Set the Topic ID to feedback
, and then click Create.
The Topic details view opens:
Return to the second Cloud Shell window.
Enter the following command to create a Cloud Pub/Sub subscription named cloud-shell-subscription
against the feedback
topic:
"Hello World"
message into the feedback
topic in the second Cloud Shell window:
feedback
topic with automatic acknowledgement of the message in the second Cloud Shell window:Output:
In this section, you write code to publish messages to Cloud Pub/Sub.
// TODO
// END TODO
Open the .../services/gcp/pubsub/PublishService.java
file in the code editor.
Update the file by adding code as directed.
Declare two static final strings for the PROJECT_ID
and TOPIC_NAME
:
Move to the publishFeedback(...)
methodand create a TopicName
object using the PROJECT_ID
and TOPIC_NAME
strings.
The topic name references the Cloud Pub/Sub topic you just created:
Declare a Publisher
object and set it to null
:
It will be initialized in the try block that follows.
Move to the try block, and initialize the publisher object using its builder:
Copy the JSON serialized feedbackMessage
string to a ByteString
:
Declare a PubsubMessage
object; initialize the message using its builder:
Use the publisher to publish the message, assign the return value to the message ID future object:
Move to the finally block and retrieve the Pub/Sub messageId from the message ID future object:
Complete the publishing code by shutting down the publisher:
Save services/gcp/pubsub/PublishService.java
.
In the .../api/QuizEndpoint.java
file, declare a new PublishService
field named publishService
.
Apply the Spring @Autowired
annotation:
In the processFeedback(...)
method that handles POST requests to the '/feedback/:quiz'
route, invoke the publishService.publishFeedback(feedback)
method:
Save /api/QuizEndpoint.java
.
In the first Cloud Shell window, restart the web application (if it is running, stop and start it):
Preview the web application, click Take Test > Places.
Answer the question, select the rating, enter some feedback text, and click Send Feedback.
In the second Cloud Shell window, to pull a message from the cloud-shell-subscription
:
In this section you write the code to create a subscription and receive message notifications from a Cloud Pub/Sub topic to the worker application.
In the code editor open the ...backend/ConsoleApp.java
file.
Update the file by adding code as directed.
Skip over the TODO blocks for languageService
and spannerService
. You'll return for those later.
In the main()
method, create a SubscriptionName
object representing a new subscription named "worker1-subscription"
:
Create a SubscriptionAdminClient
object using a try block:
Move to the code that creates a MessageReceiver
, and in the receiveMessage(...)
override, extract the message data into a String:
Use the consumer to acknowledge the message:
After the code that initializes an ObjectMapper, deserialize the JSON String message data into a feedback object:
After the block that creates the MessageReceiver
, declare a Subscriber
and initialize it to null.
Move to the try block, and initialize the Subscriber
using its default builder. This requires the subscription and receiver:
Add a listener to the subscriber to display errors:
Start the subscriber:
Move to the final block. Write the code to stop the subscriber, and delete the subscription:
Save backend/ConsoleApp.java
.
In the first Cloud Shell window, stop and start the web application:
In the second Cloud Shell window, start the worker application:
In Cloud Shell, click Web preview > Preview on port 8080 to preview the quiz application.
Click Take Test.
Click Places.
Answer the question, select the rating, enter some feedback text, and then click Send Feedback.
Return to the second Cloud Shell window.
You should see that the worker application has received the feedback message via its handler and displayed it in the second Cloud Shell window. An example of a feedback message is as follows:
In this section you write the code to perform sentiment analysis on the feedback text submitted by the user. For more information refer to Google Cloud Natural Language API.
Return to the editor and open the LanguageService.java
file in the services/gcp/languageapi
folder.
Move to the analyzeSentiment(...)
method, and create a LanguageServiceClient
object in a try block.
// END TODO
in the content that you copy into the file:Create a new Document
object using its builder, and configure this object with the document content and type:
Use the Natural Language client object to analyze the sentiment of the document, assigning the result to a Sentiment
object:
Then, return the sentiment score from the sentiment object:
Don't forget the closing brace.
Save the file.
Return to the backend/ConsoleApp.java
file.
Move to the main(...)
method.
In the main()
method, create a SubscriptionName
object representing a new subscription named "worker2-subscription"
.
"worker1-subscription"
.At the point indicated by the comments, create the LanguageService
instance using its static create()
method:
At the point indicated by the comments, use the languageService
object to perform sentiment detection on the feedback:
Then, log the score to the console and assign a new score property to the feedback object:
Save the file.
Return to the first Cloud Shell window and restart the web application.
Switch to the second Cloud Shell window and restart the worker application.
Preview the web application, then click Take Test > Places.
Answer the questions, select the rating, enter some feedback text, and then click Send Feedback.
Return to the second Cloud Shell window.
The output shows the worker application invoked the Cloud Natural Language API and displays the sentiment score in the console next to Score is:.
For example:
Stop the web and worker applications.
In this section you create a Cloud Spanner instance, database, and table. You then write the code to persist the feedback data into the database.
On the Instance details page for quiz-instance, click CREATE DATABASE.
For Database name, type quiz-database.
Under Define your schema in the text box, type the following SQL statement:
Click Create.
Return to the code editor, and move to the insertFeedback(...)
method in the ...services/gcp/spanner/SpannerService.java file.
Get a reference to Cloud Spanner:
Get a reference to the Spanner database via the Database Id:
Get a reference to the Cloud Spanner Database client:
Create a new List<Mutation>
to reference all the changes that will be made to the database:
Add the Mutation
that represents an insert against the feedback table, using data from the feedback object:
Use the database client to write the mutations:
Save the file.
Move to the main(...)
method in the backend/ConsoleApp.java
file.
In the main()
method, create a SubscriptionName
object representing a new subscription named "worker3-subscription"
.
"worker2-subscription"
:At the point indicated by the comments, create the SpannerService
instance:
At the point indicated by the comments, use the spannerService
object to insert the feedback into the database and print out a message to the console:
Save the file.
Return to the first Cloud Shell window, start the web application.
Switch to the second Cloud Shell window, restart the worker application.
Preview the Quiz application, click Take Test > Places.
Answer the questions, select the rating, enter some feedback text, and then click Send Feedback.
Return to the second Cloud Shell window.
You should see that the worker application has invoked the Cloud Spanner API and displayed the message in the console window.
Return to the Console. Click Navigation menu > Spanner.
Select quiz-instance > quiz-database and click Spanner Studio from the left pane .
To execute a query, in the Query dialog, type SELECT * FROM Feedback
, and then click Run:
You should see the new feedback record in the Cloud Spanner database, including the message data from Cloud Pub/Sub and the Quiz score from the Cloud Natural Language API.
When you have completed your lab, click End Lab. Google Cloud Skills Boost removes the resources you’ve used and cleans the account for you.
You will be given an opportunity to rate the lab experience. Select the applicable number of stars, type a comment, and then click Submit.
The number of stars indicates the following:
You can close the dialog box if you don't want to provide feedback.
For feedback, suggestions, or corrections, please use the Support tab.
Copyright 2022 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.
This content is not currently available
We will notify you via email when it becomes available
Great!
We will contact you via email if it becomes available
One lab at a time
Confirm to end all existing labs and start this one