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

The following examples show how to use com.google.appengine.api.datastore.KeyFactory#stringToKey() . 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: CachingService.java    From sc2gears with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the Account key associated with the specified user.
 * @param pm   reference to the persistence manager
 * @param user user to return the account key for
 * @return the Account key associated with the specified user; or <code>null</code> if no account is associated with the specified user
 */
public static Key getAccountKeyByUser( final PersistenceManager pm, final User user ) {
	final String memcacheKey = CACHE_KEY_USER_ACCOUNT_KEY_PREFIX + user.getEmail();
	final String accountKeyString = (String) memcacheService.get( memcacheKey );
	if ( accountKeyString != null )
		return KeyFactory.stringToKey( accountKeyString );
	
	final Query q = new Query( Account.class.getSimpleName() );
	q.setFilter( new FilterPredicate( "user", FilterOperator.EQUAL, user ) );
	q.setKeysOnly();
	final List< Entity > entityList = DatastoreServiceFactory.getDatastoreService().prepare( q ).asList( FetchOptions.Builder.withDefaults() );
	if ( entityList.isEmpty() )
		return null;
	
	final Key accountKey = entityList.get( 0 ).getKey();
	try {
		memcacheService.put( memcacheKey, KeyFactory.keyToString( accountKey ) );
	}
	catch ( final MemcacheServiceException mse ) {
		LOGGER.log( Level.WARNING, "Failed to put key to memcache: " + memcacheKey, mse );
		// Ignore memcache errors, do not prevent serving user request
	}
	
	return accountKey;
}
 
Example 2
Source File: CachingService.java    From sc2gears with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the Account key associated with the specified authorization key.
 * @param pm               reference to the persistence manager
 * @param authorizationKey authorization key to return the account key for
 * @return the Account key associated with the specified authorization key; or <code>null</code> if the authorization key is invalid
 */
public static Key getAccountKeyByAuthKey( final PersistenceManager pm, final String authorizationKey ) {
	final String memcacheKey = CACHE_KEY_AUTH_KEY_ACCOUNT_KEY_PREFIX + authorizationKey;
	final String accountKeyString = (String) memcacheService.get( memcacheKey );
	if ( accountKeyString != null )
		return KeyFactory.stringToKey( accountKeyString );
	
	final Query q = new Query( Account.class.getSimpleName() );
	q.setFilter( new FilterPredicate( "authorizationKey", FilterOperator.EQUAL, authorizationKey ) );
	q.setKeysOnly();
	final List< Entity > entityList = DatastoreServiceFactory.getDatastoreService().prepare( q ).asList( FetchOptions.Builder.withDefaults() );
	if ( entityList.isEmpty() )
		return null;
	
	final Key accountKey = entityList.get( 0 ).getKey();
	try {
		memcacheService.put( memcacheKey, KeyFactory.keyToString( accountKey ) );
	}
	catch ( final MemcacheServiceException mse ) {
		LOGGER.log( Level.WARNING, "Failed to put key to memcache: " + memcacheKey, mse );
		// Ignore memcache errors, do not prevent serving user request
	}
	
	return accountKey;
}
 
Example 3
Source File: EntitiesTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void keyToString_getsPerson() throws Exception {
  Entity p = new Entity("Person");
  p.setProperty("relationship", "Me");
  datastore.put(p);
  Key k = p.getKey();

  // [START generating_keys_3]
  String personKeyStr = KeyFactory.keyToString(k);

  // Some time later (for example, after using personKeyStr in a link).
  Key personKey = KeyFactory.stringToKey(personKeyStr);
  Entity person = datastore.get(personKey);
  // [END generating_keys_3]

  assertThat(personKey).isEqualTo(k);
  assertWithMessage("person.relationship")
      .that((String) person.getProperty("relationship"))
      .isEqualTo("Me");
}
 
