Skip to content

Commit bd33182

Browse files
author
Dane Liergaard
committed
Add Appengine Queue Tasks sample.
1 parent 9535b0d commit bd33182

File tree

4 files changed

+326
-0
lines changed

4 files changed

+326
-0
lines changed

appengine-java8/tasks/pom.xml

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!--
3+
Copyright 2016 Google Inc.
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.9</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>com.google.appengine</groupId>
47+
<artifactId>appengine-api-1.0-sdk</artifactId>
48+
<version>1.9.64</version>
49+
</dependency>
50+
<dependency>
51+
<groupId>javax.servlet</groupId>
52+
<artifactId>javax.servlet-api</artifactId>
53+
<version>3.1.0</version>
54+
<type>jar</type>
55+
<scope>provided</scope>
56+
</dependency>
57+
<dependency>
58+
<groupId>jstl</groupId>
59+
<artifactId>jstl</artifactId>
60+
<version>1.2</version>
61+
</dependency>
62+
<dependency>
63+
<groupId>com.google.cloud</groupId>
64+
<artifactId>google-cloud-tasks</artifactId>
65+
<version>0.54.0-beta</version>
66+
</dependency>
67+
<dependency>
68+
<groupId>commons-cli</groupId>
69+
<artifactId>commons-cli</artifactId>
70+
<version>1.4</version>
71+
<scope>compile</scope>
72+
</dependency>
73+
74+
<!-- Test Dependencies -->
75+
<dependency>
76+
<groupId>com.google.appengine</groupId>
77+
<artifactId>appengine-testing</artifactId>
78+
<version>1.9.64</version>
79+
<scope>test</scope>
80+
</dependency>
81+
<dependency>
82+
<groupId>com.google.appengine</groupId>
83+
<artifactId>appengine-api-stubs</artifactId>
84+
<version>1.9.64</version>
85+
<scope>test</scope>
86+
</dependency>
87+
</dependencies>
88+
89+
<build>
90+
<!-- for hot reload of the web application-->
91+
<outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes
92+
</outputDirectory>
93+
<plugins>
94+
<plugin>
95+
<groupId>com.google.cloud.tools</groupId>
96+
<artifactId>appengine-maven-plugin</artifactId>
97+
<version>1.3.1</version>
98+
<configuration>
99+
<deploy.promote>true</deploy.promote>
100+
<deploy.stopPreviousVersion>true</deploy.stopPreviousVersion>
101+
</configuration>
102+
</plugin>
103+
104+
<plugin>
105+
<groupId>org.apache.maven.plugins</groupId>
106+
<artifactId>maven-war-plugin</artifactId>
107+
<version>3.1.0</version>
108+
</plugin>
109+
110+
<plugin>
111+
<groupId>org.codehaus.mojo</groupId>
112+
<artifactId>exec-maven-plugin</artifactId>
113+
<version>${maven-exec-plugin.version}</version>
114+
<configuration>
115+
<mainClass>com.example.task.CreateTask</mainClass>
116+
<cleanupDaemonThreads>false</cleanupDaemonThreads>
117+
</configuration>
118+
</plugin>
119+
</plugins>
120+
</build>
121+
</project>
Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
package com.example.task;
2+
3+
import com.google.cloud.tasks.v2beta2.AppEngineHttpRequest;
4+
import com.google.cloud.tasks.v2beta2.CloudTasksClient;
5+
import com.google.cloud.tasks.v2beta2.HttpMethod;
6+
import com.google.cloud.tasks.v2beta2.QueueName;
7+
import com.google.cloud.tasks.v2beta2.Task;
8+
import com.google.common.base.Strings;
9+
import com.google.protobuf.ByteString;
10+
import com.google.protobuf.Timestamp;
11+
12+
import java.nio.charset.Charset;
13+
import java.time.Clock;
14+
import java.time.Instant;
15+
16+
import org.apache.commons.cli.CommandLine;
17+
import org.apache.commons.cli.CommandLineParser;
18+
import org.apache.commons.cli.DefaultParser;
19+
import org.apache.commons.cli.HelpFormatter;
20+
import org.apache.commons.cli.Option;
21+
import org.apache.commons.cli.Options;
22+
import org.apache.commons.cli.ParseException;
23+
24+
public class CreateTask {
25+
private static String GGOGLE_CLOUD_PROJECT_KEY = "GOOGLE_CLOUD_PROJECT";
26+
27+
private static Option PROJECT_ID_OPTION = Option.builder("pid")
28+
.longOpt("project-id")
29+
.desc("The Google Cloud Project, if not set as GOOGLE_CLOUD_PROJECT env var.")
30+
.hasArg()
31+
.argName("project-id")
32+
.type(String.class)
33+
.build();
34+
35+
private static Option QUEUE_OPTION = Option.builder("q")
36+
.required()
37+
.longOpt("queue")
38+
.desc("The Cloud Tasks queue.")
39+
.hasArg()
40+
.argName("queue")
41+
.type(String.class)
42+
.build();
43+
44+
private static Option LOCATION_OPTION = Option.builder("l")
45+
.required()
46+
.longOpt("location")
47+
.desc("The region in which your queue is running.")
48+
.hasArg()
49+
.argName("location")
50+
.type(String.class)
51+
.build();
52+
53+
private static Option PAYLOAD_OPTION = Option.builder("p")
54+
.longOpt("payload")
55+
.desc("The payload string for the task.")
56+
.hasArg()
57+
.argName("payload")
58+
.type(String.class)
59+
.build();
60+
61+
private static Option IN_SECONDS_OPTION = Option.builder("s")
62+
.longOpt("in-seconds")
63+
.desc("Schedule time for the task to create.")
64+
.hasArg()
65+
.argName("in-seconds")
66+
.type(int.class)
67+
.build();
68+
69+
public static void main(String... args) throws Exception {
70+
// [START cloud_tasks_appengine_create_task]
71+
Options options = new Options();
72+
options.addOption(PROJECT_ID_OPTION);
73+
options.addOption(QUEUE_OPTION);
74+
options.addOption(LOCATION_OPTION);
75+
options.addOption(PAYLOAD_OPTION);
76+
options.addOption(IN_SECONDS_OPTION);
77+
78+
if (args.length == 0) {
79+
printUsage(options);
80+
return;
81+
}
82+
83+
CommandLineParser parser = new DefaultParser();
84+
CommandLine params = null;
85+
try {
86+
params = parser.parse(options, args);
87+
} catch (ParseException e) {
88+
System.err.println("Invalid command line: " + e.getMessage());
89+
printUsage(options);
90+
return;
91+
}
92+
93+
String projectId;
94+
if (params.hasOption("project-id")) {
95+
projectId = params.getOptionValue("project-id");
96+
} else {
97+
projectId = System.getenv(GGOGLE_CLOUD_PROJECT_KEY);
98+
}
99+
if (Strings.isNullOrEmpty(projectId)) {
100+
printUsage(options);
101+
return;
102+
}
103+
104+
String queueName = params.getOptionValue(QUEUE_OPTION.getOpt());
105+
String location = params.getOptionValue(LOCATION_OPTION.getOpt());
106+
String payload = params.getOptionValue(PAYLOAD_OPTION.getOpt(), "default payload");
107+
108+
try (CloudTasksClient client = CloudTasksClient.create()) {
109+
Task.Builder taskBuilder = Task
110+
.newBuilder()
111+
.setAppEngineHttpRequest(AppEngineHttpRequest.newBuilder()
112+
.setPayload(ByteString.copyFrom(payload, Charset.defaultCharset()))
113+
.setRelativeUrl("/tasks/create")
114+
.setHttpMethod(HttpMethod.POST)
115+
.build());
116+
if (params.hasOption(IN_SECONDS_OPTION.getOpt())) {
117+
int seconds = Integer.parseInt(params.getOptionValue(IN_SECONDS_OPTION.getOpt()));
118+
taskBuilder.setScheduleTime(Timestamp
119+
.newBuilder()
120+
.setSeconds(Instant.now(Clock.systemUTC()).plusSeconds(seconds).getEpochSecond()));
121+
}
122+
Task task = client.createTask(
123+
QueueName.of(projectId, location, queueName).toString(), taskBuilder.build());
124+
System.out.println("Task created: " + task.getName());
125+
}
126+
// [END cloud_tasks_appengine_create_task]
127+
}
128+
129+
private static void printUsage(Options options) {
130+
HelpFormatter formatter = new HelpFormatter();
131+
formatter.printHelp(
132+
"client",
133+
"A simple Cloud Tasks command line client that triggers a call to an AppEngine " +
134+
"endpoint.",
135+
options, "", true);
136+
throw new RuntimeException();
137+
}
138+
139+
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
* Copyright 2015 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.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+
@Override
35+
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
36+
log.info("Received task request: " + req.getServletPath());
37+
if (req.getParameter("payload") != null) {
38+
String payload = req.getParameter("payload");
39+
log.info("Request payload: " + payload);
40+
String output = String.format("Received task with payload %s", payload);
41+
resp.getOutputStream().write(output.getBytes());
42+
log.info("Sending response: " + output);
43+
resp.setStatus(HttpServletResponse.SC_OK);
44+
}
45+
}
46+
}
47+
// [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)