Java Code Examples for com.google.appengine.api.datastore.KeyFactory#createKey()

The following examples show how to use com.google.appengine.api.datastore.KeyFactory#createKey() . 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: 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 2
Source File: TransactionsTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueriesWithDifferentAncestorsInsideSameTransactionNoUsage() {
    Transaction tx = service.beginTransaction();
    try {
        Key a1 = KeyFactory.createKey("ancestor", "1");
        prepareQueryWithAncestor(tx, a1).asIterator();

        Key a2 = KeyFactory.createKey("ancestor", "2");
        prepareQueryWithAncestor(tx, a2).asList(FetchOptions.Builder.withDefaults());

        Key a3 = KeyFactory.createKey("ancestor", "3");
        prepareQueryWithAncestor(tx, a3).asIterable();

        Key a4 = KeyFactory.createKey("ancestor", "4");
        prepareQueryWithAncestor(tx, a4).asQueryResultIterable();

        Key a5 = KeyFactory.createKey("ancestor", "5");
        prepareQueryWithAncestor(tx, a5).asQueryResultIterator();

        Key a6 = KeyFactory.createKey("ancestor", "6");
        prepareQueryWithAncestor(tx, a6).asQueryResultList(FetchOptions.Builder.withDefaults());
    } finally {
        tx.rollback();
    }
}
 
Example 3
Source File: RawKeyStdDeserializer.java    From gwt-jackson with Apache License 2.0 6 votes vote down vote up
@Override
public Key deserialize( JsonParser jp, DeserializationContext ctxt ) throws IOException {
    JsonNode node = jp.readValueAsTree();
    Key parent = null;
    if ( node.has( RawKeyConstant.PARENT ) ) {
        JsonParser parentJsonParser = node.get( RawKeyConstant.PARENT ).traverse();
        parentJsonParser.setCodec( jp.getCodec() );
        parent = parentJsonParser.readValueAs( Key.class );
    }
    String kind = null;
    if ( node.has( RawKeyConstant.KIND ) ) {
        kind = node.get( RawKeyConstant.KIND ).asText();
    }
    long id = node.get( RawKeyConstant.ID ).asLong();

    if ( id != 0 ) {
        return KeyFactory.createKey( parent, kind, id );
    }

    String name = null;
    if ( node.has( RawKeyConstant.NAME ) ) {
        name = node.get( RawKeyConstant.NAME ).asText();
    }
    return KeyFactory.createKey( parent, kind, name );
}
 
Example 4
Source File: DatastoreSessionStore.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
/**
 * Return a {@link Key} for the given session "key" string
 * ({@link SessionManager#SESSION_PREFIX} + sessionId) in the empty namespace.
 */
static Key createKeyForSession(String key) {
  String originalNamespace = NamespaceManager.get();
  try {
    NamespaceManager.set("");
    return KeyFactory.createKey(SESSION_ENTITY_TYPE, key);
  } finally {
    NamespaceManager.set(originalNamespace);
  }
}
 
Example 5
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 6
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 7
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 8
Source File: SmokeTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void batchGetReturnsOnlyExistingKeysInMap() throws Exception {
    Key existingKey = KeyFactory.createKey("batch", "existing");
    Key nonExistingKey = KeyFactory.createKey("batch", "nonExisting");
    service.put(new Entity(existingKey));

    Map<Key, Entity> map = service.get(Arrays.asList(existingKey, nonExistingKey));

    assertEquals(1, map.size());
    assertTrue(map.containsKey(existingKey));
}
 
Example 9
Source File: LocalHighRepDatastoreTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testEventuallyConsistentGlobalQueryResult() {
  DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
  Key ancestor = KeyFactory.createKey("foo", 3);
  ds.put(new Entity("yam", ancestor));
  ds.put(new Entity("yam", ancestor));
  // Global query doesn't see the data.
  assertEquals(0, ds.prepare(new Query("yam")).countEntities(withLimit(10)));
  // Ancestor query does see the data.
  assertEquals(2, ds.prepare(new Query("yam", ancestor)).countEntities(withLimit(10)));
}
 
Example 10
Source File: ServersStartServlet.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public void service(HttpServletRequest req, HttpServletResponse res) {
  CountServlet.localCount.getAndAdd(datastoreCount());
  final Key key = KeyFactory.createKey("Counter", getKeyName());
  LifecycleManager.getInstance()
      .setShutdownHook(
          new ShutdownHook() {
            @Override
            public void shutdown() {
              datastoreSave(key);
            }
          });
}
 
