Skip to content

Commit a977aec

Browse files
authored
Add task create & lease/acknowledge sample. (#1153)
* Add task create & lease/acknowledge sample. * Add Appengine Queue Tasks sample.
1 parent 1fc20ab commit a977aec

File tree

7 files changed

+658
-0
lines changed

7 files changed

+658
-0
lines changed

appengine-java8/tasks/pom.xml

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!--
3+
Copyright 2018 Google LLC
4+
5+
Licensed under the Apache License, Version 2.0 (the "License");
6+
you may not use this file except in compliance with the License.
7+
You may obtain a copy of the License at
8+
9+
http://www.apache.org/licenses/LICENSE-2.0
10+
11+
Unless required by applicable law or agreed to in writing, software
12+
distributed under the License is distributed on an "AS IS" BASIS,
13+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
See the License for the specific language governing permissions and
15+
limitations under the License.
16+
-->
17+
<project xmlns="http://maven.apache.org/POM/4.0.0"
18+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
19+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
20+
<modelVersion>4.0.0</modelVersion>
21+
<packaging>war</packaging>
22+
<version>1.0-SNAPSHOT</version>
23+
<groupId>com.example.appengine</groupId>
24+
<artifactId>appengine-tasks-j8</artifactId>
25+
26+
<!--
27+
The parent pom defines common style checks and testing strategies for our samples.
28+
Removing or replacing it should not affect the execution of the samples in anyway.
29+
-->
30+
<parent>
31+
<groupId>com.google.cloud.samples</groupId>
32+
<artifactId>shared-configuration</artifactId>
33+
<version>1.0.10</version>
34+
<relativePath></relativePath>
35+
</parent>
36+
37+
<properties>
38+
<maven.compiler.target>1.8</maven.compiler.target>
39+
<maven.compiler.source>1.8</maven.compiler.source>
40+
<maven-exec-plugin.version>1.6.0</maven-exec-plugin.version>
41+
</properties>
42+
43+
<dependencies>
44+
<!-- Compile/runtime dependencies -->
45+
<dependency>
46+
<groupId>javax.servlet</groupId>
47+
<artifactId>javax.servlet-api</artifactId>
48+
<version>3.1.0</version>
49+
<type>jar</type>
50+
<scope>provided</scope>
51+
</dependency>
52+
<dependency>
53+
<groupId>com.google.cloud</groupId>
54+
<artifactId>google-cloud-tasks</artifactId>
55+
<version>0.54.0-beta</version>
56+
</dependency>
57+
<dependency>
58+
<groupId>commons-cli</groupId>
59+
<artifactId>commons-cli</artifactId>
60+
<version>1.4</version>
61+
<scope>compile</scope>
62+
</dependency>
63+
</dependencies>
64+
65+
<build>
66+
<!-- for hot reload of the web application-->
67+
<outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes
68+
</outputDirectory>
69+
<plugins>
70+
<plugin>
71+
<groupId>com.google.cloud.tools</groupId>
72+
<artifactId>appengine-maven-plugin</artifactId>
73+
<version>1.3.1</version>
74+
<configuration>
75+
<deploy.promote>true</deploy.promote>
76+
<deploy.stopPreviousVersion>true</deploy.stopPreviousVersion>
77+
</configuration>
78+
</plugin>
79+
80+
<plugin>
81+
<groupId>org.apache.maven.plugins</groupId>
82+
<artifactId>maven-war-plugin</artifactId>
83+
<version>3.1.0</version>
84+
</plugin>
85+
86+
<plugin>
87+
<groupId>org.codehaus.mojo</groupId>
88+
<artifactId>exec-maven-plugin</artifactId>
89+
<version>${maven-exec-plugin.version}</version>
90+
<configuration>
91+
<mainClass>com.example.task.CreateTask</mainClass>
92+
<cleanupDaemonThreads>false</cleanupDaemonThreads>
93+
</configuration>
94+
</plugin>
95+
</plugins>
96+
</build>
97+
</project>
Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
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.task;
18+
19+
import com.google.cloud.tasks.v2beta2.AppEngineHttpRequest;
20+
import com.google.cloud.tasks.v2beta2.CloudTasksClient;
21+
import com.google.cloud.tasks.v2beta2.HttpMethod;
22+
import com.google.cloud.tasks.v2beta2.QueueName;
23+
import com.google.cloud.tasks.v2beta2.Task;
24+
import com.google.common.base.Strings;
25+
import com.google.protobuf.ByteString;
26+
import com.google.protobuf.Timestamp;
27+
28+
import java.nio.charset.Charset;
29+
import java.time.Clock;
30+
import java.time.Instant;
31+
32+
import org.apache.commons.cli.CommandLine;
33+
import org.apache.commons.cli.CommandLineParser;
34+
import org.apache.commons.cli.DefaultParser;
35+
import org.apache.commons.cli.HelpFormatter;
36+
import org.apache.commons.cli.Option;
37+
import org.apache.commons.cli.Options;
38+
import org.apache.commons.cli.ParseException;
39+
40+
public class CreateTask {
41+
private static String GGOGLE_CLOUD_PROJECT_KEY = "GOOGLE_CLOUD_PROJECT";
42+
43+
private static Option PROJECT_ID_OPTION = Option.builder("pid")
44+
.longOpt("project-id")
45+
.desc("The Google Cloud Project, if not set as GOOGLE_CLOUD_PROJECT env var.")
46+
.hasArg()
47+
.argName("project-id")
48+
.type(String.class)
49+
.build();
50+
51+
private static Option QUEUE_OPTION = Option.builder("q")
52+
.required()
53+
.longOpt("queue")
54+
.desc("The Cloud Tasks queue.")
55+
.hasArg()
56+
.argName("queue")
57+
.type(String.class)
58+
.build();
59+
60+
private static Option LOCATION_OPTION = Option.builder("l")
61+
.required()
62+
.longOpt("location")
63+
.desc("The region in which your queue is running.")
64+
.hasArg()
65+
.argName("location")
66+
.type(String.class)
67+
.build();
68+
69+
private static Option PAYLOAD_OPTION = Option.builder("p")
70+
.longOpt("payload")
71+
.desc("The payload string for the task.")
72+
.hasArg()
73+
.argName("payload")
74+
.type(String.class)
75+
.build();
76+
77+
private static Option IN_SECONDS_OPTION = Option.builder("s")
78+
.longOpt("in-seconds")
79+
.desc("Schedule time for the task to create.")
80+
.hasArg()
81+
.argName("in-seconds")
82+
.type(int.class)
83+
.build();
84+
85+
public static void main(String... args) throws Exception {
86+
Options options = new Options();
87+
options.addOption(PROJECT_ID_OPTION);
88+
options.addOption(QUEUE_OPTION);
89+
options.addOption(LOCATION_OPTION);
90+
options.addOption(PAYLOAD_OPTION);
91+
options.addOption(IN_SECONDS_OPTION);
92+
93+
if (args.length == 0) {
94+
printUsage(options);
95+
return;
96+
}
97+
98+
CommandLineParser parser = new DefaultParser();
99+
CommandLine params = null;
100+
try {
101+
params = parser.parse(options, args);
102+
} catch (ParseException e) {
103+
System.err.println("Invalid command line: " + e.getMessage());
104+
printUsage(options);
105+
return;
106+
}
107+
108+
String projectId;
109+
if (params.hasOption("project-id")) {
110+
projectId = params.getOptionValue("project-id");
111+
} else {
112+
projectId = System.getenv(GGOGLE_CLOUD_PROJECT_KEY);
113+
}
114+
if (Strings.isNullOrEmpty(projectId)) {
115+
printUsage(options);
116+
return;
117+
}
118+
119+
String queueName = params.getOptionValue(QUEUE_OPTION.getOpt());
120+
String location = params.getOptionValue(LOCATION_OPTION.getOpt());
121+
String payload = params.getOptionValue(PAYLOAD_OPTION.getOpt(), "default payload");
122+
123+
// [START cloud_tasks_appengine_create_task]
124+
try (CloudTasksClient client = CloudTasksClient.create()) {
125+
Task.Builder taskBuilder = Task
126+
.newBuilder()
127+
.setAppEngineHttpRequest(AppEngineHttpRequest.newBuilder()
128+
.setPayload(ByteString.copyFrom(payload, Charset.defaultCharset()))
129+
.setRelativeUrl("/tasks/create")
130+
.setHttpMethod(HttpMethod.POST)
131+
.build());
132+
if (params.hasOption(IN_SECONDS_OPTION.getOpt())) {
133+
int seconds = Integer.parseInt(params.getOptionValue(IN_SECONDS_OPTION.getOpt()));
134+
taskBuilder.setScheduleTime(Timestamp
135+
.newBuilder()
136+
.setSeconds(Instant.now(Clock.systemUTC()).plusSeconds(seconds).getEpochSecond()));
137+
}
138+
Task task = client.createTask(
139+
QueueName.of(projectId, location, queueName).toString(), taskBuilder.build());
140+
System.out.println("Task created: " + task.getName());
141+
}
142+
// [END cloud_tasks_appengine_create_task]
143+
}
144+
145+
private static void printUsage(Options options) {
146+
HelpFormatter formatter = new HelpFormatter();
147+
formatter.printHelp(
148+
"client",
149+
"A simple Cloud Tasks command line client that triggers a call to an AppEngine "
150+
+ "endpoint.",
151+
options, "", true);
152+
throw new RuntimeException();
153+
}
154+
155+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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.task;
18+
19+
import java.io.IOException;
20+
import java.util.logging.Logger;
21+
import javax.servlet.annotation.WebServlet;
22+
import javax.servlet.http.HttpServlet;
23+
import javax.servlet.http.HttpServletRequest;
24+
import javax.servlet.http.HttpServletResponse;
25+
26+
// [START cloud_tasks_appengine_quickstart]
27+
@WebServlet(
28+
name = "Tasks",
29+
description = "Create Cloud Task",
30+
urlPatterns = "/tasks/create"
31+
)
32+
public class TaskServlet extends HttpServlet {
33+
private static Logger log = Logger.getLogger(TaskServlet.class.getName());
34+
35+
@Override
36+
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
37+
log.info("Received task request: " + req.getServletPath());
38+
if (req.getParameter("payload") != null) {
39+
String payload = req.getParameter("payload");
40+
log.info("Request payload: " + payload);
41+
String output = String.format("Received task with payload %s", payload);
42+
resp.getOutputStream().write(output.getBytes());
43+
log.info("Sending response: " + output);
44+
resp.setStatus(HttpServletResponse.SC_OK);
45+
} else {
46+
log.warning("Null payload received in request to " + req.getServletPath());
47+
}
48+
}
49+
}
50+
// [END cloud_tasks_appengine_quickstart]
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<!-- [START_EXCLUDE] -->
3+
<!--
4+
Copyright 2016 Google Inc.
5+
Licensed under the Apache License, Version 2.0 (the "License");
6+
you may not use this file except in compliance with the License.
7+
You may obtain a copy of the License at
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
Unless required by applicable law or agreed to in writing, software
10+
distributed under the License is distributed on an "AS IS" BASIS,
11+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
See the License for the specific language governing permissions and
13+
limitations under the License.
14+
-->
15+
<!-- [END_EXCLUDE] -->
16+
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
17+
<runtime>java8</runtime>
18+
<threadsafe>true</threadsafe>
19+
</appengine-web-app>

0 commit comments

Comments
 (0)