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

The following examples show how to use com.google.appengine.api.datastore.KeyFactory. 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: TenantMapper.java    From ezScrum with GNU General Public License v2.0 6 votes vote down vote up
public void addTenant(String tenantId, String name, String description, RentService rentService) {
	PersistenceManager pm = PMF.get().getPersistenceManager();

	Key key = KeyFactory.createKey(TenantDataStore.class.getSimpleName(), tenantId);
	TenantDataStore tenant = new TenantDataStore(key);
	tenant.setTenantname(name);
	tenant.setTenantId(tenantId);
	tenant.setDescription(description);	
	tenant.setRentService(rentService);
	
	try {
		pm.makePersistent(tenant);
	} finally {
		pm.close();
	}	
}
 
Example #2
Source File: TenantMapper.java    From ezScrum with GNU General Public License v2.0 6 votes vote down vote up
public void updateTenant(String tenantId, String name, String description,RentService rentService) {
	PersistenceManager pm = PMF.get().getPersistenceManager();

	Key key = KeyFactory.createKey(TenantDataStore.class.getSimpleName(), tenantId);

	TenantDataStore tenant = pm.getObjectById(TenantDataStore.class, key);
	tenant.setTenantId(tenantId);
	tenant.setTenantname(name);
	tenant.setDescription(description);
	tenant.setRentService(rentService);
	try {
		pm.makePersistent(tenant);
	} finally {
		pm.close();
	}
}
 
Example #3
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 #4
Source File: CableKeyPair.java    From webauthndemo with Apache License 2.0 6 votes vote down vote up
public static KeyPair get(Long sessionId) throws IOException {
  Key sessionKey = KeyFactory.createKey(SessionData.KIND, sessionId);

  Query query = new Query(KIND).setAncestor(sessionKey);

  List<Entity> results =
      Datastore.getDatastore().prepare(query).asList(FetchOptions.Builder.withDefaults());
  
  for (Entity result : results) {
    if (result.getParent().getId() == sessionId.longValue()) {
      byte[] serializedKeyPair =
          BaseEncoding.base64().decode((String) result.getProperty(KEY_PAIR_PROPERTY));
      ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(serializedKeyPair));
      try {
        return (KeyPair) in.readObject();
      } catch (ClassNotFoundException e1) {
        throw new IOException(e1);
      }
    }
  }
  throw new IOException("KeyPair " + String.valueOf(sessionId) + "not found");
}
 
Example #5
Source File: MyEndpoint.java    From endpoints-codelab-android with GNU General Public License v3.0 6 votes vote down vote up
@ApiMethod(name = "clearTasks")
public void clearTasks() {
    DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
    Transaction txn = datastoreService.beginTransaction();
    try {
        Key taskBeanParentKey = KeyFactory.createKey("TaskBeanParent", "todo.txt");
        Query query = new Query(taskBeanParentKey);
        List<Entity> results = datastoreService.prepare(query).asList(FetchOptions.Builder.withDefaults());
        for (Entity result : results) {
            datastoreService.delete(result.getKey());
        }
        txn.commit();
    } finally {
        if (txn.isActive()) {
            txn.rollback();
        }
    }
}
 
Example #6
Source File: TenantMapper.java    From ezScrum with GNU General Public License v2.0 6 votes vote down vote up
public void addTenantAdmin(Account account){
	PersistenceManager pm = PMF.get().getPersistenceManager();
	Key key = KeyFactory.createKey(AccountDataStore.class.getSimpleName(), account.getID());
	
	AccountDataStore accountData = new AccountDataStore(key, account.getID(), account.getPassword());
	accountData.setName(account.getName());
	accountData.setEmail(account.getEmail());
	accountData.setEnable(account.getEnable());
	
	// ?
	List<String> permissions = new ArrayList<String>();
	for (int i=0; i<account.getPermissionList().size(); i++) {
		permissions.add(account.getPermissionList().get(i).getPermissionName());
	}
	accountData.setPermissions(permissions);

	try {
		pm.makePersistent(accountData);
	} finally {
		pm.close();
	}	
}
 
