From d7ad1fb40fbd622e14dd2e5b9c4cc7c3356e8b32 Mon Sep 17 00:00:00 2001 From: Kurtis Van Gent Date: Tue, 21 Nov 2017 14:29:14 -0800 Subject: [PATCH 1/3] Added Cloud Tasks snippets for Pull Queues. --- cloud-tasks/README.md | 64 ++++++ cloud-tasks/pom.xml | 89 ++++++++ .../com.example.cloudtasks/PullQueue.java | 209 ++++++++++++++++++ .../com/example/cloudtasks/PullQueueIT.java | 97 ++++++++ 4 files changed, 459 insertions(+) create mode 100644 cloud-tasks/README.md create mode 100644 cloud-tasks/pom.xml create mode 100644 cloud-tasks/src/main/java/com.example.cloudtasks/PullQueue.java create mode 100644 cloud-tasks/src/test/java/com/example/cloudtasks/PullQueueIT.java diff --git a/cloud-tasks/README.md b/cloud-tasks/README.md new file mode 100644 index 00000000000..95b3f4064e2 --- /dev/null +++ b/cloud-tasks/README.md @@ -0,0 +1,64 @@ +# Google Cloud Tasks Pull Queue Samples + +Sample command-line program for interacting with the Google Cloud Tasks +API using pull queues. + +Pull queues let you add tasks to a queue, then programatically remove +and interact with them. Tasks can be added or processed in any +environment, such as on Google App Engine or Google Compute Engine. + +`PullQueue.java` is a simple command-line program to demonstrate listing +queues, creating tasks, and pulling and acknowledging tasks. + +## Initial Setup + + * Set up a Google Cloud Project and enable billing. + * Enable the + [Cloud Tasks API](https://console.cloud.google.com/launcher/details/google/cloudtasks.googleapis.com). + * Download and install the [Cloud SDK](https://cloud.google.com/sdk). + * Download and install [Maven](http://maven.apache.org/install.html). + + +## Authentication + +To authenticate locally, download the + +and run the following command + +## Creating a queue + +To create a queue using the Cloud SDK, use the following gcloud command: + +```bash +gcloud alpha tasks queues create-pull-queue my-pull-queue +``` + +In this example, the queue will be named `my-pull-queue`. + +## Running the Samples + +First, build your project with: +``` +mvn clean package +``` + +Optionally, you can set up your settings as environment variables: +``` +export PROJECT_ID= +export QUEUE_ID= +export LOCATION_ID= +``` + +Next, create a task for a queue: +``` +java -cp target/cloudtasks-1.0.0-jar-with-dependencies.jar \ + com.example.PullQueue create-task --project=$PROJECT_ID --queue=$QUEUE_ID --location=$LOCATION_ID +``` +Finally, pull and acknowledge a task: + +``` +java -cp target/cloudtasks-1.0.0-jar-with-dependencies.jar \ + com.example.PullQueue pull-and-ack-task --project=$PROJECT_ID --queue=$QUEUE_ID --location=$LOCATION_ID +``` +Note that usually, there would be a processing step in between pulling a task and acknowledging it. + diff --git a/cloud-tasks/pom.xml b/cloud-tasks/pom.xml new file mode 100644 index 00000000000..595bc5c630c --- /dev/null +++ b/cloud-tasks/pom.xml @@ -0,0 +1,89 @@ + + + + 4.0.0 + com.example + cloud-tasks + 1.0 + + + doc-samples + com.google.cloud + 1.0.0 + .. + + + + + com.google.apis + google-api-services-cloudtasks + v2beta2-rev16-1.23.0 + + + com.google.api-client + google-api-client + 1.23.0 + + + com.google.http-client + google-http-client-jackson2 + 1.23.0 + + + + + net.sourceforge.argparse4j + argparse4j + 0.8.1 + + + + junit + junit + 4.12 + test + + + com.google.truth + truth + 0.36 + test + + + + + + src/main/java + + + org.apache.maven.plugins + maven-compiler-plugin + 3.2 + + + maven-assembly-plugin + + + jar-with-dependencies + + + + + + + + \ No newline at end of file diff --git a/cloud-tasks/src/main/java/com.example.cloudtasks/PullQueue.java b/cloud-tasks/src/main/java/com.example.cloudtasks/PullQueue.java new file mode 100644 index 00000000000..d14d8cbce2f --- /dev/null +++ b/cloud-tasks/src/main/java/com.example.cloudtasks/PullQueue.java @@ -0,0 +1,209 @@ +/** + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.cloudtasks; + +import com.google.api.services.cloudtasks.v2beta2.CloudTasks; +import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; +import com.google.api.client.http.HttpTransport; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.JsonFactory; +import com.google.api.client.json.jackson2.JacksonFactory; +import com.google.api.services.cloudtasks.v2beta2.CloudTasksScopes; +import com.google.api.services.cloudtasks.v2beta2.model.AcknowledgeTaskRequest; +import com.google.api.services.cloudtasks.v2beta2.model.CreateTaskRequest; +import com.google.api.services.cloudtasks.v2beta2.model.PullTaskTarget; +import com.google.api.services.cloudtasks.v2beta2.model.PullTasksRequest; +import com.google.api.services.cloudtasks.v2beta2.model.PullTasksResponse; +import com.google.api.services.cloudtasks.v2beta2.model.Task; +import com.google.common.io.BaseEncoding; +import java.io.IOException; +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.Namespace; +import net.sourceforge.argparse4j.inf.Subparsers; + + +public class PullQueue { + + /** + * Creates an authorized CloudTasks client service using Application Default Credentials. + * + * @return an authorized CloudTasks client + * @throws IOException if there's an error getting the default credentials. + */ + private static CloudTasks createAuthorizedClient() throws IOException { + // Create the credential + HttpTransport transport = new NetHttpTransport(); + JsonFactory jsonFactory = new JacksonFactory(); + // Authorize the client using Application Default Credentials + // @see https://g.co/dv/identity/protocols/application-default-credentials + GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory); + + // Depending on the environment that provides the default credentials (e.g. Compute Engine, App + // Engine), the credentials may require us to specify the scopes we need explicitly. + // Check for this case, and inject the scope if required. + if (credential.createScopedRequired()) { + credential = credential.createScoped(CloudTasksScopes.all()); + } + + return new CloudTasks.Builder(transport, jsonFactory, credential) + .setApplicationName("Cloud Tasks Snippets") + .build(); + } + + /** + * Create a task for a given queue with a given payload. + */ + private static Task createTask( + String project, String location, String queue) throws IOException { + // The name of the queue to use + String queueName = String.format( + "projects/%s/locations/%s/queues/%s", project, location, queue); + + // Create the Cloud Tasks Client + CloudTasks client = createAuthorizedClient(); + + // Create the Task to put in the Queue + String message = "a message for the recipient"; + String payload = BaseEncoding.base64().encode(message.getBytes()); + Task task = new Task().setPullTaskTarget(new PullTaskTarget().setPayload(payload)); + + // Create the CreateTaskRequest + CreateTaskRequest request = new CreateTaskRequest().setTask(task); + + //Execute the request and return the created Task + Task result = client + .projects() + .locations() + .queues() + .tasks() + .create(queueName, request) + .execute(); + System.out.println(String.format("Created task %s",task.getName())); + return result; + } + + /** + * Pull a single task from a given queue and lease it for 10 minutes. + */ + private static Task pullTask( + String project, String location, String queue) throws IOException { + // The name of the queue to use + String queueName = String.format( + "projects/%s/locations/%s/queues/%s", project, location, queue); + + // Create the Cloud Tasks Client + CloudTasks client = createAuthorizedClient(); + + // Create the PullTasksRequest + PullTasksRequest request = new PullTasksRequest().setMaxTasks(1).setLeaseDuration("600s"); + + //Execute the request and return the pulled task + PullTasksResponse response = client + .projects() + .locations() + .queues() + .tasks() + .pull(queueName, request) + .execute(); + return response.getTasks().get(0); + } + + /** + * Acknowledge a given task, which removes it from the queue. + */ + private static void acknowledgeTask(Task task) throws IOException{ + // Create the Cloud Tasks Client + CloudTasks client = createAuthorizedClient(); + + // Create the AcknowledgeTaskRequest + AcknowledgeTaskRequest request = new AcknowledgeTaskRequest() + .setScheduleTime(task.getScheduleTime()); + + //Execute the request + client + .projects() + .locations() + .queues() + .tasks() + .acknowledge(task.getName(), request) + .execute(); + System.out.println(String.format("Acknowledged task %s", task.getName())); + } + + public static void main(String[] args) throws Exception { + ArgumentParser parser = ArgumentParsers.newFor("PullQueue").build() + .defaultHelp(true) + .description("Sample command-line program for interacting with the Cloud Tasks API.\n\n" + + "See README.md for instructions on setting up your development environment " + + "and running the scripts."); + + Subparsers subparsers = parser.addSubparsers().dest("command"); + + // Create the parser for the command 'create-task' + ArgumentParser createTaskParser = subparsers + .addParser("create-task") + .help("Acknowledge a given task, which removes it from the queue."); + createTaskParser + .addArgument("--project") + .help("Project of the queue to add the task to.") + .required(true); + createTaskParser + .addArgument("--location") + .help("Location of the queue to add the task to.") + .required(true); + createTaskParser + .addArgument("--queue") + .help("ID (short name) of the queue to add the task to.") + .required(true); + + // Create the parser for the command 'pull-and-ack-task' + ArgumentParser pullAndAckParser = subparsers + .addParser("pull-and-ack-task") + .help("Create a task for a given queue with an arbitrary payload."); + pullAndAckParser + .addArgument("--project") + .help("Project of the queue to add the task to.") + .required(true); + pullAndAckParser + .addArgument("--location") + .help("Location of the queue to add the task to.") + .required(true); + pullAndAckParser + .addArgument("--queue") + .help("ID (short name) of the queue to add the task to.") + .required(true); + + // Parse commands + Namespace cmd = parser.parseArgs(args); + + String command = cmd.get("command"); + String project = cmd.get("project"); + String queue = cmd.get("queue"); + String location = cmd.get("location"); + + // Execute commands + if(command.equals("create-task")){ + createTask(project, location, queue); + } + if(command.equals("pull-and-ask-task")){ + Task task = pullTask(project, location, queue); + acknowledgeTask(task); + } + } + +} \ No newline at end of file diff --git a/cloud-tasks/src/test/java/com/example/cloudtasks/PullQueueIT.java b/cloud-tasks/src/test/java/com/example/cloudtasks/PullQueueIT.java new file mode 100644 index 00000000000..996f4f91573 --- /dev/null +++ b/cloud-tasks/src/test/java/com/example/cloudtasks/PullQueueIT.java @@ -0,0 +1,97 @@ +/** + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.cloudtasks; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * Integration (system) tests for {@link PullQueue}. + */ +@RunWith(JUnit4.class) +public class PullQueueIT { + private ByteArrayOutputStream bout; + private PrintStream out; + + static final private String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + static final private String LOCATION_ID = "us-central1"; + static final private String QUEUE_ID = "test-queue"; + + /** + * Capture standard out for each test. + */ + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + + assertNotNull(System.getenv("GOOGLE_CLOUD_PROJECT")); + } + + /** + * Reset standard out after each test. + */ + @After + public void tearDown() { + System.setOut(null); + bout.reset(); + } + + @Test + public void testRunner() throws Exception { + // Used to guarantee a specific test order. + testCreateTask(); + testPullAndAckTask(); + } + + /** + * Tests the the 'create-task' command. + */ + private void testCreateTask() throws Exception { + PullQueue.main(new String[] { + "create-task", + "--project", PROJECT_ID, + "--location", LOCATION_ID, + "--queue", QUEUE_ID + }); + String output = bout.toString(); + assertTrue(output.contains("Created task")); + } + + /** + * Tests the the 'pull-and-ack-task' command. + */ + private void testPullAndAckTask() throws Exception { + PullQueue.main(new String[] { + "pull-and-ack-task", + "--project", PROJECT_ID, + "--location", LOCATION_ID, + "--queue", QUEUE_ID + }); + String output = bout.toString(); + assertTrue(output.contains("Created task")); + } + +} From 597cf1f43a2d5c099ab3bc7d0f47e78b4cfe2ea8 Mon Sep 17 00:00:00 2001 From: Kurtis Van Gent Date: Mon, 27 Nov 2017 14:47:16 -0800 Subject: [PATCH 2/3] Added AppEngine Flexible App for Cloud Tasks API. --- cloud-tasks/README.md | 20 ++- cloud-tasks/pom.xml | 4 +- .../com.example.cloudtasks/PullQueue.java | 4 +- .../com/example/cloudtasks/PullQueueIT.java | 4 +- flexible/cloud-tasks/README.md | 75 +++++++++++ flexible/cloud-tasks/pom.xml | 85 +++++++++++++ .../cloud-tasks/src/main/appengine/app.yaml | 21 +++ .../example/cloudtasks/CreateTaskServlet.java | 120 ++++++++++++++++++ .../com/example/cloudtasks/HelloServlet.java | 38 ++++++ .../example/cloudtasks/LogPayloadServlet.java | 46 +++++++ flexible/pom.xml | 1 + 11 files changed, 401 insertions(+), 17 deletions(-) create mode 100644 flexible/cloud-tasks/README.md create mode 100644 flexible/cloud-tasks/pom.xml create mode 100644 flexible/cloud-tasks/src/main/appengine/app.yaml create mode 100644 flexible/cloud-tasks/src/main/java/com/example/cloudtasks/CreateTaskServlet.java create mode 100644 flexible/cloud-tasks/src/main/java/com/example/cloudtasks/HelloServlet.java create mode 100644 flexible/cloud-tasks/src/main/java/com/example/cloudtasks/LogPayloadServlet.java diff --git a/cloud-tasks/README.md b/cloud-tasks/README.md index 95b3f4064e2..e1ccbdb6b9b 100644 --- a/cloud-tasks/README.md +++ b/cloud-tasks/README.md @@ -19,12 +19,6 @@ queues, creating tasks, and pulling and acknowledging tasks. * Download and install [Maven](http://maven.apache.org/install.html). -## Authentication - -To authenticate locally, download the - -and run the following command - ## Creating a queue To create a queue using the Cloud SDK, use the following gcloud command: @@ -37,28 +31,32 @@ In this example, the queue will be named `my-pull-queue`. ## Running the Samples -First, build your project with: +From the project folder, build your project with: + ``` -mvn clean package +mvn clean assembly:single ``` Optionally, you can set up your settings as environment variables: + ``` export PROJECT_ID= -export QUEUE_ID= export LOCATION_ID= +export QUEUE_ID= ``` Next, create a task for a queue: + ``` java -cp target/cloudtasks-1.0.0-jar-with-dependencies.jar \ - com.example.PullQueue create-task --project=$PROJECT_ID --queue=$QUEUE_ID --location=$LOCATION_ID + com.example.PullQueue create-task --project=$PROJECT_ID --location=$LOCATION_ID --queue=$QUEUE_ID ``` + Finally, pull and acknowledge a task: ``` java -cp target/cloudtasks-1.0.0-jar-with-dependencies.jar \ - com.example.PullQueue pull-and-ack-task --project=$PROJECT_ID --queue=$QUEUE_ID --location=$LOCATION_ID + com.example.PullQueue pull-and-ack-task --project=$PROJECT_ID --location=$LOCATION_ID --queue=$QUEUE_ID ``` Note that usually, there would be a processing step in between pulling a task and acknowledging it. diff --git a/cloud-tasks/pom.xml b/cloud-tasks/pom.xml index 595bc5c630c..ab4447ca650 100644 --- a/cloud-tasks/pom.xml +++ b/cloud-tasks/pom.xml @@ -17,8 +17,8 @@ 4.0.0 com.example - cloud-tasks - 1.0 + cloudtasks + 1.0.0 doc-samples diff --git a/cloud-tasks/src/main/java/com.example.cloudtasks/PullQueue.java b/cloud-tasks/src/main/java/com.example.cloudtasks/PullQueue.java index d14d8cbce2f..52295cb7b69 100644 --- a/cloud-tasks/src/main/java/com.example.cloudtasks/PullQueue.java +++ b/cloud-tasks/src/main/java/com.example.cloudtasks/PullQueue.java @@ -25,7 +25,7 @@ import com.google.api.services.cloudtasks.v2beta2.CloudTasksScopes; import com.google.api.services.cloudtasks.v2beta2.model.AcknowledgeTaskRequest; import com.google.api.services.cloudtasks.v2beta2.model.CreateTaskRequest; -import com.google.api.services.cloudtasks.v2beta2.model.PullTaskTarget; +import com.google.api.services.cloudtasks.v2beta2.model.PullMessage; import com.google.api.services.cloudtasks.v2beta2.model.PullTasksRequest; import com.google.api.services.cloudtasks.v2beta2.model.PullTasksResponse; import com.google.api.services.cloudtasks.v2beta2.model.Task; @@ -80,7 +80,7 @@ private static Task createTask( // Create the Task to put in the Queue String message = "a message for the recipient"; String payload = BaseEncoding.base64().encode(message.getBytes()); - Task task = new Task().setPullTaskTarget(new PullTaskTarget().setPayload(payload)); + Task task = new Task().setPullMessage(new PullMessage().setPayload(payload)); // Create the CreateTaskRequest CreateTaskRequest request = new CreateTaskRequest().setTask(task); diff --git a/cloud-tasks/src/test/java/com/example/cloudtasks/PullQueueIT.java b/cloud-tasks/src/test/java/com/example/cloudtasks/PullQueueIT.java index 996f4f91573..16e0246ea49 100644 --- a/cloud-tasks/src/test/java/com/example/cloudtasks/PullQueueIT.java +++ b/cloud-tasks/src/test/java/com/example/cloudtasks/PullQueueIT.java @@ -34,7 +34,7 @@ public class PullQueueIT { private ByteArrayOutputStream bout; private PrintStream out; - static final private String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + static final private String PROJECT_ID = "java-docs-samples-cloud-tasks"; static final private String LOCATION_ID = "us-central1"; static final private String QUEUE_ID = "test-queue"; @@ -47,7 +47,7 @@ public void setUp() { out = new PrintStream(bout); System.setOut(out); - assertNotNull(System.getenv("GOOGLE_CLOUD_PROJECT")); + assertNotNull(PROJECT_ID); } /** diff --git a/flexible/cloud-tasks/README.md b/flexible/cloud-tasks/README.md new file mode 100644 index 00000000000..1d77cd72c1a --- /dev/null +++ b/flexible/cloud-tasks/README.md @@ -0,0 +1,75 @@ +# Google Cloud Tasks App Engine Queue Samples + +This is a sample AppEngine app demonstrating use of the Cloud Tasks API +using App Engine Queues. + +App Engine queues push tasks to an App Engine HTTP target. This +application can both create and receive Cloud Tasks. + +## Initial Setup + + * Set up a Google Cloud Project and enable billing. + * Enable the + [Cloud Tasks API](https://console.cloud.google.com/launcher/details/google/cloudtasks.googleapis.com). + * Download and install the [Cloud SDK](https://cloud.google.com/sdk). + * Download and install [Maven](http://maven.apache.org/install.html). + * Add an [AppEngine](https://pantheon.corp.google.com/appengine) App to the project + +## Creating a queue + +To create a queue using the Cloud SDK, use the following gcloud command: + +```bash +gcloud alpha tasks queues create-appengine-queue my-appengine-queue +``` + +In this example, the queue will be named `my-appengine-queue`. + +### Deploy Sample + +To deploy this sample to your AppEngine Project, use the following +command: + +```bash +gcloud config set project $YOUR_PROJECT_ID +mvn appengine:deploy +``` + +You can open a browser to your your application with: + +```bash +gcloud app browse +``` + +You can also stream the logs for the application with: + +```bash +gcloud app logs tail -s default +``` + +## Cloud Tasks in Action + +You can create a Cloud Task by sending a POST request to the +application. + +Optionally, you can set up your settings as environment variables: +``` +export PROJECT_ID= +export LOCATION_ID= +export QUEUE_ID= +``` + +Next, you can send a POST request to trigger the /create_task endpoint: +```bash +curl -d "project=$PROJECT_ID" \ + -d "location=$LOCATION_ID" \ + -d "queue=$QUEUE_ID" \ + -d "message=Hello World!" \ + --request POST https://.appspot.com/ +``` + +This endpoint will create a Cloud Tasks to trigger the `/log_payload` +endpoint, which will be visible the application's logs: +``` +Received task with payload: Hello World! +``` \ No newline at end of file diff --git a/flexible/cloud-tasks/pom.xml b/flexible/cloud-tasks/pom.xml new file mode 100644 index 00000000000..941d4de6c56 --- /dev/null +++ b/flexible/cloud-tasks/pom.xml @@ -0,0 +1,85 @@ + + + + 4.0.0 + war + 1.0-SNAPSHOT + com.example.cloudtasks + cloudtasks + + + appengine-flexible + com.google.cloud + 1.0.0 + .. + + + + 1.8 + 1.8 + + false + + 1.3.2 + 9.4.4.v20170414 + + + + + + com.google.apis + google-api-services-cloudtasks + v2beta2-rev16-1.23.0 + + + com.google.appengine + appengine-api-1.0-sdk + 1.9.59 + + + javax.servlet + javax.servlet-api + 3.1.0 + jar + provided + + + + + + ${project.build.directory}/${project.build.finalName}/WEB-INF/classes + + + + com.google.cloud.tools + appengine-maven-plugin + ${appengine.maven.plugin} + + + + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty} + + + + + + diff --git a/flexible/cloud-tasks/src/main/appengine/app.yaml b/flexible/cloud-tasks/src/main/appengine/app.yaml new file mode 100644 index 00000000000..13e75b3fa51 --- /dev/null +++ b/flexible/cloud-tasks/src/main/appengine/app.yaml @@ -0,0 +1,21 @@ +# Copyright 2016 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# [START appyaml] +runtime: java +env: flex + +handlers: +- url: /.* + script: this field is required, but ignored +# [END appyaml] diff --git a/flexible/cloud-tasks/src/main/java/com/example/cloudtasks/CreateTaskServlet.java b/flexible/cloud-tasks/src/main/java/com/example/cloudtasks/CreateTaskServlet.java new file mode 100644 index 00000000000..a14fceb863e --- /dev/null +++ b/flexible/cloud-tasks/src/main/java/com/example/cloudtasks/CreateTaskServlet.java @@ -0,0 +1,120 @@ +/** + * Copyright 2015 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.cloudtasks; + +import com.google.api.services.cloudtasks.v2beta2.CloudTasksScopes; +import com.google.api.services.cloudtasks.v2beta2.model.AppEngineHttpRequest; +import com.google.api.services.cloudtasks.v2beta2.model.CreateTaskRequest; +import com.google.api.services.cloudtasks.v2beta2.model.Task; +import com.google.appengine.api.utils.SystemProperty; +import com.google.common.io.BaseEncoding; +import java.io.IOException; +import java.io.PrintWriter; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import com.google.api.services.cloudtasks.v2beta2.CloudTasks; +import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; +import com.google.api.client.http.HttpTransport; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.JsonFactory; +import com.google.api.client.json.jackson2.JacksonFactory; + + +@WebServlet(value = "/create_task") +@SuppressWarnings("serial") +public class CreateTaskServlet extends HttpServlet { + + @Override + public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { + + String message = req.getParameter("message"); + if(message == null) message = "Hello World!"; + + String project = req.getParameter("project"); + String location = req.getParameter("location"); + String queue_id = req.getParameter("queue"); + + createTask(project, location, queue_id, message); + + PrintWriter out = resp.getWriter(); + out.println(String.format("Created a task with the following message: %s", message)); + } + + /** + * Creates an authorized CloudTasks client service using Application Default Credentials. + * + * @return an authorized CloudTasks client + * @throws IOException if there's an error getting the default credentials. + */ + private static CloudTasks createAuthorizedClient() throws IOException { + // Create the credential + HttpTransport transport = new NetHttpTransport(); + JsonFactory jsonFactory = new JacksonFactory(); + // Authorize the client using Application Default Credentials + // @see https://g.co/dv/identity/protocols/application-default-credentials + GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory); + + // Depending on the environment that provides the default credentials (e.g. Compute Engine, App + // Engine), the credentials may require us to specify the scopes we need explicitly. + // Check for this case, and inject the scope if required. + if (credential.createScopedRequired()) { + credential = credential.createScoped(CloudTasksScopes.all()); + } + + return new CloudTasks.Builder(transport, jsonFactory, credential) + .setApplicationName("Cloud Tasks Snippets") + .build(); + } + + /** + * Create a task for a given queue with a given payload. + */ + private static Task createTask( + String project, String location, String queue, String payload) throws IOException { + // The name of the queue to use + String queueName = String.format( + "projects/%s/locations/%s/queues/%s", project, location, queue); + + // Create the Cloud Tasks Client + CloudTasks client = createAuthorizedClient(); + + // Create the Task to put in the Queue + payload = BaseEncoding.base64().encode(payload.getBytes()); + AppEngineHttpRequest postRequest = new AppEngineHttpRequest() + .setHttpMethod("POST") + .setRelativeUrl("/log_payload") + .setPayload(payload); + Task task = new Task().setAppEngineHttpRequest(postRequest); + + // Create the CreateTaskRequest + CreateTaskRequest request = new CreateTaskRequest().setTask(task); + + //Execute the request and return the created Task + Task result = client + .projects() + .locations() + .queues() + .tasks() + .create(queueName, request) + .execute(); + System.out.println(String.format("Created task %s", task.getName())); + return result; + } + +} diff --git a/flexible/cloud-tasks/src/main/java/com/example/cloudtasks/HelloServlet.java b/flexible/cloud-tasks/src/main/java/com/example/cloudtasks/HelloServlet.java new file mode 100644 index 00000000000..7f9cf306eb8 --- /dev/null +++ b/flexible/cloud-tasks/src/main/java/com/example/cloudtasks/HelloServlet.java @@ -0,0 +1,38 @@ +/** + * Copyright 2015 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.cloudtasks; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + + +@WebServlet(value = "") +@SuppressWarnings("serial") +public class HelloServlet extends HttpServlet { + + @Override + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + PrintWriter out = resp.getWriter(); + out.println("Hello, world - App Engine Flexible with Cloud Tasks"); + } + +} diff --git a/flexible/cloud-tasks/src/main/java/com/example/cloudtasks/LogPayloadServlet.java b/flexible/cloud-tasks/src/main/java/com/example/cloudtasks/LogPayloadServlet.java new file mode 100644 index 00000000000..bcdf7eeaff2 --- /dev/null +++ b/flexible/cloud-tasks/src/main/java/com/example/cloudtasks/LogPayloadServlet.java @@ -0,0 +1,46 @@ +/** + * Copyright 2015 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.cloudtasks; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + + +@WebServlet(value = "/log_payload") +@SuppressWarnings("serial") +public class LogPayloadServlet extends HttpServlet { + + @Override + public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { + BufferedReader br = req.getReader(); + StringBuffer dataBuffer = new StringBuffer(); + while(br.ready()) dataBuffer.append(br.readLine()); + String data = dataBuffer.toString(); + + System.out.println(String.format("Received task with payload: %s", data)); + + PrintWriter out = resp.getWriter(); + out.println(String.format("Received task with payload: %s", data)); + } + +} diff --git a/flexible/pom.xml b/flexible/pom.xml index 4777e659429..b20fc12bf72 100644 --- a/flexible/pom.xml +++ b/flexible/pom.xml @@ -33,6 +33,7 @@ analytics async-rest + cloud-tasks cloudsql cloudstorage cron From a005df5485615c24569a0005535340fcd6ccb44b Mon Sep 17 00:00:00 2001 From: Kurtis Van Gent Date: Tue, 28 Nov 2017 07:56:31 -0800 Subject: [PATCH 3/3] Minor text fixes. --- flexible/cloud-tasks/README.md | 2 +- flexible/cloud-tasks/pom.xml | 2 +- flexible/cloud-tasks/src/main/appengine/app.yaml | 6 +----- .../main/java/com/example/cloudtasks/CreateTaskServlet.java | 2 +- .../src/main/java/com/example/cloudtasks/HelloServlet.java | 2 +- .../main/java/com/example/cloudtasks/LogPayloadServlet.java | 2 +- 6 files changed, 6 insertions(+), 10 deletions(-) diff --git a/flexible/cloud-tasks/README.md b/flexible/cloud-tasks/README.md index 1d77cd72c1a..cf53ff3052d 100644 --- a/flexible/cloud-tasks/README.md +++ b/flexible/cloud-tasks/README.md @@ -1,4 +1,4 @@ -# Google Cloud Tasks App Engine Queue Samples +# Google Cloud Tasks App Engine Flexible Queue Samples This is a sample AppEngine app demonstrating use of the Cloud Tasks API using App Engine Queues. diff --git a/flexible/cloud-tasks/pom.xml b/flexible/cloud-tasks/pom.xml index 941d4de6c56..b390c4b8abe 100644 --- a/flexible/cloud-tasks/pom.xml +++ b/flexible/cloud-tasks/pom.xml @@ -1,5 +1,5 @@