Skip to content

Commit e21d145

Browse files
dzlier-gcpchingor13
authored andcommitted
samples: Add task create & lease/acknowledge sample. (#1153)
* Add task create & lease/acknowledge sample. * Add Appengine Queue Tasks sample.
1 parent a6853b0 commit e21d145

File tree

2 files changed

+257
-0
lines changed

2 files changed

+257
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
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.CommandLine;
37+
import org.apache.commons.cli.CommandLineParser;
38+
import org.apache.commons.cli.DefaultParser;
39+
import org.apache.commons.cli.HelpFormatter;
40+
import org.apache.commons.cli.Option;
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 leaseReq = 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+
.build();
149+
LeaseTasksResponse response = client.leaseTasks(leaseReq);
150+
if (response.getTasksCount() == 0) {
151+
System.out.println("No tasks found in queue.");
152+
return;
153+
}
154+
Task task = response.getTasksList().get(0);
155+
System.out.println("Leased task: " + task.getName());
156+
AcknowledgeTaskRequest ackRequest = AcknowledgeTaskRequest
157+
.newBuilder()
158+
.setName(task.getName())
159+
.setScheduleTime(task.getScheduleTime())
160+
.build();
161+
client.acknowledgeTask(ackRequest);
162+
System.out.println("Acknowledged task: " + task.getName());
163+
} catch (Exception e) {
164+
System.out.println("Exception during PullAndAckTask: " + e.getMessage());
165+
}
166+
}
167+
// [END cloud_tasks_lease_and_acknowledge_task]
168+
169+
private static void printUsage(Options options) {
170+
HelpFormatter formatter = new HelpFormatter();
171+
formatter.printHelp("client",
172+
"A simple Cloud Tasks command line client.", options, "", true);
173+
}
174+
}
175+
// [END tasks_quickstart]
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)