Example #7
Source File: AppEngineDataStoreFactory.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public DataStore<V> delete(String key) throws IOException {
  if (key == null) {
    return this;
  }
  lock.lock();
  try {
    dataStoreService.delete(KeyFactory.createKey(getId(), key));
    if (memcache != null) {
      memcache.delete(key);
    }
  } finally {
    lock.unlock();
  }
  return this;
}
 
Example #8
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 #9
Source File: TransactionsTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void creatingAnEntityInASpecificEntityGroup() throws Exception {
  String boardName = "my-message-board";

  // [START creating_an_entity_in_a_specific_entity_group]
  DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

  String messageTitle = "Some Title";
  String messageText = "Some message.";
  Date postDate = new Date();

  Key messageBoardKey = KeyFactory.createKey("MessageBoard", boardName);

  Entity message = new Entity("Message", messageBoardKey);
  message.setProperty("message_title", messageTitle);
  message.setProperty("message_text", messageText);
  message.setProperty("post_date", postDate);

  Transaction txn = datastore.beginTransaction();
  datastore.put(txn, message);

  txn.commit();
  // [END creating_an_entity_in_a_specific_entity_group]
}
 
Example #10
Source File: FanoutTaskTest.java    From appengine-pipelines with Apache License 2.0 6 votes vote down vote up
@Override
public void setUp() throws Exception {
  super.setUp();
  helper.setUp();
  System.setProperty(USE_SIMPLE_GUIDS_FOR_DEBUGGING, "true");
  Key key = KeyFactory.createKey(JobRecord.DATA_STORE_KIND, "job1");
  RunJobTask runJobTask = new RunJobTask(key, queueSettings1);
  key = KeyFactory.createKey(JobRecord.DATA_STORE_KIND, "job2");
  RunJobTask runJobTask2 = new RunJobTask(key, queueSettings2);
  key = KeyFactory.createKey(JobRecord.DATA_STORE_KIND, "job3");
  FinalizeJobTask finalizeJobTask = new FinalizeJobTask(key, queueSettings1);
  key = KeyFactory.createKey(Slot.DATA_STORE_KIND, "slot1");
  HandleSlotFilledTask hsfTask = new HandleSlotFilledTask(key, queueSettings2);
  listOfTasks = ImmutableList.of(runJobTask, runJobTask2, finalizeJobTask, hsfTask);
  encodedBytes = FanoutTask.encodeTasks(listOfTasks);
}
 
Example #11
Source File: SecurityChecker.java    From solutions-mobile-backend-starter-java with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link Key} from the specified kindName and CloudEntity id. If
 * the kindName has _private suffix, the key will be created under a namespace
 * for the specified {@link User}.
 *
 * @param kindName
 *          Name of kind
 * @param id
 *          CloudEntity id
 * @param user
 *          {@link User} of the requestor
 * @return {@link Key}
 */
public Key createKeyWithNamespace(String kindName, String id, User user) {

  // save the original namespace
  String origNamespace = NamespaceManager.get();

  // set namespace based on the kind suffix
  if (kindName.startsWith(SecurityChecker.KIND_PREFIX_PRIVATE)) {
    String userId = getUserId(user);
    NamespaceManager.set(userId);
  } else {
    NamespaceManager.set(SecurityChecker.NAMESPACE_DEFAULT);
  }

  // create a key
  Key k = KeyFactory.createKey(kindName, id);

  // restore the original namespace
  NamespaceManager.set(origNamespace);
  return k;
}
 
Example #12
Source File: RequiredIndexesTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testAncestorQueryWithEqualityAndInequalityFiltersAndSortOnASinglePropertyDoesRequireConfiguredIndex() throws Exception {
    try {
        executeQuery(
            new Query("Unindexed")
                .setAncestor(KeyFactory.createKey("Ancestor", 1))
                .setFilter(
                    and(new Query.FilterPredicate("someProperty", GREATER_THAN, "a"),
                        new Query.FilterPredicate("someProperty", EQUAL, "b")))
                .addSort("someProperty"));
    } catch (Exception e) {
        assertTrue(EXPECTED_DS_INDEX_MSG + " instead got " + e.toString(), e instanceof DatastoreNeedIndexException);
        return;
    }
    fail(EXPECTED_DS_INDEX_MSG);
}
 
