1 /* 2 * Copyright 2016 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 /* 18 * EDITING INSTRUCTIONS 19 * This file is referenced in Datastore's javadoc. Any change to this file should be reflected in 20 * Datastore's javadoc. 21 */ 22 23 package com.google.cloud.examples.datastore.snippets; 24 25 import com.google.cloud.datastore.Batch; 26 import com.google.cloud.datastore.Datastore; 27 import com.google.cloud.datastore.Datastore.TransactionCallable; 28 import com.google.cloud.datastore.DatastoreException; 29 import com.google.cloud.datastore.DatastoreReaderWriter; 30 import com.google.cloud.datastore.Entity; 31 import com.google.cloud.datastore.IncompleteKey; 32 import com.google.cloud.datastore.Key; 33 import com.google.cloud.datastore.KeyFactory; 34 import com.google.cloud.datastore.Query; 35 import com.google.cloud.datastore.QueryResults; 36 import com.google.cloud.datastore.StructuredQuery; 37 import com.google.cloud.datastore.StructuredQuery.PropertyFilter; 38 import com.google.common.collect.Lists; 39 import java.util.Iterator; 40 import java.util.List; 41 42 /** This class contains a number of snippets for the {@link Datastore} interface. */ 43 public class DatastoreSnippets { 44 45 private final Datastore datastore; 46 DatastoreSnippets(Datastore datastore)47 public DatastoreSnippets(Datastore datastore) { 48 this.datastore = datastore; 49 } 50 51 /** Example of running in a transaction. */ 52 // [TARGET runInTransaction(TransactionCallable)] 53 // [VARIABLE "my_callable_result"] runInTransaction(final String callableResult)54 public String runInTransaction(final String callableResult) { 55 // [START runInTransaction] 56 TransactionCallable<String> callable = 57 new TransactionCallable<String>() { 58 public String run(DatastoreReaderWriter readerWriter) { 59 // use readerWriter to run in transaction 60 return callableResult; 61 } 62 }; 63 String result = datastore.runInTransaction(callable); 64 // [END runInTransaction] 65 return result; 66 } 67 68 /** Example of starting a new batch. */ 69 // [TARGET newBatch()] 70 // [VARIABLE "my_key_name_1"] 71 // [VARIABLE "my_key_name_2"] newBatch(String keyName1, String keyName2)72 public Batch newBatch(String keyName1, String keyName2) { 73 // [START newBatch] 74 Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1); 75 Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2); 76 Batch batch = datastore.newBatch(); 77 Entity entity1 = Entity.newBuilder(key1).set("name", "John").build(); 78 Entity entity2 = Entity.newBuilder(key2).set("title", "title").build(); 79 batch.add(entity1); 80 batch.add(entity2); 81 batch.submit(); 82 // [END newBatch] 83 return batch; 84 } 85 86 /** Example of allocating an id. */ 87 // [TARGET allocateId(IncompleteKey)] allocateIdSingle()88 public Key allocateIdSingle() { 89 // [START allocateIdSingle] 90 KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); 91 IncompleteKey incompleteKey = keyFactory.newKey(); 92 93 // let cloud datastore automatically assign an id 94 Key key = datastore.allocateId(incompleteKey); 95 // [END allocateIdSingle] 96 return key; 97 } 98 99 /** Example of allocating multiple ids in a single batch. */ 100 // [TARGET allocateId(IncompleteKey...)] batchAllocateId()101 public List<Key> batchAllocateId() { 102 // [START batchAllocateId] 103 KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); 104 IncompleteKey incompleteKey1 = keyFactory.newKey(); 105 IncompleteKey incompleteKey2 = keyFactory.newKey(); 106 107 // let cloud datastore automatically assign the ids 108 List<Key> keys = datastore.allocateId(incompleteKey1, incompleteKey2); 109 // [END batchAllocateId] 110 return keys; 111 } 112 113 /** Example of updating multiple entities. */ 114 // [TARGET update(Entity...)] 115 // [VARIABLE "my_key_name_1"] 116 // [VARIABLE "my_key_name_2"] batchUpdateEntities(String keyName1, String keyName2)117 public void batchUpdateEntities(String keyName1, String keyName2) { 118 // [START batchUpdateEntities] 119 Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1); 120 Entity.Builder entityBuilder1 = Entity.newBuilder(key1); 121 entityBuilder1.set("propertyName", "updatedValue1"); 122 Entity entity1 = entityBuilder1.build(); 123 124 Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2); 125 Entity.Builder entityBuilder2 = Entity.newBuilder(key2); 126 entityBuilder2.set("propertyName", "updatedValue2"); 127 Entity entity2 = entityBuilder2.build(); 128 129 datastore.update(entity1, entity2); 130 // [END batchUpdateEntities] 131 } 132 133 /** Example of adding a single entity. */ 134 // [TARGET add(FullEntity)] 135 // [VARIABLE "my_key_name"] addSingleEntity(String keyName)136 public void addSingleEntity(String keyName) { 137 // [START addSingleEntity] 138 Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName); 139 Entity.Builder entityBuilder = Entity.newBuilder(key); 140 entityBuilder.set("propertyName", "value"); 141 Entity entity = entityBuilder.build(); 142 try { 143 datastore.add(entity); 144 } catch (DatastoreException ex) { 145 if ("ALREADY_EXISTS".equals(ex.getReason())) { 146 // entity.getKey() already exists 147 } 148 } 149 // [END addSingleEntity] 150 } 151 152 /** Example of adding multiple entities. */ 153 // [TARGET add(FullEntity...)] 154 // [VARIABLE "my_key_name1"] 155 // [VARIABLE "my_key_name2"] batchAddEntities(String keyName1, String keyName2)156 public void batchAddEntities(String keyName1, String keyName2) { 157 // [START batchAddEntities] 158 Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1); 159 Entity.Builder entityBuilder1 = Entity.newBuilder(key1); 160 entityBuilder1.set("propertyName", "value1"); 161 Entity entity1 = entityBuilder1.build(); 162 163 Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2); 164 Entity.Builder entityBuilder2 = Entity.newBuilder(key2); 165 entityBuilder2.set("propertyName", "value2"); 166 Entity entity2 = entityBuilder2.build(); 167 168 try { 169 datastore.add(entity1, entity2); 170 } catch (DatastoreException ex) { 171 if ("ALREADY_EXISTS".equals(ex.getReason())) { 172 // at least one of entity1.getKey() and entity2.getKey() already exists 173 } 174 } 175 // [END batchAddEntities] 176 } 177 178 /** Example of putting a single entity. */ 179 // [TARGET put(FullEntity)] 180 // [VARIABLE "my_key_name"] putSingleEntity(String keyName)181 public void putSingleEntity(String keyName) { 182 // [START putSingleEntity] 183 Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName); 184 Entity.Builder entityBuilder = Entity.newBuilder(key); 185 entityBuilder.set("propertyName", "value"); 186 Entity entity = entityBuilder.build(); 187 datastore.put(entity); 188 // [END putSingleEntity] 189 } 190 191 /** Example of putting multiple entities. */ 192 // [TARGET put(FullEntity...)] 193 // [VARIABLE "my_key_name1"] 194 // [VARIABLE "my_key_name2"] batchPutEntities(String keyName1, String keyName2)195 public void batchPutEntities(String keyName1, String keyName2) { 196 // [START batchPutEntities] 197 Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1); 198 Entity.Builder entityBuilder1 = Entity.newBuilder(key1); 199 entityBuilder1.set("propertyName", "value1"); 200 Entity entity1 = entityBuilder1.build(); 201 202 Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2); 203 Entity.Builder entityBuilder2 = Entity.newBuilder(key2); 204 entityBuilder2.set("propertyName", "value2"); 205 Entity entity2 = entityBuilder2.build(); 206 207 datastore.put(entity1, entity2); 208 // [END batchPutEntities] 209 } 210 211 /** Example of deleting multiple entities. */ 212 // [TARGET delete(Key...)] 213 // [VARIABLE "my_key_name1"] 214 // [VARIABLE "my_key_name2"] batchDeleteEntities(String keyName1, String keyName2)215 public void batchDeleteEntities(String keyName1, String keyName2) { 216 // [START batchDeleteEntities] 217 Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1); 218 Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2); 219 datastore.delete(key1, key2); 220 // [END batchDeleteEntities] 221 } 222 223 /** Example of creating a {@code KeyFactory}. */ 224 // [TARGET newKeyFactory()] createKeyFactory()225 public KeyFactory createKeyFactory() { 226 // [START createKeyFactory] 227 KeyFactory keyFactory = datastore.newKeyFactory(); 228 // [END createKeyFactory] 229 return keyFactory; 230 } 231 232 /** Example of getting an entity. */ 233 // [TARGET get(Key, ReadOption...)] 234 // [VARIABLE "my_key_name"] getEntityWithKey(String keyName)235 public Entity getEntityWithKey(String keyName) { 236 // [START getEntityWithKey] 237 Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName); 238 Entity entity = datastore.get(key); 239 // Do something with the entity 240 // [END getEntityWithKey] 241 return entity; 242 } 243 244 /** Example of getting multiple entity objects. */ 245 // [TARGET get(Iterable, ReadOption...)] 246 // [VARIABLE "my_first_key_name"] 247 // [VARIABLE "my_second_key_name"] getEntitiesWithKeys(String firstKeyName, String secondKeyName)248 public List<Entity> getEntitiesWithKeys(String firstKeyName, String secondKeyName) { 249 // TODO change so that it's not necessary to hold the entities in a list for integration testing 250 // [START getEntitiesWithKeys] 251 KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); 252 Key firstKey = keyFactory.newKey(firstKeyName); 253 Key secondKey = keyFactory.newKey(secondKeyName); 254 Iterator<Entity> entitiesIterator = datastore.get(Lists.newArrayList(firstKey, secondKey)); 255 List<Entity> entities = Lists.newArrayList(); 256 while (entitiesIterator.hasNext()) { 257 Entity entity = entitiesIterator.next(); 258 // do something with the entity 259 entities.add(entity); 260 } 261 // [END getEntitiesWithKeys] 262 return entities; 263 } 264 265 /** Example of fetching a list of Entity objects. */ 266 // [TARGET fetch(Iterable, ReadOption...)] 267 // [VARIABLE "my_first_key_name"] 268 // [VARIABLE "my_second_key_name"] fetchEntitiesWithKeys(String firstKeyName, String secondKeyName)269 public List<Entity> fetchEntitiesWithKeys(String firstKeyName, String secondKeyName) { 270 // [START fetchEntitiesWithKeys] 271 KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); 272 Key firstKey = keyFactory.newKey(firstKeyName); 273 Key secondKey = keyFactory.newKey(secondKeyName); 274 List<Entity> entities = datastore.fetch(Lists.newArrayList(firstKey, secondKey)); 275 for (Entity entity : entities) { 276 // do something with the entity 277 } 278 // [END fetchEntitiesWithKeys] 279 return entities; 280 } 281 282 /** Example of running a query to find all entities of one kind. */ 283 // [TARGET run(Query, ReadOption...)] 284 // [VARIABLE "my_kind"] runQuery(String kind)285 public List<Entity> runQuery(String kind) { 286 // TODO change so that it's not necessary to hold the entities in a list for integration testing 287 // [START runQuery] 288 StructuredQuery<Entity> query = Query.newEntityQueryBuilder().setKind(kind).build(); 289 QueryResults<Entity> results = datastore.run(query); 290 List<Entity> entities = Lists.newArrayList(); 291 while (results.hasNext()) { 292 Entity result = results.next(); 293 // do something with result 294 entities.add(result); 295 } 296 // [END runQuery] 297 return entities; 298 } 299 300 /** Example of running a query to find all entities with a matching property value. */ 301 // [TARGET run(Query, ReadOption...)] 302 // [VARIABLE "my_kind"] 303 // [VARIABLE "my_property"] 304 // [VARIABLE "my_value"] runQueryOnProperty(String kind, String property, String value)305 public List<Entity> runQueryOnProperty(String kind, String property, String value) { 306 // TODO change so that it's not necessary to hold the entities in a list for integration testing 307 // [START runQueryOnProperty] 308 StructuredQuery<Entity> query = 309 Query.newEntityQueryBuilder() 310 .setKind(kind) 311 .setFilter(PropertyFilter.eq(property, value)) 312 .build(); 313 QueryResults<Entity> results = datastore.run(query); 314 List<Entity> entities = Lists.newArrayList(); 315 while (results.hasNext()) { 316 Entity result = results.next(); 317 // do something with result 318 entities.add(result); 319 } 320 // [END runQueryOnProperty] 321 return entities; 322 } 323 } 324