Example 4
Source File: DeleteEntityAction.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  // Get raw key strings from request
  ImmutableList.Builder<Object> ofyDeletionsBuilder = new ImmutableList.Builder<>();
  ImmutableList.Builder<Key> rawDeletionsBuilder = new ImmutableList.Builder<>();
  for (String rawKeyString : Splitter.on(',').split(rawKeys)) {
    // Convert raw keys string to real keys. Try to load it from Objectify if it's a registered
    // type, and fall back to DatastoreService if its not registered.
    Key rawKey = KeyFactory.stringToKey(rawKeyString);
    Optional<Object> ofyEntity = loadOfyEntity(rawKey);
    if (ofyEntity.isPresent()) {
      ofyDeletionsBuilder.add(ofyEntity.get());
      continue;
    }
    Optional<Entity> rawEntity = loadRawEntity(rawKey);
    if (rawEntity.isPresent()) {
      rawDeletionsBuilder.add(rawEntity.get().getKey());
      continue;
    }
    // The entity could not be found by either Objectify or the Datastore service
    throw new BadRequestException("Could not find entity with key " + rawKeyString);
  }
  // Delete raw entities.
  ImmutableList<Key> rawDeletions = rawDeletionsBuilder.build();
  getDatastoreService().delete(rawDeletions);
  // Delete ofy entities.
  final ImmutableList<Object> ofyDeletions = ofyDeletionsBuilder.build();
  tm().transactNew(() -> ofy().delete().entities(ofyDeletions).now());
  String message = String.format(
      "Deleted %d raw entities and %d registered entities",
      rawDeletions.size(),
      ofyDeletions.size());
  logger.atInfo().log(message);
  response.setPayload(message);
}
 
Example 5
Source File: TaskServlet.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
private void customTask( final HttpServletRequest request, final PersistenceManager pm ) throws IOException {
	LOGGER.fine( "Key: " + request.getParameter( "key" ) + ", file type: " + request.getParameter( "fileType" ) );
	
	final FileType fileType = FileType.fromString( request.getParameter( "fileType" ) );
	if ( fileType == null ) {
		LOGGER.severe( "Invalid File type!" );
		return;
	}
	
	final Key key = KeyFactory.stringToKey( request.getParameter( "key" ) );
	
	final DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
       final Entity e;
	try {
        e = ds.get( key );
       } catch ( final EntityNotFoundException enfe ) {
		LOGGER.log( Level.WARNING, "Entity not found!", enfe );
        return;
       }
	
       if ( !e.getKind().equals( "Rep" ) && !e.getKind().equals( "Smpd" ) && !e.getKind().equals( "OtherFile" ) ) {
		LOGGER.severe( "Invalid Entity kind:" + e.getKind() );
		return;
       }
       
       if ( (Long) e.getProperty( "v" ) == 4 ) {
		LOGGER.warning( "Entity is already v4!" );
		return;
	}
       
       // Update common properties:
       // TODO
       final int size = ( (Long) e.getProperty( "size" ) ).intValue();
       if ( size < FileServlet.DATASTORE_CONTENT_STORE_LIMIT ) {
           final FileService fileService = FileServiceFactory.getFileService();
   		final AppEngineFile   appeFile = new AppEngineFile( FileSystem.BLOBSTORE, ( (BlobKey) e.getProperty( "blobKey" ) ).getKeyString() );
   		final FileReadChannel channel  = fileService.openReadChannel( appeFile, false );
   		final byte[]          content  = new byte[ size ];
   		final ByteBuffer      wrapper  = ByteBuffer.wrap( content );
   		while ( channel.read( wrapper ) > 0 )
   			;
   		channel.close();
   		
   		e.setProperty( "content", new Blob( content ) );
   		e.setProperty( "blobKey", null );
   		fileService.delete( appeFile );
       }
       e.setUnindexedProperty( "blobKey", e.getProperty( "blobKey" ) );
       e.setUnindexedProperty( "content", e.getProperty( "content" ) );
       
       switch ( fileType ) {
       case SC2REPLAY :
           e.setUnindexedProperty( "matchup", e.getProperty( "matchup" ) );
       	break;
       case MOUSE_PRINT :
       	break;
       case OTHER :
       	break;
       default:
       	throw new RuntimeException( "Invalid file type!" );
       }
       
       // UPGRADE COMPLETE!
	e.setProperty( "v", 4 );
	ds.put( e );
}
 
Example 6
Source File: HandleChildExceptionTask.java    From appengine-pipelines with Apache License 2.0 4 votes vote down vote up
protected HandleChildExceptionTask(Type type, String taskName, Properties properties) {
  super(type, taskName, properties);
  failedChildKey = KeyFactory.stringToKey(properties.getProperty(FAILED_CHILD_KEY_PARAM));
}
 