Example #13
Source File: TenantManagerTest.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
private TenantDataStore getTenantDS(String tenantId) {
	PersistenceManager pm = PMF.get().getPersistenceManager();
	
	Key tenantKey = KeyFactory.createKey(TenantDataStore.class.getSimpleName(), tenantId);
	TenantDataStore tenantDS;
	try {
		tenantDS = pm.getObjectById(TenantDataStore.class, tenantKey);

	} finally {
		pm.close();
	}
	
	return tenantDS;
}
 
Example #14
Source File: TaskServlet.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
/**
 * Registers a process-file-with-content task.
 * @param fileKey  key of file to process
 * @param fileType file type
 */
public static void register_procFileWithContentTask( final Key fileKey, final String fileType ) {
	QueueFactory.getQueue( QUEUE_NAME_PROC_FILE_WITH_CONTENT ).add(
		buildTask( OPERATION_PROC_FILE_WITH_CONTENT )
			.param( PARAM_FILE_KEY , KeyFactory.keyToString( fileKey ) )
			.param( PARAM_FILE_TYPE, fileType )
	);
}
 
Example #15
Source File: PipelineManager.java    From appengine-pipelines with Apache License 2.0 5 votes vote down vote up
/**
 * Changes the state of the specified job to STOPPED.
 *
 * @param jobHandle The handle of a job
 * @throws NoSuchObjectException If a JobRecord with the given handle cannot
 *         be found in the data store.
 */
public static void stopJob(String jobHandle) throws NoSuchObjectException {
  checkNonEmpty(jobHandle, "jobHandle");
  Key key = KeyFactory.createKey(JobRecord.DATA_STORE_KIND, jobHandle);
  JobRecord jobRecord = backEnd.queryJob(key, JobRecord.InflationType.NONE);
  jobRecord.setState(State.STOPPED);
  UpdateSpec updateSpec = new UpdateSpec(jobRecord.getRootJobKey());
  updateSpec.getOrCreateTransaction("stopJob").includeJob(jobRecord);
  backEnd.save(updateSpec, jobRecord.getQueueSettings());
}
 
Example #16
Source File: Worker.java    From solutions-mobile-backend-starter-java with Apache License 2.0 5 votes vote down vote up
/**
 * Check for already processed tasks.
 *
 * @param tasks the list of the tasks to be checked.
 * @return the set of task names that have already been processed.
 */
private Set<String> getAlreadyProcessedTaskNames(List<TaskHandle> tasks) {
  /*
   * To optimize for performance check in memcache first. A value from memcache may have been
   * evicted. Datastore is the authoritative source, so for any task not found in memcache check
   * in Datastore.
   */

  List<String> taskNames = new ArrayList<String>();

  for (TaskHandle task : tasks) {
    taskNames.add(task.getName());
  }

  Map<String, Object> alreadyProcessedTaskNames = cache.getAll(taskNames);

  List<Key> keys = new ArrayList<Key>();

  for (String taskName : taskNames) {
    if (!alreadyProcessedTaskNames.containsKey(taskName)) {
      keys.add(KeyFactory.createKey(PROCESSED_NOTIFICATION_TASKS_ENTITY_KIND, taskName));
    }
  }

  if (keys.size() > 0) {
    Map<Key, Entity> entityMap = dataStore.get(keys);
    for (Key key : entityMap.keySet()) {
      alreadyProcessedTaskNames.put(key.getName(), 1);
    }
  }

  return alreadyProcessedTaskNames.keySet();
}
 
