Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Cloud tasks samples #1211

Merged
merged 8 commits into from
Sep 12, 2018
Merged
Show file tree
Hide file tree
Changes from 4 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
22 changes: 6 additions & 16 deletions appengine-java8/tasks/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ App Engine task attempts.
[Cloud Tasks API](https://console.cloud.google.com/launcher/details/google/cloudtasks.googleapis.com).
* Download and install the [Cloud SDK](https://cloud.google.com/sdk).
* Download and install [Maven](http://maven.apache.org/install.html).
* Set up [Google Application Credentials](https://cloud.google.com/docs/authentication/getting-started).

## Creating a queue

Expand All @@ -37,25 +38,18 @@ version unless configured to do otherwise.
[Using Maven and the App Engine Plugin](https://cloud.google.com/appengine/docs/flexible/java/using-maven)
& [Maven Plugin Goals and Parameters](https://cloud.google.com/appengine/docs/flexible/java/maven-reference)

### Running locally

```
mvn appengine:run
```
### Deploying

```
mvn appengine:deploy
```

## Running the Sample
## Run the Sample Using the Command Line

Set environment variables:

First, your project ID:

```
export GOOGLE_CLOUD_PROJECT=<YOUR_PROJECT_ID>
export PROJECT_ID=<YOUR_PROJECT_ID>
```

Then the queue ID, as specified at queue creation time. Queue IDs already
Expand All @@ -79,23 +73,19 @@ Create a task, targeted at the `/tasks/create` endpoint, with a payload specifie

```
mvn exec:java -Dexec.mainClass="com.example.task.CreateTask" \
-Dexec.args="--project-id $GOOGLE_CLOUD_PROJECT \
-Dexec.args="--project-id $PROJECT_ID \
Copy link
Member

Choose a reason for hiding this comment

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

Why is this being changed? It's GOOGLE_CLOUD_PROJECT in all the samples I can think of, though I wouldn't be surprised if there were inconsistencies. Was there guidance on this that I missed?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Trying to make it consistent between the samples; there are many inconsistencies between repos/samples. I don't think there is an official call.

Copy link
Member

Choose a reason for hiding this comment

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

There are documentation pages that refer to GOOGLE_CLOUD_PROJECT env var though, including it being required for AEF, where I haven't seen any doc pages using just PROJECT_ID (aside from as a placeholder in CLI args or urls). That seems to only exist in samples.

You're right that the inconsistencies should be addressed though. If you're looking to remove one in favor of the other, though, this is the wrong direction - I found 39 examples of System.getenv("GOOGLE_CLOUD_PROJECT") in the project, versus 15 examples of System.getenv("PROJECT_ID"). Considering the first is referred to as an env var in our documentation, I'd prefer leaving this the way it was.

--queue $QUEUE_ID --location $LOCATION_ID --payload hello"
```

The App Engine app serves as a target for the push requests. It has an
endpoint `/tasks/create` that reads the payload (i.e., the request body) of the
HTTP POST request and logs it. The log output can be viewed with:

```
gcloud app logs read
```
HTTP POST request and logs it. The log output can be viewed with [Stackdriver Logging](https://console.cloud.google.com/logs/viewer?minLogLevel=0).

Create a task that will be scheduled for a time in the future using the
`--in-seconds` flag:

```
mvn exec:java -Dexec.mainClass="com.example.task.CreateTask" \
-Dexec.args="--project-id $GOOGLE_CLOUD_PROJECT \
-Dexec.args="--project-id $PROJECT_ID \
--queue $QUEUE_ID --location $LOCATION_ID --payload hello --in-seconds 30"
```
5 changes: 3 additions & 2 deletions appengine-java8/tasks/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ Copyright 2018 Google LLC
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>

<dependencies>
Expand All @@ -51,7 +52,7 @@ Copyright 2018 Google LLC
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-tasks</artifactId>
<version>0.54.0-beta</version>
<version>0.61.0-beta</version>
</dependency>
<dependency>
<groupId>commons-cli</groupId>
Expand All @@ -69,7 +70,7 @@ Copyright 2018 Google LLC
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>appengine-maven-plugin</artifactId>
<version>1.3.1</version>
<version>1.3.2</version>
<configuration>
<deploy.promote>true</deploy.promote>
<deploy.stopPreviousVersion>true</deploy.stopPreviousVersion>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@

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.cloud.tasks.v2beta3.AppEngineHttpRequest;
import com.google.cloud.tasks.v2beta3.CloudTasksClient;
import com.google.cloud.tasks.v2beta3.HttpMethod;
import com.google.cloud.tasks.v2beta3.QueueName;
import com.google.cloud.tasks.v2beta3.Task;
import com.google.common.base.Strings;
import com.google.protobuf.ByteString;
import com.google.protobuf.Timestamp;
Expand All @@ -38,11 +38,11 @@
import org.apache.commons.cli.ParseException;

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

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.")
.desc("The Google Cloud Project, if not set as PROJECT_ID env var.")
.hasArg()
.argName("project-id")
.type(String.class)
Expand Down Expand Up @@ -109,7 +109,7 @@ public static void main(String... args) throws Exception {
if (params.hasOption("project-id")) {
projectId = params.getOptionValue("project-id");
} else {
projectId = System.getenv(GGOGLE_CLOUD_PROJECT_KEY);
projectId = System.getenv(GOOGLE_CLOUD_PROJECT_KEY);
}
if (Strings.isNullOrEmpty(projectId)) {
printUsage(options);
Expand All @@ -121,22 +121,36 @@ public static void main(String... args) throws Exception {
String payload = params.getOptionValue(PAYLOAD_OPTION.getOpt(), "default payload");

// [START cloud_tasks_appengine_create_task]
// Instantiates a client.
try (CloudTasksClient client = CloudTasksClient.create()) {

// TODO(developer): Uncomment these lines and replace with your values.
// String project = "my-project-id";
Copy link
Member

Choose a reason for hiding this comment

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

Vars should be projectId and queueName to match below if this is kept as is. But uncommenting these lines would be a compile error because these fields are all declared up above. In addition, they are all pulled from CLI opts so the user is presumably already supplying them if they are running the CLI, unless this comment is more aimed at docs readers than people running the sample.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Trying to comprise between the code snippet for the docs and running the sample with the CLI. Changing the comment to "Variables provided by the CLI."

// String queue = "my-appengine-queue";
// String location = "us-central1";
// String payload = "hello";

// Construct the fully qualified queue name.
String queuePath = QueueName.of(projectId, location, queueName).toString();
// Construct the task body.
Task.Builder taskBuilder = Task
.newBuilder()
.setAppEngineHttpRequest(AppEngineHttpRequest.newBuilder()
.setPayload(ByteString.copyFrom(payload, Charset.defaultCharset()))
.setRelativeUrl("/tasks/create")
.setBody(ByteString.copyFrom(payload, Charset.defaultCharset()))
.setRelativeUri("/tasks/create")
.setHttpMethod(HttpMethod.POST)
.build());

if (params.hasOption(IN_SECONDS_OPTION.getOpt())) {
// Add the scheduled time to the request.
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());

// Send create task request.
Task task = client.createTask(queuePath, taskBuilder.build());
System.out.println("Task created: " + task.getName());
}
// [END cloud_tasks_appengine_create_task]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,13 @@ public class TaskServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
log.info("Received task request: " + req.getServletPath());
if (req.getParameter("payload") != null) {
String payload = req.getParameter("payload");
log.info("Request payload: " + payload);
String output = String.format("Received task with payload %s", payload);
String body = req.getReader()
.lines()
.reduce("", (accumulator, actual) -> accumulator + actual);

if (!body.isEmpty()) {
log.info("Request payload: " + body);
String output = String.format("Received task with payload %s", body);
resp.getOutputStream().write(output.getBytes());
log.info("Sending response: " + output);
resp.setStatus(HttpServletResponse.SC_OK);
Expand Down
66 changes: 0 additions & 66 deletions tasks/README.md

This file was deleted.

91 changes: 0 additions & 91 deletions tasks/pom.xml

This file was deleted.

Loading