com.google.appengine.api.datastore.EntityNotFoundException Java Examples

The following examples show how to use com.google.appengine.api.datastore.EntityNotFoundException. 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: AppEngineBackEnd.java    From appengine-pipelines with Apache License 2.0 6 votes vote down vote up
private Entity getEntity(String logString, final Key key) throws NoSuchObjectException {
  try {
    return tryFiveTimes(new Operation<Entity>(logString) {
      @Override
      public Entity call() throws EntityNotFoundException  {
          return dataStore.get(null, key);
      }
    });
  } catch (NonRetriableException|RetriesExhaustedException e) {
    Throwable cause = e.getCause();
    if (cause instanceof EntityNotFoundException) {
      throw new NoSuchObjectException(key.toString(), cause);
    } else {
      throw e;
    }
  }
}
 
Example #2
Source File: EntitiesTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void deletingAnEntity_deletesAnEntity() throws Exception {
  Entity employee = new Entity("Employee", "asalieri");
  datastore.put(employee);

  Key employeeKey = KeyFactory.createKey("Employee", "asalieri");
  // [START deleting_an_entity]
  // Key employeeKey = ...;
  datastore.delete(employeeKey);
  // [END deleting_an_entity]

  try {
    Entity got = datastore.get(employeeKey);
    fail("Expected EntityNotFoundException");
  } catch (EntityNotFoundException expected) {
    assertWithMessage("exception key name")
        .that(expected.getKey().getName())
        .isEqualTo("asalieri");
  }
}
 
Example #3
Source File: LocalRawGcsService.java    From appengine-gcs-client with Apache License 2.0 6 votes vote down vote up
@Override
public boolean deleteObject(GcsFilename filename, long timeoutMillis) throws IOException {
  ensureInitialized();
  Transaction tx = datastore.beginTransaction();
  Key key = makeKey(filename);
  try {
    datastore.get(tx, key);
    datastore.delete(tx, key);
    blobstoreService.delete(getBlobKeyForFilename(filename));
  } catch (EntityNotFoundException ex) {
    return false;
  } finally {
    if (tx.isActive()) {
      tx.commit();
    }
  }

  return true;
}
 
Example #4
Source File: LocalRawGcsService.java    From appengine-gcs-client with Apache License 2.0 6 votes vote down vote up
@Override
public GcsFileMetadata getObjectMetadata(GcsFilename filename, long timeoutMillis)
    throws IOException {
  ensureInitialized();
  Entity entity;
  try {
    entity = datastore.get(null, makeKey(filename));
    return createGcsFileMetadata(entity, filename);
  } catch (EntityNotFoundException ex1) {
    try {
      entity = datastore.get(null, makeBlobstoreKey(filename));
      return createGcsFileMetadataFromBlobstore(entity, filename);
    } catch (EntityNotFoundException ex2) {
      return null;
    }
  }
}
 
Example #5
Source File: SessionManagerTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void testNewSession() throws EntityNotFoundException {
  assertTrue(manager.getSessionIdManager() instanceof SessionManager.SessionIdManager);
  manager.setMaxInactiveInterval(SESSION_EXPIRATION_SECONDS);

  HttpServletRequest request = makeMockRequest(true);
  replay(request);

  AppEngineSession session = manager.newSession(request);
  assertNotNull(session);
  assertTrue(session instanceof SessionManager.AppEngineSession);
  assertEquals(SessionManager.lastId(), session.getId());

  session.setAttribute("foo", "bar");
  session.save();
}
 
Example #6
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
/**
 * Delete a value stored in the project's datastore.
 * @param sessionId Request from which the session is extracted.
 */