Example #17
Source File: ObjRefTask.java    From appengine-pipelines with Apache License 2.0 5 votes vote down vote up
private static String createTaskName(String namePrefix, Key key) {
  if (null == key) {
    throw new IllegalArgumentException("key is null.");
  }
  if (namePrefix == null) {
    throw new IllegalArgumentException("namePrix is null.");
  }
  return namePrefix + KeyFactory.keyToString(key);
}
 
Example #18
Source File: RequiredIndexesTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryWithInequalityFilterOnKeyPropertyAndEqualityFilterOnOtherPropertyDoesNotRequireConfiguredIndex() throws Exception {
    executeQuery(
        new Query("Unindexed")
            .setFilter(
                and(new Query.FilterPredicate(Entity.KEY_RESERVED_PROPERTY, GREATER_THAN, KeyFactory.createKey("Unindexed", 1)),
                    new Query.FilterPredicate("otherProperty", EQUAL, "b"))));
}
 
Example #19
Source File: RemoteApiSharedTests.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public Key get() {
  // This assumes that the remote api has already been installed.
  Key key = KeyFactory.createKey(kind, "somename" + nameCounter);
  if (expectRemoteAppIdsOnKeysAfterInstallingRemoteApi) {
    assertRemoteAppId(key);
  }
  nameCounter++;

  return key;
}
 
Example #20
Source File: GuestbookStrong.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@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 #21
Source File: TenantMapper.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
public void renewTenant(String tenantId) {
	PersistenceManager pm = PMF.get().getPersistenceManager();

	Key key = KeyFactory.createKey(TenantDataStore.class.getSimpleName(), tenantId);
	TenantDataStore tenant = pm.getObjectById(TenantDataStore.class, key);
	
	tenant.setEnable(true);		
	try {
		pm.makePersistent(tenant);
	} finally {
		pm.close();
	}
}
 
Example #22
Source File: RequiredIndexesTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryUsingOnlyAncestorFiltersAndEqualityFiltersOnPropertiesAndInequalityFiltersOnKeysDoesNotRequireConfiguredIndex() throws Exception {
    executeQuery(new Query("Unindexed")
        .setAncestor(KeyFactory.createKey("Ancestor", 1))
        .setFilter(
            and(new Query.FilterPredicate("someProperty", EQUAL, "foo"),
                new Query.FilterPredicate(Entity.KEY_RESERVED_PROPERTY, GREATER_THAN, KeyFactory.createKey("Unindexed", 1)))));
}
 
Example #23
Source File: GuestbookTestUtilities.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void cleanDatastore(DatastoreService ds, String book) {
  Query query =
      new Query("Greeting")
          .setAncestor(new KeyFactory.Builder("Guestbook", book).getKey())
          .setKeysOnly();
  PreparedQuery pq = ds.prepare(query);
  List<Entity> entities = pq.asList(FetchOptions.Builder.withDefaults());
  ArrayList<Key> keys = new ArrayList<>(entities.size());

  for (Entity e : entities) {
    keys.add(e.getKey());
  }
  ds.delete(keys);
}
 
Example #24
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 #25
Source File: TransactionsTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void usesForTransactions_relativeUpdates() throws Exception {
  String boardName = "my-message-board";
  Entity b = new Entity("MessageBoard", boardName);
  b.setProperty("count", 41);
  datastore.put(b);

  // [START uses_for_transactions_1]
  int retries = 3;
  while (true) {
    Transaction txn = datastore.beginTransaction();
    try {
      Key boardKey = KeyFactory.createKey("MessageBoard", boardName);
      Entity messageBoard = datastore.get(boardKey);

      long count = (Long) messageBoard.getProperty("count");
      ++count;
      messageBoard.setProperty("count", count);
      datastore.put(txn, messageBoard);

      txn.commit();
      break;
    } catch (ConcurrentModificationException e) {
      if (retries == 0) {
        throw e;
      }
      // Allow retry to occur
      --retries;
    } finally {
      if (txn.isActive()) {
        txn.rollback();
      }
    }
  }
  // [END uses_for_transactions_1]

  b = datastore.get(KeyFactory.createKey("MessageBoard", boardName));
  assertWithMessage("board.count").that((long) b.getProperty("count")).isEqualTo(42L);
}
 