Example 11
Source File: PipelineModelObject.java    From appengine-pipelines with Apache License 2.0 5 votes vote down vote up
protected static Key generateKey(Key parentKey, String kind) {
  String name = GUIDGenerator.nextGUID();
  Key key;
  if (null == parentKey) {
    key = KeyFactory.createKey(kind, name);
  } else {
    key = parentKey.getChild(kind, name);
  }
  return key;
}
 
Example 12
Source File: EntitiesTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void createKey_makesKey() {
  // [START generating_keys_1]
  Key k1 = KeyFactory.createKey("Person", "GreatGrandpa");
  Key k2 = KeyFactory.createKey("Person", 74219);
  // [END generating_keys_1]

  assertThat(k1).isNotNull();
  assertThat(k2).isNotNull();
}
 
Example 13
Source File: SessionData.java    From webauthndemo with Apache License 2.0 5 votes vote down vote up
/**
 * Query datastore for a session for a particular user via id.
 * 
 * @param currentUser
 * @param id
 * @return
 */
public static SessionData load(String currentUser, Long id) {
  Key userKey = KeyFactory.createKey(User.KIND, currentUser);
  Key sessionKey = KeyFactory.createKey(userKey, KIND, id);

  try {
    Entity e = Datastore.getDatastore().get(sessionKey);

    return new SessionData(
        BaseEncoding.base64().decode((String) e.getProperty(CHALLENGE_PROPERTY)),
        (String) e.getProperty(ORIGIN_PROPERTY), (Date) e.getProperty(TIMESTAMP_PROPERTY));
  } catch (EntityNotFoundException e1) {
    return null;
  }
}
 
Example 14
Source File: AppEngineTaskQueueTest.java    From appengine-pipelines with Apache License 2.0 4 votes vote down vote up
private Task createTask() {
  String name = GUIDGenerator.nextGUID();
  Key key = KeyFactory.createKey("testType", name);
  Task task = new RunJobTask(key, new QueueSettings().setModuleVersion("m1"));
  return task;
}
 
Example 15
Source File: BackendConfigManager.java    From io2014-codelabs with Apache License 2.0 4 votes vote down vote up
protected Key getKey() {
  return KeyFactory.createKey(CONFIGURATION_ENTITY_KIND, CURRENT_CONFIGURATION);
}
 
Example 16
Source File: DatastoreDao.java    From getting-started-java with Apache License 2.0 4 votes vote down vote up
@Override
public void deleteBook(Long bookId) {
  Key key = KeyFactory.createKey(BOOK_KIND, bookId);        // Create the Key
  datastore.delete(key);                      // Delete the Entity
}
 
Example 17
Source File: BlobMetadata.java    From io2014-codelabs with Apache License 2.0 4 votes vote down vote up
/**
 * Gets Datastore entity key for a given canonicalizedResource.
 */
public static Key getKey(String canonicalizedResource) {
  return KeyFactory.createKey(ENTITY_KIND, canonicalizedResource);
}
 
Example 18
Source File: DatastoreTest.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
private static Key getKey() {
    return KeyFactory.createKey(MODULES_KIND, 1);
}
 
Example 19
Source File: PipelineManager.java    From appengine-pipelines with Apache License 2.0 3 votes vote down vote up
/**
 * Retrieves a JobRecord for the specified job handle. The returned instance
 * will be only partially inflated. The run and finalize barriers will not be
 * available but the output slot will be.
 *
 * @param jobHandle The handle of a job.
 * @return The corresponding JobRecord
 * @throws NoSuchObjectException If a JobRecord with the given handle cannot
 *         be found in the data store.
 */
public static JobRecord getJob(String jobHandle) throws NoSuchObjectException {
  checkNonEmpty(jobHandle, "jobHandle");
  Key key = KeyFactory.createKey(JobRecord.DATA_STORE_KIND, jobHandle);
  logger.finest("getJob: " + key.getName());
  return backEnd.queryJob(key, JobRecord.InflationType.FOR_OUTPUT);
}
 
Example 20
Source File: ShardedCounter.java    From appengine-modules-sample-java with Apache License 2.0 2 votes vote down vote up
/**
 * Increase the number of shards for a given sharded counter. Will never
 * decrease the number of shards.
 *
 * @param count Number of new shards to build and store
 * @return the new number of shards
 */
public long addShards(int count) {
  final Key counterKey = KeyFactory.createKey(Counter.KIND, counterName);
  return incrementPropertyTx(counterKey, Counter.SHARD_COUNT, count,
      INITIAL_SHARDS + count);
}