Java Code Examples for com.google.appengine.api.datastore.DatastoreService#put()
The following examples show how to use
com.google.appengine.api.datastore.DatastoreService#put() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PhotoManagerNoSql.java From solutions-photo-sharing-demo-java with Apache License 2.0 | 6 votes |
@Override public Photo deactivePhoto(String userId, long id) { Utils.assertTrue(userId != null, "user id cannot be null"); DatastoreService ds = getDatastoreService(); Transaction txn = ds.beginTransaction(); try { Entity entity = getDatastoreEntity(ds, createPhotoKey(userId, id)); if (entity != null) { PhotoNoSql photo = new PhotoNoSql(entity); if (photo.isActive()) { photo.setActive(false); ds.put(entity); } txn.commit(); return photo; } } catch (Exception e) { logger.severe("Failed to delete entity from datastore:" + e.getMessage()); } finally { if (txn.isActive()) { txn.rollback(); } } return null; }
Example 2
Source File: TestBase.java From appengine-tck with Apache License 2.0 | 6 votes |
public static Key putTempData(TempData data) { DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); Transaction txn = ds.beginTransaction(TransactionOptions.Builder.withXG(true)); try { Class<? extends TempData> type = data.getClass(); String kind = getKind(type); Entity entity = new Entity(kind); for (Map.Entry<String, Object> entry : data.toProperties(ds).entrySet()) { entity.setProperty(entry.getKey(), entry.getValue()); } entity.setProperty(TEMP_DATA_READ_PROPERTY, false); data.prePut(ds); Key key = ds.put(txn, entity); data.postPut(ds); txn.commit(); return key; } catch (Exception e) { throw new IllegalStateException(e); } finally { if (txn.isActive()) { txn.rollback(); } } }
Example 3
Source File: LocalDatastoreSmoketestServlet.java From appengine-java-vm-runtime with Apache License 2.0 | 6 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); Entity e = new Entity("foo"); e.setProperty("foo", 23); Key key = ds.put(e); try { e = ds.get(key); } catch (EntityNotFoundException e1) { throw new ServletException(e1); } e.setProperty("bar", 44); ds.put(e); Query q = new Query("foo"); q.addFilter("foo", Query.FilterOperator.GREATER_THAN_OR_EQUAL, 22); Iterator<Entity> iter = ds.prepare(q).asIterator(); iter.next(); }
Example 4
Source File: MetadataEntityGroupTest.java From java-docs-samples with Apache License 2.0 | 6 votes |
private static void printEntityGroupVersions(DatastoreService ds, PrintWriter writer) { Entity entity1 = new Entity("Simple"); Key key1 = ds.put(entity1); Key entityGroupKey = Entities.createEntityGroupKey(key1); // Print entity1's entity group version writer.println("version " + getEntityGroupVersion(ds, null, key1)); // Write to a different entity group Entity entity2 = new Entity("Simple"); ds.put(entity2); // Will print the same version, as entity1's entity group has not changed writer.println("version " + getEntityGroupVersion(ds, null, key1)); // Change entity1's entity group by adding a new child entity Entity entity3 = new Entity("Simple", entity1.getKey()); ds.put(entity3); // Will print a higher version, as entity1's entity group has changed writer.println("version " + getEntityGroupVersion(ds, null, key1)); }
Example 5
Source File: PersistingTest.java From appengine-tck with Apache License 2.0 | 6 votes |
@Test public void putStoresEntity() throws Exception { DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); Entity client = new Entity("Client"); client.setProperty("username", "alesj"); client.setProperty("password", "password"); final Key key = ds.put(client); try { Query query = new Query("Client"); query.setFilter(new Query.FilterPredicate("username", Query.FilterOperator.EQUAL, "alesj")); PreparedQuery pq = ds.prepare(query); Entity result = pq.asSingleEntity(); Assert.assertNotNull(result); Assert.assertEquals(key, result.getKey()); Assert.assertEquals("alesj", result.getProperty("username")); Assert.assertEquals("password", result.getProperty("password")); } finally { ds.delete(key); } }
Example 6
Source File: ReadPolicyTest.java From java-docs-samples with Apache License 2.0 | 6 votes |
@Test public void readPolicy_strong_returnsAllResults() { double deadline = 5.0; ReadPolicy policy = new ReadPolicy(ReadPolicy.Consistency.STRONG); DatastoreServiceConfig datastoreConfig = DatastoreServiceConfig.Builder.withReadPolicy(policy).deadline(deadline); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(datastoreConfig); Entity parent = new Entity("Person", "a"); Entity child = new Entity("Person", "b", parent.getKey()); datastore.put(ImmutableList.<Entity>of(parent, child)); Query q = new Query("Person").setAncestor(parent.getKey()); List<Entity> results = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()); assertWithMessage("query results").that(results).hasSize(2); }
Example 7
Source File: TransactionsTest.java From java-docs-samples with Apache License 2.0 | 6 votes |
@Test public void crossGroupTransactions() throws Exception { // [START cross-group_XG_transactions_using_the_Java_low-level_API] DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); TransactionOptions options = TransactionOptions.Builder.withXG(true); Transaction txn = datastore.beginTransaction(options); Entity a = new Entity("A"); a.setProperty("a", 22); datastore.put(txn, a); Entity b = new Entity("B"); b.setProperty("b", 11); datastore.put(txn, b); txn.commit(); // [END cross-group_XG_transactions_using_the_Java_low-level_API] }
Example 8
Source File: SignGuestbookServlet.java From appengine-modules-sample-java with Apache License 2.0 | 6 votes |
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { final UserService userService = UserServiceFactory.getUserService(); final User user = userService.getCurrentUser(); final String guestbookName = req.getParameter("guestbookName"); final Key guestbookKey = KeyFactory.createKey("Guestbook", guestbookName); final String content = req.getParameter("content"); final Date date = new Date(); final Entity greeting = new Entity("Greeting", guestbookKey); greeting.setProperty("user", user); greeting.setProperty("date", date); greeting.setProperty("content", content); final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); datastore.put(greeting); resp.sendRedirect("/guestbook.jsp?guestbookName=" + guestbookName); }
Example 9
Source File: TestMetadataServlet.java From appengine-java-vm-runtime with Apache License 2.0 | 6 votes |
private void populate(DatastoreService ds, String namespace) { NamespaceManager.set(namespace); Entity e = new Entity("Fun"); e.setProperty("me", "yes"); e.setProperty("you", 23); e.setUnindexedProperty("haha", 0); ds.put(e); Entity s = new Entity("Strange"); ArrayList nowhereList = new ArrayList<Integer>(); nowhereList.add(1); nowhereList.add(2); nowhereList.add(3); s.setProperty("nowhere", nowhereList); ds.put(s); Entity s2 = new Entity("Stranger"); s2.setProperty("missing", new ArrayList<Integer>()); ds.put(s2); }
Example 10
Source File: GuestbookStrong.java From java-docs-samples with Apache License 2.0 | 5 votes |
@Override protected Entity createGreeting( DatastoreService datastore, User user, Date date, String content) { // String guestbookName = "my guestbook"; -- Set elsewhere (injected to the constructor). Key guestbookKey = KeyFactory.createKey("Guestbook", guestbookName); // Place greeting in the same entity group as guestbook. Entity greeting = new Entity("Greeting", guestbookKey); greeting.setProperty("user", user); greeting.setProperty("date", date); greeting.setProperty("content", content); datastore.put(greeting); return greeting; }
Example 11
Source File: TestReport.java From appengine-tck with Apache License 2.0 | 5 votes |
/** * Persists {@code this} test report to the given {@link com.google.appengine.api.datastore.DatastoreService} * and invalidate the cache. * * @param reports the reports entry point */ public void save(Reports reports) { final Entity entity = new Entity(TEST_REPORT, buildTypeId + buildId); entity.setProperty("buildTypeId", buildTypeId); entity.setProperty("buildId", buildId); entity.setProperty("buildDate", buildDate); entity.setProperty("buildDuration", buildDuration); entity.setProperty("numberOfPassedTests", numberOfPassedTests); entity.setProperty("numberOfIgnoredTests", numberOfIgnoredTests); entity.setProperty("numberOfFailedTests", numberOfFailedTests); final JSONArray jsonArrayFailedTests = new JSONArray(); for (Test oneFailingTest : failedTests) { jsonArrayFailedTests.put(oneFailingTest.asJson()); } entity.setProperty("failedTests", new Text(jsonArrayFailedTests.toString())); final JSONArray jsonArrayIgnoredTests = new JSONArray(); for (Test oneIgnoredTest : ignoredTests) { jsonArrayIgnoredTests.put(oneIgnoredTest.asJson()); } entity.setProperty("ignoredTests", new Text(jsonArrayIgnoredTests.toString())); final DatastoreService datastoreService = reports.getDatastoreService(); datastoreService.put(entity); final MemcacheService memcacheService = reports.getMemcacheService(); memcacheService.delete(buildTypeId); // invalidate cache }
Example 12
Source File: RemoteApiSharedTests.java From appengine-java-vm-runtime with Apache License 2.0 | 5 votes |
@Override public void run( DatastoreService ds, Supplier<Key> keySupplier, Supplier<Entity> entitySupplier) { Key key = keySupplier.get(); Entity entity = new Entity(key); entity.setProperty("prop1", 75L); ds.put(entity); assertGetEquals(ds, key, entity); ds.delete(key); assertEntityNotFoundException(ds, key); }
Example 13
Source File: Guestbook.java From java-docs-samples with Apache License 2.0 | 5 votes |
@Override protected Entity createGreeting( DatastoreService datastore, User user, Date date, String content) { // No parent key specified, so Greeting is a root entity. Entity greeting = new Entity("Greeting"); greeting.setProperty("user", user); greeting.setProperty("date", date); greeting.setProperty("content", content); datastore.put(greeting); return greeting; }
Example 14
Source File: ReadPolicyTest.java From java-docs-samples with Apache License 2.0 | 5 votes |
@Test public void readPolicy_eventual_returnsNoResults() { // [START data_consistency] double deadline = 5.0; // Construct a read policy for eventual consistency ReadPolicy policy = new ReadPolicy(ReadPolicy.Consistency.EVENTUAL); // Set the read policy DatastoreServiceConfig eventuallyConsistentConfig = DatastoreServiceConfig.Builder.withReadPolicy(policy); // Set the call deadline DatastoreServiceConfig deadlineConfig = DatastoreServiceConfig.Builder.withDeadline(deadline); // Set both the read policy and the call deadline DatastoreServiceConfig datastoreConfig = DatastoreServiceConfig.Builder.withReadPolicy(policy).deadline(deadline); // Get Datastore service with the given configuration DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(datastoreConfig); // [END data_consistency] Entity parent = new Entity("Person", "a"); Entity child = new Entity("Person", "b", parent.getKey()); datastore.put(ImmutableList.<Entity>of(parent, child)); // Even though we are using an ancestor query, the policy is set to // eventual, so we should get eventually-consistent results. Since the // local data store test config is set to 100% unapplied jobs, there // should be no results. Query q = new Query("Person").setAncestor(parent.getKey()); List<Entity> results = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()); assertWithMessage("query results").that(results).isEmpty(); }
Example 15
Source File: IndexesTest.java From java-docs-samples with Apache License 2.0 | 5 votes |
@Test public void propertyFilterExample_returnsMatchingEntities() throws Exception { // [START unindexed_properties_1] DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key acmeKey = KeyFactory.createKey("Company", "Acme"); Entity tom = new Entity("Person", "Tom", acmeKey); tom.setProperty("name", "Tom"); tom.setProperty("age", 32); datastore.put(tom); Entity lucy = new Entity("Person", "Lucy", acmeKey); lucy.setProperty("name", "Lucy"); lucy.setUnindexedProperty("age", 29); datastore.put(lucy); Filter ageFilter = new FilterPredicate("age", FilterOperator.GREATER_THAN, 25); Query q = new Query("Person").setAncestor(acmeKey).setFilter(ageFilter); // Returns tom but not lucy, because her age is unindexed List<Entity> results = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()); // [END unindexed_properties_1] assertWithMessage("query results").that(results).containsExactly(tom); }
Example 16
Source File: LocalDatastoreTest.java From java-docs-samples with Apache License 2.0 | 5 votes |
private void doTest() { DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); assertEquals(0, ds.prepare(new Query("yam")).countEntities(withLimit(10))); ds.put(new Entity("yam")); ds.put(new Entity("yam")); assertEquals(2, ds.prepare(new Query("yam")).countEntities(withLimit(10))); }
Example 17
Source File: LocalCustomPolicyHighRepDatastoreTest.java From java-docs-samples with Apache License 2.0 | 5 votes |
@Test public void testEventuallyConsistentGlobalQueryResult() { DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); ds.put(new Entity("yam")); // applies ds.put(new Entity("yam")); // does not apply // First global query only sees the first Entity. assertEquals(1, ds.prepare(new Query("yam")).countEntities(withLimit(10))); // Second global query sees both Entities because we "groom" (attempt to // apply unapplied jobs) after every query. assertEquals(2, ds.prepare(new Query("yam")).countEntities(withLimit(10))); }
Example 18
Source File: AppEngineCredentialStore.java From google-oauth-java-client with Apache License 2.0 | 5 votes |
@Override public void store(String userId, Credential credential) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Entity entity = new Entity(KIND, userId); entity.setProperty("accessToken", credential.getAccessToken()); entity.setProperty("refreshToken", credential.getRefreshToken()); entity.setProperty("expirationTimeMillis", credential.getExpirationTimeMilliseconds()); datastore.put(entity); }
Example 19
Source File: ReceiveMessageServlet.java From cloud-pubsub-samples-java with Apache License 2.0 | 5 votes |
@Override @SuppressWarnings("unchecked") public final void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { // Validating unique subscription token before processing the message String subscriptionToken = System.getProperty( Constants.BASE_PACKAGE + ".subscriptionUniqueToken"); if (!subscriptionToken.equals(req.getParameter("token"))) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); resp.getWriter().close(); return; } ServletInputStream inputStream = req.getInputStream(); // Parse the JSON message to the POJO model class JsonParser parser = JacksonFactory.getDefaultInstance() .createJsonParser(inputStream); parser.skipToKey("message"); PubsubMessage message = parser.parseAndClose(PubsubMessage.class); // Store the message in the datastore Entity messageToStore = new Entity("PubsubMessage"); messageToStore.setProperty("message", new String(message.decodeData(), "UTF-8")); messageToStore.setProperty("receipt-time", System.currentTimeMillis()); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); datastore.put(messageToStore); // Invalidate the cache MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService(); memcacheService.delete(Constants.MESSAGE_CACHE_KEY); // Acknowledge the message by returning a success code resp.setStatus(HttpServletResponse.SC_OK); resp.getWriter().close(); }
Example 20
Source File: RemoteApiSharedTests.java From appengine-java-vm-runtime with Apache License 2.0 | 4 votes |
@Override public void run( DatastoreService ds, Supplier<Key> keySupplier, Supplier<Entity> entitySupplier) { Entity entity1 = new Entity(keySupplier.get()); entity1.setProperty("prop1", 75L); // Verify results of Put Key keyReturnedFromPut = ds.put(entity1); assertEquals(entity1.getKey(), keyReturnedFromPut); // Make sure we can retrieve it again. assertGetEquals(ds, keyReturnedFromPut, entity1); // Test EntityNotFoundException Key unsavedKey = keySupplier.get(); assertEntityNotFoundException(ds, unsavedKey); // Test batch get Entity entity2 = new Entity(keySupplier.get()); entity2.setProperty("prop1", 88L); ds.put(entity2); Map<Key, Entity> batchGetResult = ds.get(Arrays.asList(entity1.getKey(), unsavedKey, entity2.getKey())); // Omits the unsaved key from results. assertEquals(2, batchGetResult.size()); assertEquals(entity1, batchGetResult.get(entity1.getKey())); assertEquals(entity2, batchGetResult.get(entity2.getKey())); // Test Put and Get with id generated by Datastore backend. Entity entity3 = entitySupplier.get(); entity3.setProperty("prop1", 35L); assertNoIdOrName(entity3.getKey()); Key assignedKey = ds.put(entity3); assertTrue(assignedKey.getId() > 0); assertEquals(assignedKey, entity3.getKey()); assertGetEquals(ds, assignedKey, entity3); }