Skip to content

Commit 9535b0d

Browse files
author
Dane Liergaard
committed
Add task create & lease/acknowledge sample.
1 parent 86603c2 commit 9535b0d

File tree

3 files changed

+335
-0
lines changed

3 files changed

+335
-0
lines changed

tasks/pom.xml

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
<project xmlns="http://maven.apache.org/POM/4.0.0"
2+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4+
<modelVersion>4.0.0</modelVersion>
5+
<groupId>com.example</groupId>
6+
<artifactId>tasks-samples</artifactId>
7+
<packaging>jar</packaging>
8+
<version>1.0</version>
9+
10+
<!--
11+
The parent pom defines common style checks and testing strategies for our samples.
12+
Removing or replacing it should not affect the execution of the samples in anyway.
13+
-->
14+
<parent>
15+
<groupId>com.google.cloud.samples</groupId>
16+
<artifactId>shared-configuration</artifactId>
17+
<version>1.0.10</version>
18+
<relativePath></relativePath>
19+
</parent>
20+
21+
<properties>
22+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
23+
<maven.compiler.target>1.8</maven.compiler.target>
24+
<maven.compiler.source>1.8</maven.compiler.source>
25+
</properties>
26+
27+
<dependencies>
28+
<dependency>
29+
<groupId>com.google.cloud</groupId>
30+
<artifactId>google-cloud-tasks</artifactId>
31+
<version>0.54.0-beta</version>
32+
</dependency>
33+
34+
<!-- test dependencies -->
35+
<dependency>
36+
<groupId>junit</groupId>
37+
<artifactId>junit</artifactId>
38+
<version>4.12</version>
39+
<scope>test</scope>
40+
</dependency>
41+
<dependency>
42+
<groupId>com.google.truth</groupId>
43+
<artifactId>truth</artifactId>
44+
<version>0.41</version>
45+
<scope>test</scope>
46+
</dependency>
47+
<dependency>
48+
<groupId>com.google.api-client</groupId>
49+
<artifactId>google-api-client</artifactId>
50+
<version>1.23.0</version>
51+
<scope>compile</scope>
52+
</dependency>
53+
<dependency>
54+
<groupId>commons-cli</groupId>
55+
<artifactId>commons-cli</artifactId>
56+
<version>1.4</version>
57+
<scope>compile</scope>
58+
</dependency>
59+
</dependencies>
60+
61+
<build>
62+
<sourceDirectory>src/main/java</sourceDirectory>
63+
<plugins>
64+
<plugin>
65+
<groupId>org.apache.maven.plugins</groupId>
66+
<artifactId>maven-compiler-plugin</artifactId>
67+
<version>3.2</version>
68+
</plugin>
69+
<plugin>
70+
<artifactId>maven-assembly-plugin</artifactId>
71+
<configuration>
72+
<descriptorRefs>
73+
<descriptorRef>jar-with-dependencies</descriptorRef>
74+
</descriptorRefs>
75+
</configuration>
76+
</plugin>
77+
</plugins>
78+
</build>
79+
80+
</project>
Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
/*
2+
* Copyright 2018 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example;
18+
19+
// [START tasks_quickstart]
20+
21+
import com.google.cloud.tasks.v2beta2.AcknowledgeTaskRequest;
22+
import com.google.cloud.tasks.v2beta2.CloudTasksClient;
23+
import com.google.cloud.tasks.v2beta2.CreateTaskRequest;
24+
import com.google.cloud.tasks.v2beta2.LeaseTasksRequest;
25+
import com.google.cloud.tasks.v2beta2.LeaseTasksResponse;
26+
import com.google.cloud.tasks.v2beta2.PullMessage;
27+
import com.google.cloud.tasks.v2beta2.QueueName;
28+
import com.google.cloud.tasks.v2beta2.Task;
29+
import com.google.common.base.Strings;
30+
import com.google.protobuf.ByteString;
31+
import com.google.protobuf.Duration;
32+
33+
import java.io.IOException;
34+
import java.nio.charset.Charset;
35+
36+
import org.apache.commons.cli.CommandLineParser;
37+
import org.apache.commons.cli.DefaultParser;
38+
import org.apache.commons.cli.Option;
39+
import org.apache.commons.cli.CommandLine;
40+
import org.apache.commons.cli.HelpFormatter;
41+
import org.apache.commons.cli.Options;
42+
import org.apache.commons.cli.ParseException;
43+
44+
public class Quickstart {
45+
private static String GGOGLE_CLOUD_PROJECT_KEY = "GOOGLE_CLOUD_PROJECT";
46+
47+
private static Option PROJECT_ID_OPTION = Option.builder("project")
48+
.longOpt("project-id")
49+
.desc("The Google Cloud Project, if not set as GOOGLE_CLOUD_PROJECT env var.")
50+
.hasArg()
51+
.argName("project-id")
52+
.type(String.class)
53+
.build();
54+
55+
private static Option QUEUE_OPTION = Option.builder("queue")
56+
.required()
57+
.longOpt("queue")
58+
.desc("The Cloud Tasks queue.")
59+
.hasArg()
60+
.argName("queue")
61+
.type(String.class)
62+
.build();
63+
64+
private static Option LOCATION_OPTION = Option.builder("location")
65+
.required()
66+
.longOpt("location")
67+
.desc("The region in which your queue is running.")
68+
.hasArg()
69+
.argName("location")
70+
.type(String.class)
71+
.build();
72+
73+
public static void main(String... args) throws Exception {
74+
Options options = new Options();
75+
options.addOption(PROJECT_ID_OPTION);
76+
options.addOption(QUEUE_OPTION);
77+
options.addOption(LOCATION_OPTION);
78+
79+
if (args.length == 0) {
80+
printUsage(options);
81+
return;
82+
}
83+
84+
CommandLineParser parser = new DefaultParser();
85+
CommandLine params;
86+
try {
87+
params = parser.parse(options, args);
88+
} catch (ParseException e) {
89+
System.err.println("Invalid command line: " + e.getMessage());
90+
printUsage(options);
91+
return;
92+
}
93+
94+
String projectId;
95+
if (params.hasOption("project-id")) {
96+
projectId = params.getOptionValue("project-id");
97+
} else {
98+
projectId = System.getenv(GGOGLE_CLOUD_PROJECT_KEY);
99+
}
100+
if (Strings.isNullOrEmpty(projectId)) {
101+
printUsage(options);
102+
return;
103+
}
104+
105+
String queue = params.getOptionValue(QUEUE_OPTION.getOpt());
106+
String location = params.getOptionValue(LOCATION_OPTION.getOpt());
107+
108+
switch (args[0]) {
109+
default:
110+
printUsage(options);
111+
break;
112+
case "create-task":
113+
createTask(projectId, queue, location);
114+
break;
115+
case "lease-and-ack-task":
116+
pullAndAckTask(projectId, queue, location);
117+
break;
118+
}
119+
}
120+
121+
// [START cloud_tasks_create_task]
122+
private static void createTask(String projectId, String queueName, String location)
123+
throws IOException {
124+
try (CloudTasksClient client = CloudTasksClient.create()) {
125+
Task.Builder taskBuilder = Task
126+
.newBuilder()
127+
.setPullMessage(PullMessage.newBuilder().setPayload(
128+
ByteString.copyFrom("a message for recipient", Charset.defaultCharset())));
129+
130+
Task newTask = client.createTask(CreateTaskRequest
131+
.newBuilder()
132+
.setParent(QueueName.of(projectId, location, queueName).toString())
133+
.setTask(taskBuilder)
134+
.build());
135+
System.out.println("Task created: " + newTask.getName());
136+
}
137+
}
138+
// [END cloud_tasks_create_task]
139+
140+
// [START cloud_tasks_lease_and_acknowledge_task]
141+
private static void pullAndAckTask(String projectId, String queueName, String location) {
142+
try (CloudTasksClient client = CloudTasksClient.create()) {
143+
LeaseTasksRequest.Builder reqBuilder = LeaseTasksRequest.newBuilder()
144+
.setParent(QueueName.of(projectId, location, queueName).toString())
145+
.setLeaseDuration(Duration.newBuilder().setSeconds(600))
146+
.setMaxTasks(1)
147+
.setResponseView(Task.View.FULL);
148+
LeaseTasksResponse response = client.leaseTasks(reqBuilder.build());
149+
if (response.getTasksCount() == 0) {
150+
System.out.println("No tasks found in queue.");
151+
return;
152+
}
153+
Task task = response.getTasksList().get(0);
154+
System.out.println("Leased task: " + task.getName());
155+
client.acknowledgeTask(AcknowledgeTaskRequest
156+
.newBuilder()
157+
.setName(task.getName())
158+
.setScheduleTime(task.getScheduleTime())
159+
.build());
160+
System.out.println("Acknowledged task: " + task.getName());
161+
} catch (Exception e) {
162+
System.out.println("Exception during PullAndAckTask: " + e.getMessage());
163+
}
164+
}
165+
// [END cloud_tasks_lease_and_acknowledge_task]
166+
167+
private static void printUsage(Options options) {
168+
HelpFormatter formatter = new HelpFormatter();
169+
formatter.printHelp("client",
170+
"A simple Cloud Tasks command line client.", options, "", true);
171+
}
172+
}
173+
// [END tasks_quickstart]
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
/*
2+
* Copyright 2017 Google Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example;
18+
19+
import static com.google.common.truth.Truth.assertThat;
20+
import static org.junit.Assert.assertTrue;
21+
22+
import com.google.cloud.tasks.v2beta2.CloudTasksClient;
23+
import com.google.cloud.tasks.v2beta2.QueueName;
24+
25+
import java.io.ByteArrayOutputStream;
26+
import java.io.IOException;
27+
import java.io.PrintStream;
28+
29+
import org.junit.AfterClass;
30+
import org.junit.Assert;
31+
import org.junit.Before;
32+
import org.junit.BeforeClass;
33+
import org.junit.Test;
34+
import org.junit.runner.RunWith;
35+
import org.junit.runners.JUnit4;
36+
37+
/**
38+
* Integration (system) tests for {@link Quickstart}.
39+
*/
40+
@RunWith(JUnit4.class)
41+
@SuppressWarnings("checkstyle:abbreviationaswordinname")
42+
public class QuickstartIT {
43+
private static String queue_name = "my-pull-queue";
44+
private static String location = "us-east1";
45+
private ByteArrayOutputStream bout;
46+
private PrintStream out;
47+
48+
@BeforeClass
49+
public static void setUpClass() throws Exception {
50+
ByteArrayOutputStream bout = new ByteArrayOutputStream();
51+
PrintStream out = new PrintStream(bout);
52+
System.setOut(out);
53+
}
54+
55+
// Purge the task queue when tests done.
56+
@AfterClass
57+
public static void tearDownClass() throws IOException {
58+
try (CloudTasksClient client = CloudTasksClient.create()) {
59+
client.purgeQueue(QueueName.of(System.getenv("GOOGLE_CLOUD_PROJECT"), location, queue_name));
60+
}
61+
}
62+
63+
@Before
64+
public void setUp() throws Exception {
65+
bout = new ByteArrayOutputStream();
66+
out = new PrintStream(bout);
67+
System.setOut(out);
68+
}
69+
70+
@Test
71+
public void createTaskTest() throws Exception {
72+
Quickstart.main("create-task", "--queue", queue_name, "--location", location);
73+
assertThat(bout.toString()).contains("Task created: ");
74+
}
75+
76+
@Test
77+
public void leaseAndAcknowledge() throws Exception {
78+
Quickstart.main("lease-and-ack-task", "--queue", queue_name, "--location", location);
79+
assertThat(bout.toString()).contains("Leased task: ");
80+
assertThat(bout.toString()).contains("Acknowledged task: ");
81+
}
82+
}

0 commit comments

Comments
 (0)