protected void deleteSessionVariables(String sessionId, String... varNames) {
  if (sessionId.equals("")) {
    return;
  }
  Key key = KeyFactory.createKey(SESSION_KIND, sessionId);
  Transaction transaction = datastore.beginTransaction();
  try {
    Entity stateEntity = datastore.get(transaction, key);
    for (String varName : varNames) {
      stateEntity.removeProperty(varName);
    }
    datastore.put(transaction, stateEntity);
    transaction.commit();
  } catch (EntityNotFoundException e) {
    // Ignore - if there's no session, there's nothing to delete.
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example #7
Source File: TransactionTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleDefault() throws EntityNotFoundException, InterruptedException {
    clearData(kindName);
    Transaction tx = service.beginTransaction();
    Entity newRec = new Entity(kindName);
    newRec.setProperty("check", "4100331");
    newRec.setProperty("step", "added");
    Key key = service.put(tx, newRec);
    tx.commit();
    Entity qRec = service.get(key);
    assertEquals("4100331", qRec.getProperty("check"));

    tx = service.beginTransaction();
    qRec = service.get(key);
    qRec.setUnindexedProperty("step", "update");
    service.put(tx, newRec);
    tx.rollback();
    qRec = service.get(key);
    assertEquals("added", qRec.getProperty("step"));
}
 
Example #8
Source File: TransactionsTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
private void assertRollbackSucceedsWhenResultFetchedWith(ResultFetcher resultFetcher) throws EntityNotFoundException {
    String methodName = "assertRollbackSucceedsWhenResultFetchedWith";
    Entity entity = createTestEntityWithUniqueMethodNameKey(TRANSACTION_TEST_ENTITY, methodName);
    Key parentKey = entity.getKey();
    entity.setProperty("name", "original");
    Key key = service.put(entity);
    try {
        Transaction tx = service.beginTransaction();
        PreparedQuery preparedQuery = service.prepare(new Query(TRANSACTION_TEST_ENTITY).setAncestor(parentKey));
        Entity entity2 = resultFetcher.fetchResult(preparedQuery);
        entity2.setProperty("name", "modified");
        service.put(tx, entity2);
        tx.rollback();

        Entity entity3 = service.get(key);
        assertEquals("original", entity3.getProperty("name"));
    } finally {
        service.delete(entity.getKey());
    }
}
 
Example #9
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
/**
 * Delete a value stored in the project's datastore.
 * @param sessionId Request from which the session is extracted.
 */
protected void deleteSessionVariables(String sessionId, String... varNames) {
  if (sessionId.equals("")) {
    return;
  }
  Key key = KeyFactory.createKey(SESSION_KIND, sessionId);
  Transaction transaction = datastore.beginTransaction();
  try {
    Entity stateEntity = datastore.get(transaction, key);
    for (String varName : varNames) {
      stateEntity.removeProperty(varName);
    }
    datastore.put(transaction, stateEntity);
    transaction.commit();
  } catch (EntityNotFoundException e) {
    // Ignore - if there's no session, there's nothing to delete.
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example #10
Source File: DeviceSubscription.java    From solutions-mobile-backend-starter-java with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an entity with device subscription information from memcache or datastore based on the
 *     provided deviceId.
 *
 * @param deviceId A unique device identifier
 * @return an entity with device subscription information; or null when no corresponding
 *         information found
 */
public Entity get(String deviceId) {
  if (StringUtility.isNullOrEmpty(deviceId)) {
    throw new IllegalArgumentException("DeviceId cannot be null or empty");
  }
  Key key = getKey(deviceId);
  Entity entity = (Entity) this.memcacheService.get(key);

  // Get from datastore if unable to get data from cache
  if (entity == null) {
    try {
      entity = this.datastoreService.get(key);
    } catch (EntityNotFoundException e) {
      return null;
    }
  }

  return entity;
}
 
Example #11
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
/**
 * Delete a value stored in the project's datastore.
 * @param sessionId Request from which the session is extracted.
 */
protected void deleteSessionVariables(String sessionId, String... varNames) {
  if (sessionId.equals("")) {
    return;
  }
  Key key = KeyFactory.createKey(SESSION_KIND, sessionId);
  Transaction transaction = datastore.beginTransaction();
  try {
    Entity stateEntity = datastore.get(transaction, key);
    for (String varName : varNames) {
      stateEntity.removeProperty(varName);
    }
    datastore.put(transaction, stateEntity);
    transaction.commit();
  } catch (EntityNotFoundException e) {
    // Ignore - if there's no session, there's nothing to delete.
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example #12
Source File: LocalDatastoreSmoketestServlet.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
@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 #13
Source File: SessionManagerTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
public void testSessionNotAvailableInMemcache() throws EntityNotFoundException {
  HttpServletRequest request = makeMockRequest(true);
  replay(request);
  AppEngineSession session = manager.newSession(request);
  session.setAttribute("foo", "bar");
  session.save();

  memcache.clearAll();
  manager =
      new SessionManager(Arrays.asList(new DatastoreSessionStore(), new MemcacheSessionStore()));
  HttpSession session2 = manager.getSession(session.getId());
  assertEquals(session.getId(), session2.getId());
  assertEquals("bar", session2.getAttribute("foo"));

  manager =
      new SessionManager(Collections.<SessionStore>singletonList(new MemcacheSessionStore()));
  assertNull(manager.getSession(session.getId()));
}
 
Example #14
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
/**
 * Delete a value stored in the project's datastore.
 * @param sessionId Request from which the session is extracted.
 */
protected void deleteSessionVariables(String sessionId, String... varNames) {
  if (sessionId.equals("")) {
    return;
  }
  Key key = KeyFactory.createKey(SESSION_KIND, sessionId);
  Transaction transaction = datastore.beginTransaction();
  try {
    Entity stateEntity = datastore.get(transaction, key);
    for (String varName : varNames) {
      stateEntity.removeProperty(varName);
    }
    datastore.put(transaction, stateEntity);
    transaction.commit();
  } catch (EntityNotFoundException e) {
    // Ignore - if there's no session, there's nothing to delete.
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example #15
Source File: DeviceSubscription.java    From io2014-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an entity with device subscription information from memcache or datastore based on the
 *     provided deviceId.
 *
 * @param deviceId A unique device identifier
 * @return an entity with device subscription information; or null when no corresponding
 *         information found
 */
public Entity get(String deviceId) {
  if (StringUtility.isNullOrEmpty(deviceId)) {
    throw new IllegalArgumentException("DeviceId cannot be null or empty");
  }
  Key key = getKey(deviceId);
  Entity entity = (Entity) this.memcacheService.get(key);

  // Get from datastore if unable to get data from cache
  if (entity == null) {
    try {
      entity = this.datastoreService.get(key);
    } catch (EntityNotFoundException e) {
      return null;
    }
  }

  return entity;
}
 
Example #16
Source File: RequestLogsTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(20)
public void testRequestLogsAreSortedNewestFirst() throws EntityNotFoundException {
    LogQuery query = new LogQuery().startTimeMillis(System.currentTimeMillis() - 60000);
    Iterator<RequestLogs> iterator = findLogLine(query, 3);

    Long previousEndTimeUsec = null;
    while (iterator.hasNext()) {
        RequestLogs requestLogs = iterator.next();
        long endTimeUsec = requestLogs.getEndTimeUsec();
        if (previousEndTimeUsec != null) {
            assertTrue(
                "RequestLogs with endTimeUsec " + endTimeUsec + " was returned after RequestLogs with endTimeUsec " + previousEndTimeUsec,
                previousEndTimeUsec >= endTimeUsec);
        }
        previousEndTimeUsec = endTimeUsec;
    }
}
 
Example #17
Source File: SessionManagerTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
 public void testDatastoreTimeouts() throws EntityNotFoundException {
   Delegate original = ApiProxy.getDelegate();
   // Throw in a couple of datastore timeouts
   TimeoutGeneratingDelegate newDelegate = new TimeoutGeneratingDelegate(original);
   try {
     ApiProxy.setDelegate(newDelegate);

     HttpServletRequest request = makeMockRequest(true);
        replay(request);
AppEngineSession session = manager.newSession(request);
     session.setAttribute("foo", "bar");
     newDelegate.setTimeouts(3);
     session.save();
     assertEquals(newDelegate.getTimeoutsRemaining(), 0);

     memcache.clearAll();
     manager =
         new SessionManager(Collections.<SessionStore>singletonList(new DatastoreSessionStore()));
     HttpSession session2 = manager.getSession(session.getId());
     assertEquals(session.getId(), session2.getId());
     assertEquals("bar", session2.getAttribute("foo"));
   } finally {
     ApiProxy.setDelegate(original);
   }
 }
 
Example #18
Source File: DemoEntityManagerNoSql.java    From solutions-photo-sharing-demo-java with Apache License 2.0 5 votes vote down vote up
/**
 * Looks up an entity by key.
 *
 * @param ds the datastore service objct.
 * @param key the entity key.
 * @return the entity; null if the key could not be found.
 */
protected Entity getDatastoreEntity(DatastoreService ds, Key key) {
  try {
    return ds.get(key);
  } catch (EntityNotFoundException e) {
    logger.fine("No entity found:" + key.toString());
  }
  return null;
}
 
Example #19
Source File: ShardedCounter.java    From appengine-modules-sample-java with Apache License 2.0 5 votes vote down vote up
/**
 * Get the number of shards in this counter.
 *
 * @return shard count
 */
public int getShardCount() {
  try {
    final Key counterKey = KeyFactory.createKey(Counter.KIND, counterName);
    final Entity counter = ds.get(counterKey);
    final Long shardCount = (Long) counter.getProperty(Counter.SHARD_COUNT);
    return shardCount.intValue();
  } catch (EntityNotFoundException ignore) {
    return INITIAL_SHARDS;
  }
}
 
Example #20
Source File: ShardedCounter.java    From appengine-sharded-counters-java with Apache License 2.0 5 votes vote down vote up
/**
 * Get the number of shards in this counter.
 *
 * @return shard count
 */
private int getShardCount() {
    try {
        Key counterKey = KeyFactory.createKey(Counter.KIND, counterName);
        Entity counter = DS.get(counterKey);
        Long shardCount = (Long) counter.getProperty(Counter.SHARD_COUNT);
        return shardCount.intValue();
    } catch (EntityNotFoundException ignore) {
        return INITIAL_SHARDS;
    }
}
 
Example #21
Source File: SimpleXmppTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
private Entity pollForChatWithTimeout(int timeoutInSeconds) {
    Key testChatKey = KeyFactory.createKey("XmppMsg", "test");
    Entity chatMsg = null;
    while (timeoutInSeconds-- > 0) {
        try {
            chatMsg = datastoreService.get(testChatKey);
            break;
        } catch (EntityNotFoundException enfe) {
            sync();
        }
    }
    return chatMsg;
}
 
Example #22
Source File: KeyTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testKeySerialization() throws EntityNotFoundException, IOException {
    Key parentKeyB = KeyFactory.createKey("family", "same");
    Key childKeyB = KeyFactory.createKey(parentKeyB, "children", "same");
    Entity entB1 = new Entity(childKeyB);
    service.put(entB1);

    Entity entB2 = service.get(childKeyB);
    assertEquals(new String(MemcacheSerialization.makePbKey(entB1.getKey())),
        new String(MemcacheSerialization.makePbKey(childKeyB)));
    assertEquals(new String(MemcacheSerialization.makePbKey(entB2.getKey())),
        new String(MemcacheSerialization.makePbKey(childKeyB)));
    service.delete(childKeyB);
    service.delete(parentKeyB);
}
 
Example #23
Source File: SchemaTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testEntityGroupMetadata() throws EntityNotFoundException {
    if (service.getDatastoreAttributes().getDatastoreType() == DatastoreAttributes.DatastoreType.HIGH_REPLICATION) {
        NamespaceManager.set(namespaceDat[2]);
        Entity entity1 = new Entity(kindDat[2]);
        entity1.setProperty("name", "entity1");
        entity1.setProperty("timestamp", new Date());
        Key k1 = service.put(entity1);
        Key entityGroupKey = Entities.createEntityGroupKey(k1);
        long version1 = Entities.getVersionProperty(service.get(entityGroupKey));

        Entity entity2 = new Entity(kindDat[2]);
        entity2.setProperty("name", "entity2");
        entity2.setProperty("timestamp", new Date());
        service.put(entity2);
        // Get entity1's version again.  There should be no change.
        long version2 = Entities.getVersionProperty(service.get(entityGroupKey));
        assertEquals(version1, version2);

        Entity entity3 = new Entity(kindDat[2], k1);
        entity3.setProperty("name", "entity3");
        entity3.setProperty("timestamp", new Date());
        service.put(entity3);
        // Get entity1's version again.  There should be change since it is used as parent.
        long version3 = Entities.getVersionProperty(service.get(entityGroupKey));
        assertTrue(version3 > version1);
        // clean test data
        service.delete(entity3.getKey(), entity2.getKey(), k1);
    }
}
 
Example #24
Source File: CloudEndpointsConfigManager.java    From solutions-mobile-backend-starter-java with Apache License 2.0 5 votes vote down vote up
private Entity getEndpointEntity(Class<?> endpointClass) {
  Key key = KeyFactory.createKey(ENDPOINT_CONFIGURATION_KIND,
      endpointClass.getSimpleName());
  try {
    return datastoreService.get(key);
  } catch (EntityNotFoundException e) {
    return new Entity(key);
  }
}
 
Example #25
Source File: DatastoreHelperTestBase.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
protected void assertStoreDoesNotContain(Key key) throws EntityNotFoundException {
    try {
        Entity storedEntity = service.get(key);
        Assert.fail("expected the datastore not to contain anything under key " + key + ", but it contained the entity " + storedEntity);
    } catch (EntityNotFoundException e) {
        // pass
    }
}
 
Example #26
Source File: BlobManager.java    From solutions-mobile-backend-starter-java with Apache License 2.0 5 votes vote down vote up
/**
 * Gets blob metadata.
 *
 * @param bucketName Google Cloud Storage bucket where the object was uploaded.
 * @param objectPath path to the object in the bucket.
 * @return blob metadata or null if there is no object for this objectPath and bucketName.
 */
public static BlobMetadata getBlobMetadata(String bucketName, String objectPath) {
  try {
    Entity metadataEntity =
        dataStore.get(BlobMetadata.getKey(getCanonicalizedResource(bucketName, objectPath)));
    return new BlobMetadata(metadataEntity);
  } catch (EntityNotFoundException e) {
    return null;
  }
}
 
Example #27
Source File: AppEngineCredentialStore.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
@Override
public boolean load(String userId, Credential credential) {
  DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
  Key key = KeyFactory.createKey(KIND, userId);
  try {
    Entity entity = datastore.get(key);
    credential.setAccessToken((String) entity.getProperty("accessToken"));
    credential.setRefreshToken((String) entity.getProperty("refreshToken"));
    credential.setExpirationTimeMilliseconds((Long) entity.getProperty("expirationTimeMillis"));
    return true;
  } catch (EntityNotFoundException exception) {
    return false;
  }
}
 
Example #28
Source File: CloudEndpointsConfigManager.java    From io2014-codelabs with Apache License 2.0 5 votes vote down vote up
private Entity getEndpointEntity(Class<?> endpointClass) {
  Key key = KeyFactory.createKey(ENDPOINT_CONFIGURATION_KIND,
      endpointClass.getSimpleName());
  try {
    return datastoreService.get(key);
  } catch (EntityNotFoundException e) {
    return new Entity(key);
  }
}
 
Example #29
Source File: CrudOperations.java    From io2014-codelabs with Apache License 2.0 5 votes vote down vote up
private Entity getEntityById(String kindName, String id, User user) throws NotFoundException {

    // try to find the Entity on Memcache
    Entity e = (Entity) memcache.get(id);

    // try to find the Entity
    if (e == null) {
      try {
        e = datastore.get(SecurityChecker.getInstance().createKeyWithNamespace(kindName, id, user));
      } catch (EntityNotFoundException e2) {
        throw new NotFoundException("Cloud Entity not found for id: " + id);
      }
    }
    return e;
  }
 
Example #30
Source File: BlobManager.java    From io2014-codelabs with Apache License 2.0 5 votes vote down vote up
/**
 * Gets blob metadata.
 *
 * @param bucketName Google Cloud Storage bucket where the object was uploaded.
 * @param objectPath path to the object in the bucket.
 * @return blob metadata or null if there is no object for this objectPath and bucketName.
 */
public static BlobMetadata getBlobMetadata(String bucketName, String objectPath) {
  try {
    Entity metadataEntity =
      dataStore.get(BlobMetadata.getKey(getCanonicalizedResource(bucketName, objectPath)));
    return new BlobMetadata(metadataEntity);
  } catch (EntityNotFoundException e) {
    return null;
  }
}