Example #26
Source File: TaskServlet.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
/**
 * Registers a recalc-file-stats task.
 * @param accountKey account key
 */
public static void register_recalcFileStatsTask( final Key accountKey ) {
	QueueFactory.getQueue( getEntityUpdateQueueName( accountKey ) ).add(
		buildTask( OPERATION_RECALC_FILE_STATS )
			.param( PARAM_ACCOUNT_KEY, KeyFactory.keyToString( accountKey ) )
	);
}
 
Example #27
Source File: TaskServlet.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
/**
 * Registers an update-file-delete-stats task.
 * @param accountKey account key
 * @param fileSize   file size
 * @param fileType   file type
 * @param sha1       SHA-1 of the file to be deleted after
 */
public static void register_updateFileDelStatsTask( final Key accountKey, final long fileSize, final String fileType ) {
	QueueFactory.getQueue( getEntityUpdateQueueName( accountKey ) ).add(
		buildTask( OPERATION_UPDATE_FILE_DEL_STATS )
			.param( PARAM_ACCOUNT_KEY, KeyFactory.keyToString( accountKey ) )
			.param( PARAM_FILE_SIZE  , Long.toString( fileSize            ) )
			.param( PARAM_FILE_TYPE  , fileType                             )
	);
}
 
Example #28
Source File: TaskServlet.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
/**
 * Registers an update-file-dl-stats task options.
 * @param accountKey account key
 * @param fileSize   file size
 * @return an update-file-dl-stats task options
 */
public static void register_updateFileDownlStatsTask( final Key accountKey, final long fileSize, final String fileType ) {
	QueueFactory.getQueue( getEntityUpdateQueueName( accountKey ) ).add(
		buildTask( OPERATION_UPDATE_FILE_DOWNL_STATS )
			.param( PARAM_ACCOUNT_KEY, KeyFactory.keyToString( accountKey ) )
			.param( PARAM_FILE_SIZE  , Long.toString( fileSize            ) )
			.param( PARAM_FILE_TYPE  , fileType                             )
	);
}
 
Example #29
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 5 votes vote down vote up
/**
 * Take an HttpServletRequest, and copy all of the current session variables over to it
 * @param req Request from which to extract session.
 * @return a map of strings containing all the session variables loaded or an empty map.
 */
protected Map<String, String> loadSessionVariables(HttpServletRequest req)
    throws ServletException {
  Map<String, String> datastoreMap = new HashMap<>();
  String sessionId = getCookieValue(req, "bookshelfSessionId");
  if (sessionId.equals("")) {
    return datastoreMap;
  }
  Key key = KeyFactory.createKey(SESSION_KIND, sessionId);
  Transaction transaction = datastore.beginTransaction();
  try {
    Entity stateEntity = datastore.get(transaction, key);
    Map<String, Object> properties = stateEntity.getProperties();
    for (Map.Entry<String, Object> property : properties.entrySet()) {
      req.getSession().setAttribute(property.getKey(), property.getValue());
      datastoreMap.put(property.getKey(), (String)property.getValue());
    }
    transaction.commit();
  } catch (EntityNotFoundException e) {
    // Ignore - if there's no session, there's nothing to delete.
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
  return datastoreMap;
}
 
Example #30
Source File: QueryBasicsTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void queryingByKindOnlyReturnsEntitiesOfRequestedKind() throws Exception {
    Key parentKey = createQueryBasicsTestParent("queryingByKindOnlyReturnsEntitiesOfRequestedKind");
    Entity person = new Entity(KeyFactory.createKey(parentKey, "Person", 1));
    service.put(person);

    Entity address = new Entity(KeyFactory.createKey(parentKey, "Address", 1));
    service.put(address);

    assertSingleResult(person, new Query("Person").setAncestor(parentKey));
}