-
Notifications
You must be signed in to change notification settings - Fork 43
/
TaskList.java
234 lines (218 loc) · 7.59 KB
/
TaskList.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
/*
* 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.
*/
package com.google.datastore.snippets;
import com.google.cloud.Timestamp;
import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.Key;
import com.google.cloud.datastore.KeyFactory;
import com.google.cloud.datastore.Query;
import com.google.cloud.datastore.StringValue;
import com.google.cloud.datastore.StructuredQuery.OrderBy;
import com.google.cloud.datastore.Transaction;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* A simple Task List application demonstrating how to connect to Cloud Datastore, create, modify,
* delete, and query entities.
*/
public class TaskList {
// [START datastore_build_service]
// Create an authorized Datastore service using Application Default Credentials.
private final Datastore datastore = DatastoreOptions.getDefaultInstance().getService();
// Create a Key factory to construct keys associated with this project.
private final KeyFactory keyFactory = datastore.newKeyFactory().setKind("Task");
// [END datastore_build_service]
// [START datastore_add_entity]
/**
* Adds a task entity to the Datastore.
*
* @param description The task description
* @return The {@link Key} of the entity
* @throws DatastoreException if the ID allocation or put fails
*/
Key addTask(String description) {
Key key = datastore.allocateId(keyFactory.newKey());
Entity task = Entity.newBuilder(key)
.set("description", StringValue.newBuilder(description).setExcludeFromIndexes(true).build())
.set("created", Timestamp.now())
.set("done", false)
.build();
datastore.put(task);
return key;
}
// [END datastore_add_entity]
// [START datastore_update_entity]
/**
* Marks a task entity as done.
*
* @param id The ID of the task entity as given by {@link Key#id()}
* @return true if the task was found, false if not
* @throws DatastoreException if the transaction fails
*/
boolean markDone(long id) {
Transaction transaction = datastore.newTransaction();
try {
Entity task = transaction.get(keyFactory.newKey(id));
if (task != null) {
transaction.put(Entity.newBuilder(task).set("done", true).build());
}
transaction.commit();
return task != null;
} finally {
if (transaction.isActive()) {
transaction.rollback();
}
}
}
// [END datastore_update_entity]
// [START datastore_retrieve_entities]
/**
* Returns a list of all task entities in ascending order of creation time.
*
* @throws DatastoreException if the query fails
*/
Iterator<Entity> listTasks() {
Query<Entity> query =
Query.newEntityQueryBuilder().setKind("Task").setOrderBy(OrderBy.asc("created")).build();
return datastore.run(query);
}
// [END datastore_retrieve_entities]
// [START datastore_delete_entity]
/**
* Deletes a task entity.
*
* @param id The ID of the task entity as given by {@link Key#id()}
* @throws DatastoreException if the delete fails
*/
void deleteTask(long id) {
datastore.delete(keyFactory.newKey(id));
}
// [END datastore_delete_entity]
/**
* Converts a list of task entities to a list of formatted task strings.
*
* @param tasks An iterator over task entities
* @return A list of tasks strings, one per entity
*/
static List<String> formatTasks(Iterator<Entity> tasks) {
List<String> strings = new ArrayList<>();
while (tasks.hasNext()) {
Entity task = tasks.next();
if (task.getBoolean("done")) {
strings.add(
String.format("%d : %s (done)", task.getKey().getId(), task.getString("description")));
} else {
strings.add(String.format("%d : %s (created %s)", task.getKey().getId(),
task.getString("description"), task.getTimestamp("created")));
}
}
return strings;
}
/**
* Handles a single command.
*
* @param commandLine A line of input provided by the user
*/
void handleCommandLine(String commandLine) {
String[] args = commandLine.split("\\s+");
if (args.length < 1) {
throw new IllegalArgumentException("not enough args");
}
String command = args[0];
switch (command) {
case "new":
// Everything after the first whitespace token is interpreted to be the description.
args = commandLine.split("\\s+", 2);
if (args.length != 2) {
throw new IllegalArgumentException("missing description");
}
// Set created to now() and done to false.
addTask(args[1]);
System.out.println("task added");
break;
case "done":
assertArgsLength(args, 2);
long id = Long.parseLong(args[1]);
if (markDone(id)) {
System.out.println("task marked done");
} else {
System.out.printf("did not find a Task entity with ID %d%n", id);
}
break;
case "list":
assertArgsLength(args, 1);
List<String> tasks = formatTasks(listTasks());
System.out.printf("found %d tasks:%n", tasks.size());
System.out.println("task ID : description");
System.out.println("---------------------");
for (String taskString : tasks) {
System.out.println(taskString);
}
break;
case "delete":
assertArgsLength(args, 2);
deleteTask(Long.parseLong(args[1]));
System.out.println("task deleted (if it existed)");
break;
default:
throw new IllegalArgumentException("unrecognized command: " + command);
}
}
private void assertArgsLength(String[] args, int expectedLength) {
if (args.length != expectedLength) {
throw new IllegalArgumentException(
String.format("expected exactly %d arg(s), found %d", expectedLength, args.length));
}
}
/**
* Exercises the methods defined in this class.
*
* <p>Assumes that you are authenticated using the Google Cloud SDK (using
* {@code gcloud auth application-default login}).
*/
public static void main(String[] args) throws Exception {
TaskList taskList = new TaskList();
System.out.println("Cloud Datastore Task List");
System.out.println();
printUsage();
while (true) {
String commandLine = System.console().readLine("> ");
if (commandLine.trim().isEmpty()) {
break;
}
try {
taskList.handleCommandLine(commandLine);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
printUsage();
}
}
System.out.println("exiting");
System.exit(0);
}
private static void printUsage() {
System.out.println("Usage:");
System.out.println();
System.out.println(" new <description> Adds a task with a description <description>");
System.out.println(" done <task-id> Marks a task as done");
System.out.println(" list Lists all tasks by creation time");
System.out.println(" delete <task-id> Deletes a task");
System.out.println();
}
}