Example 7
Source File: DelayedSlotFillTask.java    From appengine-pipelines with Apache License 2.0 4 votes vote down vote up
protected DelayedSlotFillTask(Type type, String taskName, Properties properties) {
  super(type, taskName, properties);
  rootJobKey = KeyFactory.stringToKey(properties.getProperty(ROOT_JOB_KEY_PARAM));
}
 
Example 8
Source File: FanoutTask.java    From appengine-pipelines with Apache License 2.0 4 votes vote down vote up
/**
 * Construct a new FanoutTask from the given Properties. This constructor
 * is used to construct an instance that is being handled.
 */
public FanoutTask(Type type, String taskName, Properties properties) {
  super(type, taskName, properties);
  this.recordKey = KeyFactory.stringToKey(properties.getProperty(RECORD_KEY_PROPERTY));
}
 
Example 9
Source File: PipelineManager.java    From appengine-pipelines with Apache License 2.0 4 votes vote down vote up
public static void acceptPromisedValue(String promiseHandle, Object value)
    throws NoSuchObjectException, OrphanedObjectException {
  checkNonEmpty(promiseHandle, "promiseHandle");
  Key key = KeyFactory.stringToKey(promiseHandle);
  Slot slot = null;
  // It is possible, though unlikely, that we might be asked to accept a
  // promise before the slot to hold the promise has been saved. We will try 5
  // times, sleeping 1, 2, 4, 8 seconds between attempts.
  int attempts = 0;
  boolean interrupted = false;
  try {
    while (slot == null) {
      attempts++;
      try {
        slot = backEnd.querySlot(key, false);
      } catch (NoSuchObjectException e) {
        if (attempts >= 5) {
          throw new NoSuchObjectException("There is no promise with handle " + promiseHandle);
        }
        try {
          Thread.sleep((long) Math.pow(2.0, attempts - 1) * 1000L);
        } catch (InterruptedException f) {
          interrupted = true;
        }
      }
    }
  } finally {
    // TODO(user): replace with Uninterruptibles#sleepUninterruptibly once we use guava
    if (interrupted) {
      Thread.currentThread().interrupt();
    }
  }
  Key generatorJobKey = slot.getGeneratorJobKey();
  if (null == generatorJobKey) {
    throw new RuntimeException(
        "Pipeline is fatally corrupted. Slot for promised value has no generatorJobKey: " + slot);
  }
  JobRecord generatorJob = backEnd.queryJob(generatorJobKey, JobRecord.InflationType.NONE);
  if (null == generatorJob) {
    throw new RuntimeException("Pipeline is fatally corrupted. "
        + "The generator job for a promised value slot was not found: " + generatorJobKey);
  }
  String childGraphGuid = generatorJob.getChildGraphGuid();
  if (null == childGraphGuid) {
    // The generator job has not been saved with a childGraphGuid yet. This can happen if the
    // promise handle leaked out to an external thread before the job that generated it
    // had finished.
    throw new NoSuchObjectException(
        "The framework is not ready to accept the promised value yet. "
        + "Please try again after the job that generated the promis handle has completed.");
  }
  if (!childGraphGuid.equals(slot.getGraphGuid())) {
    // The slot has been orphaned
    throw new OrphanedObjectException(promiseHandle);
  }
  UpdateSpec updateSpec = new UpdateSpec(slot.getRootJobKey());
  registerSlotFilled(updateSpec, generatorJob.getQueueSettings(), slot, value);
  backEnd.save(updateSpec, generatorJob.getQueueSettings());
}
 
Example 10
Source File: ObjRefTask.java    From appengine-pipelines with Apache License 2.0 2 votes vote down vote up
/**
 * This constructor is used on the receiving side. That is, it is used to
 * construct an {@code ObjRefTask} from an HttpRequest sent from the App
 * Engine task queue.
 *
 * @param type The type of task being constructed
 * @param properties In addition to the properties specified in the parent
 *        constructor, {@code properties} must also contain a property named "key"
 *        with a value of a stringified data store key. This will be used as
 *        the {@link #key} of the object to which this {@code ObjRefTask}
 *        refers.
 */
protected ObjRefTask(Type type, String taskName, Properties properties) {
  super(type, taskName, properties);
  key = KeyFactory.stringToKey(properties.getProperty(KEY_PARAM));
}