Skip to content

Commit

Permalink
Add Cloud Tasks Samples (#930)
Browse files Browse the repository at this point in the history
* Added Cloud Tasks snippets for Pull Queues.
* Added AppEngine Flexible App for Cloud Tasks API.
* Minor text fixes.
  • Loading branch information
kurtisvg authored Nov 28, 2017
1 parent 2e71be4 commit ab682d2
Show file tree
Hide file tree
Showing 11 changed files with 839 additions and 0 deletions.
62 changes: 62 additions & 0 deletions cloud-tasks/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# 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).


## 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

From the project folder, build your project with:

```
mvn clean assembly:single
```

Optionally, you can set up your settings as environment variables:

```
export PROJECT_ID=<YOUR_PROJECT_ID>
export LOCATION_ID=<YOUR_ZONE>
export QUEUE_ID=<YOUR_QUEUE_NAME>
```

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 --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 --location=$LOCATION_ID --queue=$QUEUE_ID
```
Note that usually, there would be a processing step in between pulling a task and acknowledging it.

89 changes: 89 additions & 0 deletions cloud-tasks/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>cloudtasks</artifactId>
<version>1.0.0</version>

<parent>
<artifactId>doc-samples</artifactId>
<groupId>com.google.cloud</groupId>
<version>1.0.0</version>
<relativePath>..</relativePath>
</parent>

<dependencies>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-cloudtasks</artifactId>
<version>v2beta2-rev16-1.23.0</version>
</dependency>
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.23.0</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson2</artifactId>
<version>1.23.0</version>
</dependency>

<!-- parser dependency -->
<dependency>
<groupId>net.sourceforge.argparse4j</groupId>
<artifactId>argparse4j</artifactId>
<version>0.8.1</version>
</dependency>
<!-- test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
<version>0.36</version>
<scope>test</scope>
</dependency>
</dependencies>


<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>


</project>
209 changes: 209 additions & 0 deletions cloud-tasks/src/main/java/com.example.cloudtasks/PullQueue.java
Original file line number Diff line number Diff line change
@@ -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.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;
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().setPullMessage(new PullMessage().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);
}
}

}
Loading

0 comments on commit ab682d2

Please sign in to comment.