Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 97 additions & 0 deletions appengine-java8/tasks/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2018 Google LLC

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 xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<groupId>com.example.appengine</groupId>
<artifactId>appengine-tasks-j8</artifactId>

<!--
The parent pom defines common style checks and testing strategies for our samples.
Removing or replacing it should not affect the execution of the samples in anyway.
-->
<parent>
<groupId>com.google.cloud.samples</groupId>
<artifactId>shared-configuration</artifactId>
<version>1.0.10</version>
<relativePath></relativePath>
</parent>

<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<maven-exec-plugin.version>1.6.0</maven-exec-plugin.version>
</properties>

<dependencies>
<!-- Compile/runtime dependencies -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-tasks</artifactId>
<version>0.54.0-beta</version>
</dependency>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.4</version>
<scope>compile</scope>
</dependency>
</dependencies>

<build>
<!-- for hot reload of the web application-->
<outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes
</outputDirectory>
<plugins>
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>appengine-maven-plugin</artifactId>
<version>1.3.1</version>
<configuration>
<deploy.promote>true</deploy.promote>
<deploy.stopPreviousVersion>true</deploy.stopPreviousVersion>
</configuration>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.1.0</version>
</plugin>

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${maven-exec-plugin.version}</version>
<configuration>
<mainClass>com.example.task.CreateTask</mainClass>
<cleanupDaemonThreads>false</cleanupDaemonThreads>
</configuration>
</plugin>
</plugins>
</build>
</project>
155 changes: 155 additions & 0 deletions appengine-java8/tasks/src/main/java/com/example/task/CreateTask.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
/*
* Copyright 2018 Google LLC
*
* 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.task;

import com.google.cloud.tasks.v2beta2.AppEngineHttpRequest;
import com.google.cloud.tasks.v2beta2.CloudTasksClient;
import com.google.cloud.tasks.v2beta2.HttpMethod;
import com.google.cloud.tasks.v2beta2.QueueName;
import com.google.cloud.tasks.v2beta2.Task;
import com.google.common.base.Strings;
import com.google.protobuf.ByteString;
import com.google.protobuf.Timestamp;

import java.nio.charset.Charset;
import java.time.Clock;
import java.time.Instant;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class CreateTask {
private static String GGOGLE_CLOUD_PROJECT_KEY = "GOOGLE_CLOUD_PROJECT";

private static Option PROJECT_ID_OPTION = Option.builder("pid")
.longOpt("project-id")
.desc("The Google Cloud Project, if not set as GOOGLE_CLOUD_PROJECT env var.")
.hasArg()
.argName("project-id")
.type(String.class)
.build();

private static Option QUEUE_OPTION = Option.builder("q")
.required()
.longOpt("queue")
.desc("The Cloud Tasks queue.")
.hasArg()
.argName("queue")
.type(String.class)
.build();

private static Option LOCATION_OPTION = Option.builder("l")
.required()
.longOpt("location")
.desc("The region in which your queue is running.")
.hasArg()
.argName("location")
.type(String.class)
.build();

private static Option PAYLOAD_OPTION = Option.builder("p")
.longOpt("payload")
.desc("The payload string for the task.")
.hasArg()
.argName("payload")
.type(String.class)
.build();

private static Option IN_SECONDS_OPTION = Option.builder("s")
.longOpt("in-seconds")
.desc("Schedule time for the task to create.")
.hasArg()
.argName("in-seconds")
.type(int.class)
.build();

public static void main(String... args) throws Exception {
Options options = new Options();
options.addOption(PROJECT_ID_OPTION);
options.addOption(QUEUE_OPTION);
options.addOption(LOCATION_OPTION);
options.addOption(PAYLOAD_OPTION);
options.addOption(IN_SECONDS_OPTION);

if (args.length == 0) {
printUsage(options);
return;
}

CommandLineParser parser = new DefaultParser();
CommandLine params = null;
try {
params = parser.parse(options, args);
} catch (ParseException e) {
System.err.println("Invalid command line: " + e.getMessage());
printUsage(options);
return;
}

String projectId;
if (params.hasOption("project-id")) {
projectId = params.getOptionValue("project-id");
} else {
projectId = System.getenv(GGOGLE_CLOUD_PROJECT_KEY);
}
if (Strings.isNullOrEmpty(projectId)) {
printUsage(options);
return;
}

String queueName = params.getOptionValue(QUEUE_OPTION.getOpt());
String location = params.getOptionValue(LOCATION_OPTION.getOpt());
String payload = params.getOptionValue(PAYLOAD_OPTION.getOpt(), "default payload");

// [START cloud_tasks_appengine_create_task]
try (CloudTasksClient client = CloudTasksClient.create()) {
Task.Builder taskBuilder = Task
.newBuilder()
.setAppEngineHttpRequest(AppEngineHttpRequest.newBuilder()
.setPayload(ByteString.copyFrom(payload, Charset.defaultCharset()))
.setRelativeUrl("/tasks/create")
.setHttpMethod(HttpMethod.POST)
.build());
if (params.hasOption(IN_SECONDS_OPTION.getOpt())) {
int seconds = Integer.parseInt(params.getOptionValue(IN_SECONDS_OPTION.getOpt()));
taskBuilder.setScheduleTime(Timestamp
.newBuilder()
.setSeconds(Instant.now(Clock.systemUTC()).plusSeconds(seconds).getEpochSecond()));
}
Task task = client.createTask(
QueueName.of(projectId, location, queueName).toString(), taskBuilder.build());
System.out.println("Task created: " + task.getName());
}
// [END cloud_tasks_appengine_create_task]
}

private static void printUsage(Options options) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(
"client",
"A simple Cloud Tasks command line client that triggers a call to an AppEngine "
+ "endpoint.",
options, "", true);
throw new RuntimeException();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Copyright 2018 Google LLC
*
* 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.task;

import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// [START cloud_tasks_appengine_quickstart]
@WebServlet(
name = "Tasks",
description = "Create Cloud Task",
urlPatterns = "/tasks/create"
)
public class TaskServlet extends HttpServlet {
private static Logger log = Logger.getLogger(TaskServlet.class.getName());

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
log.info("Received task request: " + req.getServletPath());
if (req.getParameter("payload") != null) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It might be a good idea to add a line of logging for when the payload is null - that way if the user forgets to set a payload the endpoint will still logged that it was triggered.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These log statements were actually just for my debugging purposes initially, but yeah I can add one for a null payload. Warning level probably, since it doesn't affect the execution?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typically logging is debug < info < warning < critical, so using ' debug' or 'info' is probably typical (but I don't think it makes a big difference for a smaller application).

String payload = req.getParameter("payload");
log.info("Request payload: " + payload);
String output = String.format("Received task with payload %s", payload);
resp.getOutputStream().write(output.getBytes());
log.info("Sending response: " + output);
resp.setStatus(HttpServletResponse.SC_OK);
} else {
log.warning("Null payload received in request to " + req.getServletPath());
}
}
}
// [END cloud_tasks_appengine_quickstart]
19 changes: 19 additions & 0 deletions appengine-java8/tasks/src/main/webapp/WEB-INF/appengine-web.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- [START_EXCLUDE] -->
<!--
Copyright 2016 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.
-->
<!-- [END_EXCLUDE] -->
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<runtime>java8</runtime>
<threadsafe>true</threadsafe>
</appengine-web-app>
Loading