signature: public class ObjectTranslatorFactory { @ Override public Translator < Object , Object > create ( final TypeKey < Object > tk , final CreateContext createCtx , final Path path ) { } }

implementation:
if ( tk . getTypeAsClass ( ) != Object . class ) return null ; return new NullSafeTranslator < Object , Object > ( ) { @ Override protected Object loadSafe ( final Value < Object > value , final LoadContext ctx , final Path path ) throws SkipException { return value . get ( ) ; } @ Override protected Value < Object > saveSafe ( final Object pojo , final boolean index , final SaveContext saveCtx , final Path path ) throws SkipException { final TypeKey < Object > runtimeTypeKey = new TypeKey < > ( pojo . getClass ( ) ) ; // We really only need the createctx so that the translators can get a factory .
final Translator < Object , Object > realTranslator = translators . get ( runtimeTypeKey , createCtx , path ) ; return realTranslator . save ( pojo , index , saveCtx , path ) ; } } ;


signature:
public class PendingFutures { /** * Iterate through all pending futures and get ( ) them , forcing any callbacks to be called .
 * This is used only by the AsyncCacheFilter ( if using cache without Objectify ) or ObjectifyFilter
 * ( if using Objectify normally ) because we don ' t have a proper hook otherwise . */
public static void completeAllPendingFutures ( ) { } }

implementation:
// This will cause done Futures to fire callbacks and remove themselves
for ( Future < ? > fut : pending . get ( ) . keySet ( ) ) { try { fut . get ( ) ; } catch ( Exception e ) { log . error ( "Error cleaning up pending Future: " + fut , e ) ; } }


signature:
public class Registrar { /** * < p > All @ Entity and @ Subclass classes ( for both entity and embedded classes )
 * must be registered before using Objectify to load or save data . This method
 * must be called in a single - threaded mode sometime around application initialization . < / p >
 * < p > Re - registering a class has no effect . < / p >
 * @ param clazz must be annotated with either @ Entity or @ Subclass */
public < T > void register ( Class < T > clazz ) { } }

implementation:
// There are two possible cases
// 1 ) This might be a simple class with @ Entity
// 2 ) This might be a class annotated with @ Subclass
// @ Entity is inherited , but we only create entity metadata for the class with the @ Entity declaration
if ( TypeUtils . isDeclaredAnnotationPresent ( clazz , Entity . class ) ) { String kind = Key . getKind ( clazz ) ; // If we are already registered , ignore
if ( this . byKind . containsKey ( kind ) ) return ; EntityMetadata < T > cmeta = new EntityMetadata < > ( this . fact , clazz ) ; this . byKind . put ( kind , cmeta ) ; if ( cmeta . getCacheExpirySeconds ( ) != null ) this . cacheEnabled = true ; } else if ( clazz . isAnnotationPresent ( Subclass . class ) ) { // We just need to make sure that a translator was created
fact . getTranslators ( ) . getRoot ( clazz ) ; } else { throw new IllegalArgumentException ( clazz + " must be annotated with either @Entity or @Subclass" ) ; }


signature:
public class Registrar { /** * Gets metadata for the specified kind
 * @ throws IllegalArgumentException if the kind has not been registered */
public < T > EntityMetadata < T > getMetadataSafe ( String kind ) throws IllegalArgumentException { } }

implementation: EntityMetadata < T > metadata = this . getMetadata ( kind ) ; if ( metadata == null ) throw new IllegalArgumentException ( "No entity class has been registered which matches kind '" + kind + "'" ) ; else return metadata ;


signature:
public class QueryEngine { /** * Perform a keys - only query . */
public < T > QueryResults < Key < T > > queryKeysOnly ( final KeyQuery query ) { } }

implementation: log . trace ( "Starting keys-only query" ) ; return new KeyQueryResults < > ( ds . run ( query ) ) ;


signature:
public class QueryEngine { /** * Perform a keys - only plus batch gets . */
public < T > QueryResults < T > queryHybrid ( final KeyQuery query , final int chunkSize ) { } }

implementation: log . trace ( "Starting hybrid query" ) ; final QueryResults < Key < T > > results = new KeyQueryResults < > ( ds . run ( query ) ) ; return new HybridQueryResults < > ( loader . createLoadEngine ( ) , results , chunkSize ) ;


signature:
public class QueryEngine { /** * A normal , non - hybrid query */
public < T > QueryResults < T > queryNormal ( final EntityQuery query , final int chunkSize ) { } }

implementation:
log . trace ( "Starting normal query" ) ; // Normal queries are actually more complex than hybrid queries because we need the fetched entities to
// be stuffed back into the engine to satisfy @ Load instructions without extra fetching . Even though
// this looks like we ' re doing hybrid load - by - key operations , the data is pulled from the stuffed values .
final LoadEngine loadEngine = loader . createLoadEngine ( ) ; final QueryResults < Entity > entityResults = ds . run ( query ) ; final QueryResults < com . google . cloud . datastore . Key > stuffed = new StuffingQueryResults ( loadEngine , entityResults ) ; final QueryResults < Key < T > > keyResults = new KeyQueryResults < > ( stuffed ) ; return new HybridQueryResults < > ( loadEngine , keyResults , chunkSize ) ;


signature:
public class QueryEngine { /** * A projection query . Bypasses the session entirely . */
public < T > QueryResults < T > queryProjection ( final ProjectionEntityQuery query ) { } }

implementation: log . trace ( "Starting projection query" ) ; final LoadEngine loadEngine = loader . createLoadEngine ( ) ; return new ProjectionQueryResults < > ( ds . run ( query ) , loadEngine ) ;


signature:
public class QueryEngine { /** * The fundamental query count operation . This doesn ' t appear to be implemented in the new SDK , so we simulate
 * with a keys - only query . */
public int queryCount ( final KeyQuery query ) { } }

implementation: log . trace ( "Starting count query" ) ; final QueryResults < com . google . cloud . datastore . Key > results = ds . run ( query ) ; return Iterators . size ( results ) ;


signature:
public class HybridQueryResults { /** * Detects Integer . MAX _ VALUE and prevents OOM exceptions */
private < T > Iterator < Iterator < T > > safePartition ( final Iterator < T > input , int chunkSize ) { } }

implementation:
// Cloud Datastore library errors if you try to fetch more than 1000 keys at a time
if ( chunkSize > 1000 ) { chunkSize = 1000 ; } return Iterators . transform ( Iterators . partition ( input , chunkSize ) , IterateFunction . instance ( ) ) ;


signature:
public class HybridQueryResults { /** * Loads them ; note that it ' s possible for some loaded results to be null */
private Iterator < ResultWithCursor < T > > load ( final Iterator < ResultWithCursor < Key < T > > > keys ) { } }

implementation: final List < Entry < ResultWithCursor < Key < T > > , Result < T > > > results = Lists . newArrayList ( ) ; while ( keys . hasNext ( ) ) { final ResultWithCursor < Key < T > > next = keys . next ( ) ; results . add ( Maps . immutableEntry ( next , loadEngine . load ( next . getResult ( ) ) ) ) ; } loadEngine . execute ( ) ; return Iterators . transform ( results . iterator ( ) , entry -> new ResultWithCursor < > ( entry . getValue ( ) . now ( ) , entry . getKey ( ) . getCursorAfter ( ) ) ) ;


signature:
public class ArrayUtils { /** * Copies an array of primitive longs while boxing them at the same time ,
 * and then converting into a list . Can ' t use { @ link Arrays # asList ( Object [ ] ) }
 * directly as that will create a list of arrays instead .
 * @ param elements The array of primitive longs to convert to a list
 * @ return A list of boxed { @ link long } values */
public static List < Long > asList ( long ... elements ) { } }

implementation: Objects . requireNonNull ( elements ) ; Long [ ] copy = new Long [ elements . length ] ; for ( int index = 0 ; index < elements . length ; index ++ ) { copy [ index ] = elements [ index ] ; } return Arrays . asList ( copy ) ;


signature:
public class LoadResult { /** * Like now ( ) , but throws NotFoundException instead of returning null .
 * @ throws NotFoundException if the loaded value was not found */
public final T safe ( ) throws NotFoundException { } }

implementation: T t = now ( ) ; if ( t == null ) throw new NotFoundException ( key ) ; else return t ;


signature:
public class LogUtils { /** * Create a log a message for a given path */
public static String msg ( Path path , String msg ) { } }

implementation: StringBuilder bld = new StringBuilder ( ) ; bld . append ( "\t." ) ; bld . append ( path . toPathString ( ) ) ; if ( bld . length ( ) < PATH_PADDING ) while ( bld . length ( ) < PATH_PADDING ) bld . append ( ' ' ) ; else bld . append ( '\t' ) ; bld . append ( msg ) ; return bld . toString ( ) ;


signature:
public class Key { /** * Key . create ( key ) is easier to type than new Key < Blah > ( key ) */
public static < T > Key < T > create ( final com . google . cloud . datastore . Key raw ) { } }

implementation: if ( raw == null ) throw new NullPointerException ( "Cannot create a Key<?> from a null datastore Key" ) ; return new Key < > ( raw ) ;


signature:
public class Key { /** * Key . create ( Blah . class , id ) is easier to type than new Key < Blah > ( Blah . class , id ) */
public static < T > Key < T > create ( final Class < ? extends T > kindClass , final long id ) { } }

implementation: return new Key < > ( kindClass , id ) ;


signature:
public class Key { /** * Key . create ( Blah . class , name ) is easier to type than new Key < Blah > ( Blah . class , name ) */
public static < T > Key < T > create ( final Class < ? extends T > kindClass , final String name ) { } }

implementation: return new Key < > ( kindClass , name ) ;


signature:
public class Key { /** * Key . create ( urlSafeString ) is easier to type than new Key < Blah > ( urlSafeString ) */
public static < T > Key < T > create ( final String urlSafeString ) { } }

implementation: if ( urlSafeString == null ) throw new NullPointerException ( "Cannot create a Key<?> from a null String" ) ; return new Key < > ( urlSafeString ) ;


signature:
public class Key { /** * Create a key from a registered POJO entity . */
public static < T > Key < T > create ( final T pojo ) { } }

implementation: return ObjectifyService . factory ( ) . keys ( ) . keyOf ( pojo ) ;


signature:
public class Key { /** * < p > The new cloud sdk Key doesn ' t have compareTo ( ) , so we reimplement the logic from the old GAE SDK . < / p > */
@ Override public int compareTo ( final Key < ? > other ) { } }

implementation:
if ( this . raw == other . raw ) { return 0 ; } { final int result = this . raw . getProjectId ( ) . compareTo ( other . raw . getProjectId ( ) ) ; if ( result != 0 ) return result ; } { final int result = this . raw . getNamespace ( ) . compareTo ( other . raw . getNamespace ( ) ) ; if ( result != 0 ) return result ; } { final int result = this . compareAncestors ( other ) ; if ( result != 0 ) return result ; } { // Too bad PathElement and Key don ' t share any kind of interface grrr
final int result = this . getRaw ( ) . getKind ( ) . compareTo ( other . getRaw ( ) . getKind ( ) ) ; if ( result != 0 ) { return result ; } else if ( this . raw . getNameOrId ( ) == null && other . raw . getNameOrId ( ) == null ) { return compareToWithIdentityHash ( this . raw , other . raw ) ; } else if ( this . raw . hasId ( ) ) { return other . raw . hasId ( ) ? Long . compare ( this . raw . getId ( ) , other . raw . getId ( ) ) : - 1 ; } else { return other . raw . hasId ( ) ? 1 : this . raw . getName ( ) . compareTo ( other . raw . getName ( ) ) ; } }


signature:
public class Key { /** * I have no idea what this is about , it was in the old logic */
private int compareToWithIdentityHash ( final Object k1 , final Object k2 ) { } }

implementation: return Integer . compare ( System . identityHashCode ( k1 ) , System . identityHashCode ( k2 ) ) ;


signature:
public class Key { /** * Easy null - safe conversion of the raw key . */
public static < V > Key < V > key ( final com . google . cloud . datastore . Key raw ) { } }

implementation: if ( raw == null ) return null ; else return new Key < > ( raw ) ;


signature:
public class Key { /** * Easy null - safe conversion of the typed key . */
public static com . google . cloud . datastore . Key key ( final Key < ? > typed ) { } }

implementation: if ( typed == null ) return null ; else return typed . getRaw ( ) ;


signature:
public class Key { /** * < p > Determines the kind for a Class , as understood by the datastore . The first class in a
 * hierarchy that has @ Entity defines the kind ( either explicitly or as that class ' simplename ) . < / p >
 * < p > If no @ Entity annotation is found , just uses the simplename as is . < / p > */
public static String getKind ( final Class < ? > clazz ) { } }

implementation: final String kind = getKindRecursive ( clazz ) ; if ( kind == null ) return clazz . getSimpleName ( ) ; else return kind ;


signature:
public class Key { /** * < p > Recursively looks for the @ Entity annotation . < / p >
 * @ return null if kind cannot be found */
private static String getKindRecursive ( final Class < ? > clazz ) { } }

implementation: if ( clazz == Object . class ) return null ; final String kind = getKindHere ( clazz ) ; if ( kind != null ) return kind ; else return getKindRecursive ( clazz . getSuperclass ( ) ) ;


signature:
public class Key { /** * Get the kind from the class if the class has an @ Entity annotation , otherwise return null . */
private static String getKindHere ( final Class < ? > clazz ) { } }

implementation:
// @ Entity is inherited so we have to be explicit about the declared annotations
final Entity ourAnn = TypeUtils . getDeclaredAnnotation ( clazz , Entity . class ) ; if ( ourAnn != null ) if ( ourAnn . name ( ) . length ( ) != 0 ) return ourAnn . name ( ) ; else return clazz . getSimpleName ( ) ; return null ;


signature:
public class GenericTypeReflector { /** * Checks if the given type is a class that is supposed to have type parameters , but doesn ' t .
 * In other words , if it ' s a really raw type . */
static boolean isMissingTypeParameters ( Type type ) { } }

implementation: if ( type instanceof Class ) { for ( Class < ? > clazz = ( Class < ? > ) type ; clazz != null ; clazz = clazz . getEnclosingClass ( ) ) { if ( clazz . getTypeParameters ( ) . length != 0 ) return true ; } return false ; } else if ( type instanceof ParameterizedType ) { return false ; } else { throw new AssertionError ( "Unexpected type " + type . getClass ( ) ) ; }


signature:
public class GenericTypeReflector { /** * Checks if the capture of subType is a subtype of superType */
public static boolean isSuperType ( Type superType , Type subType ) { } }

implementation:
if ( superType instanceof ParameterizedType || superType instanceof Class || superType instanceof GenericArrayType ) { Class < ? > superClass = erase ( superType ) ; Type mappedSubType = getExactSuperType ( capture ( subType ) , superClass ) ; if ( mappedSubType == null ) { return false ; } else if ( superType instanceof Class < ? > ) { return true ; } else if ( mappedSubType instanceof Class < ? > ) { // TODO treat supertype by being raw type differently ( " supertype , but with warnings " )
return true ; // class has no parameters , or it ' s a raw type
} else if ( mappedSubType instanceof GenericArrayType ) { Type superComponentType = getArrayComponentType ( superType ) ; assert superComponentType != null ; Type mappedSubComponentType = getArrayComponentType ( mappedSubType ) ; assert mappedSubComponentType != null ; return isSuperType ( superComponentType , mappedSubComponentType ) ; } else { assert mappedSubType instanceof ParameterizedType ; ParameterizedType pMappedSubType = ( ParameterizedType ) mappedSubType ; assert pMappedSubType . getRawType ( ) == superClass ; ParameterizedType pSuperType = ( ParameterizedType ) superType ; Type [ ] superTypeArgs = pSuperType . getActualTypeArguments ( ) ; Type [ ] subTypeArgs = pMappedSubType . getActualTypeArguments ( ) ; assert superTypeArgs . length == subTypeArgs . length ; for ( int i = 0 ; i < superTypeArgs . length ; i ++ ) { if ( ! contains ( superTypeArgs [ i ] , subTypeArgs [ i ] ) ) { return false ; } } // params of the class itself match , so if the owner types are supertypes too , it ' s a supertype .
return pSuperType . getOwnerType ( ) == null || isSuperType ( pSuperType . getOwnerType ( ) , pMappedSubType . getOwnerType ( ) ) ; } } else if ( superType instanceof CaptureType ) { if ( superType . equals ( subType ) ) return true ; for ( Type lowerBound : ( ( CaptureType ) superType ) . getLowerBounds ( ) ) { if ( isSuperType ( lowerBound , subType ) ) { return true ; } } return false ; } else if ( superType instanceof GenericArrayType ) { return isArraySupertype ( superType , subType ) ; } else { throw new RuntimeException ( "not implemented: " + superType . getClass ( ) ) ; }


signature:
public class GenericTypeReflector { /** * Returns the direct supertypes of the given type . Resolves type parameters . */
private static Type [ ] getExactDirectSuperTypes ( Type type ) { } }

implementation:
if ( type instanceof ParameterizedType || type instanceof Class ) { Class < ? > clazz ; if ( type instanceof ParameterizedType ) { clazz = ( Class < ? > ) ( ( ParameterizedType ) type ) . getRawType ( ) ; } else { // TODO primitive types ?
clazz = ( Class < ? > ) type ; if ( clazz . isArray ( ) ) return getArrayExactDirectSuperTypes ( clazz ) ; } Type [ ] superInterfaces = clazz . getGenericInterfaces ( ) ; Type superClass = clazz . getGenericSuperclass ( ) ; // the only supertype of an interface without superinterfaces is Object
if ( superClass == null && superInterfaces . length == 0 && clazz . isInterface ( ) ) { return new Type [ ] { Object . class } ; } Type [ ] result ; int resultIndex ; if ( superClass == null ) { result = new Type [ superInterfaces . length ] ; resultIndex = 0 ; } else { result = new Type [ superInterfaces . length + 1 ] ; resultIndex = 1 ; result [ 0 ] = mapTypeParameters ( superClass , type ) ; } for ( Type superInterface : superInterfaces ) { result [ resultIndex ++ ] = mapTypeParameters ( superInterface , type ) ; } return result ; } else if ( type instanceof TypeVariable ) { TypeVariable < ? > tv = ( TypeVariable < ? > ) type ; return tv . getBounds ( ) ; } else if ( type instanceof WildcardType ) { // This should be a rare case : normally this wildcard is already captured .
// But it does happen if the upper bound of a type variable contains a wildcard
// TODO shouldn ' t upper bound of type variable have been captured too ? ( making this case impossible ? )
return ( ( WildcardType ) type ) . getUpperBounds ( ) ; } else if ( type instanceof CaptureType ) { return ( ( CaptureType ) type ) . getUpperBounds ( ) ; } else if ( type instanceof GenericArrayType ) { return getArrayExactDirectSuperTypes ( type ) ; } else if ( type == null ) { throw new NullPointerException ( ) ; } else { throw new RuntimeException ( "not implemented type: " + type ) ; }


signature:
public class GenericTypeReflector { /** * Returns the exact type of the given field in the given type .
 * This may be different from < tt > f . getGenericType ( ) < / tt > when the field was declared in a superclass ,
 * or < tt > type < / tt > has a type parameter that is used in the type of the field , or < tt > type < / tt > is a raw type . */
public static Type getExactFieldType ( Field f , Type type ) { } }

implementation:
Type returnType = f . getGenericType ( ) ; Type exactDeclaringType = getExactSuperType ( capture ( type ) , f . getDeclaringClass ( ) ) ; if ( exactDeclaringType == null ) { // capture ( type ) is not a subtype of f . getDeclaringClass ( )
throw new IllegalArgumentException ( "The field " + f + " is not a member of type " + type ) ; } return mapTypeParameters ( returnType , exactDeclaringType ) ;


signature:
public class GenericTypeReflector { /** * Applies capture conversion to the given type . */
public static Type capture ( Type type ) { } }

implementation: if ( type instanceof ParameterizedType ) { return capture ( ( ParameterizedType ) type ) ; } else { return type ; }


signature:
public class CreateContext { /** * Get the relevant translator , creating it if necessary . */
public < P , D > Translator < P , D > getTranslator ( final TypeKey < P > tk , final CreateContext ctx , final Path path ) { } }

implementation: return factory . getTranslators ( ) . get ( tk , ctx , path ) ;


signature:
public class CreateContext { /** * Get the populator for the specified class . This requires looking up the
 * translator for that class and then getting the populator from it .
 * @ param clazz is the class we want a populator for . */
@ SuppressWarnings ( "unchecked" ) public < P > Populator < P > getPopulator ( final Class < P > clazz , final Path path ) { } }

implementation: if ( clazz == null || clazz . equals ( Object . class ) ) { return ( Populator < P > ) NullPopulator . INSTANCE ; } else { final ClassTranslator < P > classTranslator = ( ClassTranslator < P > ) this . < P , FullEntity < ? > > getTranslator ( new TypeKey < > ( clazz ) , this , path ) ; return classTranslator . getPopulator ( ) ; }


signature: public class ClassPopulator { @ Override public void load ( FullEntity < ? > node , LoadContext ctx , Path path , final P into ) { } }

implementation:
superPopulator . load ( node , ctx , path , into ) ; ctx . enterContainerContext ( into ) ; try { for ( final Populator < Object > prop : props ) { prop . load ( node , ctx , path , into ) ; } } finally { ctx . exitContainerContext ( into ) ; } // If there are any @ OnLoad methods , call them after everything else
if ( ! onLoadMethods . isEmpty ( ) ) { ctx . defer ( new Runnable ( ) { @ Override public void run ( ) { for ( LifecycleMethod method : onLoadMethods ) method . execute ( into ) ; } @ Override public String toString ( ) { return "(deferred invoke " + clazz + " @OnLoad callbacks on " + into + ")" ; } } ) ; }


signature: public class ClassPopulator { @ Override public void save ( P pojo , boolean index , SaveContext ctx , Path path , FullEntity . Builder < ? > into ) { } }

implementation:
superPopulator . save ( pojo , index , ctx , path , into ) ; // Must do @ OnSave methods after superclass but before actual population
if ( ! ctx . skipLifecycle ( ) && ! onSaveMethods . isEmpty ( ) ) for ( LifecycleMethod method : onSaveMethods ) method . execute ( pojo ) ; if ( indexInstruction != null ) index = indexInstruction ; for ( final Populator < Object > prop : props ) { prop . save ( pojo , index , ctx , path , into ) ; }


signature:
public class ClassPopulator { /** * Figure out if there is an index instruction for the whole class .
 * @ return true , false , or null ( which means no info ) */
private Boolean getIndexInstruction ( Class < P > clazz ) { } }

implementation: Index ind = clazz . getAnnotation ( Index . class ) ; Unindex unind = clazz . getAnnotation ( Unindex . class ) ; if ( ind != null && unind != null ) throw new IllegalStateException ( "You cannot have @Index and @Unindex on the same class: " + clazz ) ; if ( ind != null ) return true ; else if ( unind != null ) return false ; else return null ;


signature:
public class ClassPopulator { /** * Determine if we should create a Property for the field . Things we ignore : static , final , @ Ignore , synthetic */
private boolean isOfInterest ( Field field ) { } }

implementation: return ! field . isAnnotationPresent ( Ignore . class ) && ( ( field . getModifiers ( ) & NOT_SAVEABLE_MODIFIERS ) == 0 ) && ! field . isSynthetic ( ) && ! field . getName ( ) . startsWith ( "bitmap$init" ) ; // Scala adds a field bitmap $ init $ 0 and bitmap $ init $ 1 etc


signature:
public class ClassPopulator { /** * Determine if we should create a Property for the method ( ie , @ AlsoLoad ) */
private boolean isOfInterest ( Method method ) { } }

implementation: for ( Annotation [ ] annos : method . getParameterAnnotations ( ) ) if ( TypeUtils . getAnnotation ( annos , AlsoLoad . class ) != null ) return true ; return false ;


signature:
public class ClassPopulator { /** * Get all the persistable fields and methods declared on a class . Ignores superclasses .
 * @ return the fields we load and save , including @ Id and @ Parent fields . All fields will be set accessable
 * and returned in order of declaration . */
private List < Property > getDeclaredProperties ( ObjectifyFactory fact , Class < ? > clazz ) { } }

implementation: List < Property > good = new ArrayList < > ( ) ; for ( Field field : clazz . getDeclaredFields ( ) ) if ( isOfInterest ( field ) ) good . add ( new FieldProperty ( fact , clazz , field ) ) ; for ( Method method : clazz . getDeclaredMethods ( ) ) if ( isOfInterest ( method ) ) good . add ( new MethodProperty ( method ) ) ; return good ;


signature:
public class ClassPopulator { /** * Gets the key metadata but only if this was an @ Entity annotated class . Should not be called if not . */
public KeyMetadata < P > getKeyMetadata ( ) { } }

implementation: final Populator < Object > populator = props . get ( 0 ) ; Preconditions . checkState ( populator instanceof KeyPopulator , "Cannot get KeyMetadata for non-@Entity class " + this . clazz ) ; return ( ( KeyPopulator < P > ) populator ) . getKeyMetadata ( ) ;


signature:
public class Round { /** * Gets a result , using the session cache if possible . */
public < T > Result < T > get ( final Key < T > key ) { } }

implementation:
assert ! isExecuted ( ) ; SessionValue < T > sv = getSession ( ) . get ( key ) ; if ( sv == null ) { log . trace ( "Adding to round (session miss): {}" , key ) ; this . pending . add ( key . getRaw ( ) ) ; Result < T > result = new ResultCache < T > ( ) { @ Override @ SuppressWarnings ( "unchecked" ) public T nowUncached ( ) { // Because clients could conceivably get ( ) in the middle of our operations ( see LoadCollectionRefsTest . specialListWorks ( ) ) ,
// we need to check for early execution . This will perform poorly , but at least it will work .
// assert Round . this . isExecuted ( ) ;
loadEngine . execute ( ) ; return ( T ) translated . now ( ) . get ( key ) ; } @ Override public String toString ( ) { return "(Fetch result for " + key + ")" ; } } ; sv = new SessionValue < > ( result , getLoadArrangement ( ) ) ; getSession ( ) . add ( key , sv ) ; } else { log . trace ( "Adding to round (session hit): {}" , key ) ; if ( sv . loadWith ( getLoadArrangement ( ) ) ) { log . trace ( "New load group arrangement, checking for upgrades: {}" , getLoadArrangement ( ) ) ; // We are looking at a brand - new arrangement for something that already existed in the session .
// We need to go through any Ref < ? > s that might be in need of loading . We find those refs by
// actually saving the entity into a custom SaveContext .
T thing = sv . getResult ( ) . now ( ) ; if ( thing != null ) { SaveContext saveCtx = new SaveContext ( ) { @ Override public boolean skipLifecycle ( ) { return true ; } @ Override public com . google . cloud . datastore . Key saveRef ( Ref < ? > value , LoadConditions loadConditions ) { com . google . cloud . datastore . Key key = super . saveRef ( value , loadConditions ) ; if ( loadEngine . shouldLoad ( loadConditions ) ) { log . trace ( "Upgrading key {}" , key ) ; loadEngine . load ( value . key ( ) ) ; } return key ; } } ; // We throw away the saved entity and we are done
loadEngine . ofy . factory ( ) . getMetadataForEntity ( thing ) . save ( thing , saveCtx ) ; } } } return sv . getResult ( ) ;


signature:
public class Round { /** * Turn this into a result set */
public void execute ( ) { } }

implementation:
if ( needsExecution ( ) ) { log . trace ( "Executing round: {}" , pending ) ; Result < Map < com . google . cloud . datastore . Key , Entity > > fetched = fetchPending ( ) ; translated = loadEngine . translate ( fetched ) ; // If we ' re in a transaction ( and beyond the first round ) , force all subsequent rounds to complete .
// This effectively means that only the first round can be asynchronous ; all other rounds are
// materialized immediately . The reason for this is that there are some nasty edge cases with @ Load
// annotations in transactions getting called after the transaction closes . This is possibly not the
// best solution to the problem , but it solves the problem now .
if ( loadEngine . ofy . getTransaction ( ) != null && depth > 0 ) translated . now ( ) ; }


signature:
public class Round { /** * Possibly pulls some values from the stuffed collection */
private Result < Map < com . google . cloud . datastore . Key , Entity > > fetchPending ( ) { } }

implementation:
// We don ' t need to fetch anything that has been stuffed
final Map < com . google . cloud . datastore . Key , Entity > combined = new HashMap < > ( ) ; Set < com . google . cloud . datastore . Key > fetch = new HashSet < > ( ) ; for ( com . google . cloud . datastore . Key key : pending ) { Entity ent = stuffed . get ( key ) ; if ( ent == null ) fetch . add ( key ) ; else combined . put ( key , ent ) ; } if ( fetch . isEmpty ( ) ) { return new ResultNow < > ( combined ) ; } else { final Result < Map < com . google . cloud . datastore . Key , Entity > > fetched = loadEngine . fetch ( fetch ) ; return ( ) -> { combined . putAll ( fetched . now ( ) ) ; return combined ; } ; }


signature: public class ClassTranslator { @ Override public P loadSafe ( final Value < FullEntity < ? > > container , final LoadContext ctx , final Path path ) throws SkipException { } }

implementation:
// check if we need to redirect to a different translator
final String containerDiscriminator = container . get ( ) . contains ( DISCRIMINATOR_PROPERTY ) ? container . get ( ) . getString ( DISCRIMINATOR_PROPERTY ) : null ; // wow no Optional or nullable get
if ( ! Objects . equals ( discriminator , containerDiscriminator ) ) { final ClassTranslator < ? extends P > translator = byDiscriminator . get ( containerDiscriminator ) ; if ( translator == null ) { throw new IllegalStateException ( "Datastore object has discriminator value '" + containerDiscriminator + "' but no relevant @Subclass is registered" ) ; } else { // This fixes alsoLoad names in discriminators by changing the discriminator to what the
// translator expects for loading that subclass . Otherwise we ' ll get the error above since the
// translator discriminator and the container discriminator won ' t match .
final StringValue discriminatorValue = StringValue . newBuilder ( translator . getDiscriminator ( ) ) . setExcludeFromIndexes ( true ) . build ( ) ; final FullEntity < ? > updatedEntity = FullEntity . newBuilder ( container . get ( ) ) . set ( DISCRIMINATOR_PROPERTY , discriminatorValue ) . build ( ) ; return translator . load ( EntityValue . of ( updatedEntity ) , ctx , path ) ; } } else { // This is a normal load
if ( log . isTraceEnabled ( ) ) log . trace ( LogUtils . msg ( path , "Instantiating a " + declaredClass . getName ( ) ) ) ; final P into = forge . construct ( declaredClass ) ; populator . load ( container . get ( ) , ctx , path , into ) ; return into ; }


signature: public class ClassTranslator { @ Override public Value < FullEntity < ? > > saveSafe ( final P pojo , final boolean index , final SaveContext ctx , final Path path ) throws SkipException { } }

implementation:
// check if we need to redirect to a different translator
if ( pojo . getClass ( ) != declaredClass ) { // Sometimes generics are more of a hindrance than a help
@ SuppressWarnings ( "unchecked" ) final ClassTranslator < P > translator = ( ClassTranslator < P > ) byClass . get ( pojo . getClass ( ) ) ; if ( translator == null ) throw new IllegalStateException ( "Class '" + pojo . getClass ( ) + "' is not a registered @Subclass" ) ; else return translator . save ( pojo , index , ctx , path ) ; } else { // This is a normal save
final FullEntity . Builder < IncompleteKey > into = FullEntity . newBuilder ( ) ; populator . save ( pojo , index , ctx , path , into ) ; if ( discriminator != null ) { into . set ( DISCRIMINATOR_PROPERTY , StringValue . newBuilder ( discriminator ) . setExcludeFromIndexes ( true ) . build ( ) ) ; if ( ! indexedDiscriminators . isEmpty ( ) ) into . set ( DISCRIMINATOR_INDEX_PROPERTY , ListValue . of ( indexedDiscriminators ) ) ; } // The question of whether to index this is weird . In order for subthings to be indexed , the entity needs
// to be indexed . But then lists with index - heterogeous values ( say , nulls ) get reordered ( ! )
// by the datastore . So we always index EntityValues and force all the list translators homogenize their lists .
// Gross but seems to be the only way .
return EntityValue . of ( into . build ( ) ) ; }


signature:
public class ClassTranslator { /** * Recursively go through the class hierarchy adding any discriminators that are indexed */
private void addIndexedDiscriminators ( final Class < ? > clazz ) { } }

implementation: if ( clazz == Object . class ) return ; this . addIndexedDiscriminators ( clazz . getSuperclass ( ) ) ; final Subclass sub = clazz . getAnnotation ( Subclass . class ) ; if ( sub != null && sub . index ( ) ) { final String disc = ( sub . name ( ) . length ( ) > 0 ) ? sub . name ( ) : clazz . getSimpleName ( ) ; this . indexedDiscriminators . add ( StringValue . of ( disc ) ) ; }


signature:
public class ClassTranslator { /** * Register a subclass translator with this class translator . That way if we get called upon
 * to translate an instance of the subclass , we will forward to the correct translator . */
public void registerSubclass ( ClassTranslator < ? extends P > translator ) { } }

implementation: byDiscriminator . put ( translator . getDiscriminator ( ) , translator ) ; Subclass sub = translator . getDeclaredClass ( ) . getAnnotation ( Subclass . class ) ; for ( String alsoLoad : sub . alsoLoad ( ) ) byDiscriminator . put ( alsoLoad , translator ) ; byClass . put ( translator . getDeclaredClass ( ) , translator ) ;


signature:
public class GenericUtils { /** * Get the component type of a Collection . */
public static Type getCollectionComponentType ( Type collectionType ) { } }

implementation:
Type componentType = GenericTypeReflector . getTypeParameter ( collectionType , Collection . class . getTypeParameters ( ) [ 0 ] ) ; if ( componentType == null ) // if it was a raw type , just assume Object
return Object . class ; else return componentType ;


signature:
public class GenericUtils { /** * Get the key type of a Map . */
public static Type getMapKeyType ( Type mapType ) { } }

implementation:
Type componentType = GenericTypeReflector . getTypeParameter ( mapType , Map . class . getTypeParameters ( ) [ 0 ] ) ; if ( componentType == null ) // if it was a raw type , just assume Object
return Object . class ; else return componentType ;


signature:
public class ForwardPath { /** * Recursive method which reverses the path into a ForwardPath .
 * @ param path cannot be the root path . */
public static ForwardPath of ( Path path ) { } }

implementation: ForwardPath next = new ForwardPath ( path ) ; if ( path . getPrevious ( ) == Path . root ( ) ) return next ; ForwardPath previous = of ( path . getPrevious ( ) ) ; previous . next = next ; return previous ;


signature:
public class ForwardPath { /** * Get the complete path in this chain , typically for error messages or debugging */
public Path getFinalPath ( ) { } }

implementation: ForwardPath here = this ; while ( here . next != null ) here = here . next ; return here . getPath ( ) ;


signature:
public class Path { /** * Create the full x . y . z string */
public String toPathString ( ) { } }

implementation: if ( this == ROOT ) { return "" ; } else { StringBuilder builder = new StringBuilder ( ) ; toPathString ( builder ) ; return builder . toString ( ) ; }


signature:
public class Path { /** * ROOT is 0 , top level Entity properties are 1 , embedded things are higher . */
public int depth ( ) { } }

implementation: int depth = 0 ; Path here = this ; while ( here != ROOT ) { depth ++ ; here = here . previous ; } return depth ;


signature:
public class SaverImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . Saver # entity ( java . lang . Object ) */
@ Override public < E > Result < Key < E > > entity ( final E entity ) { } }

implementation: final Result < Map < Key < E > , E > > base = this . < E > entities ( Collections . singleton ( entity ) ) ; return new ResultWrapper < Map < Key < E > , E > , Key < E > > ( base ) { private static final long serialVersionUID = 1L ; @ Override protected Key < E > wrap ( final Map < Key < E > , E > base ) { return base . keySet ( ) . iterator ( ) . next ( ) ; } } ;


signature:
public class SaverImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . Saver # entities ( E [ ] ) */
@ Override public < E > Result < Map < Key < E > , E > > entities ( final E ... entities ) { } }

implementation: return this . entities ( Arrays . asList ( entities ) ) ;


signature:
public class SaverImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . Saver # entities ( java . lang . Iterable ) */
@ Override public < E > Result < Map < Key < E > , E > > entities ( final Iterable < E > entities ) { } }

implementation: return ofy . createWriteEngine ( ) . save ( entities ) ;


signature:
public class SaverImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . Saver # toEntity ( java . lang . Object ) */
@ Override public FullEntity < ? > toEntity ( final Object pojo ) { } }

implementation: if ( pojo instanceof FullEntity < ? > ) { return ( FullEntity < ? > ) pojo ; } else { @ SuppressWarnings ( "unchecked" ) final EntityMetadata < Object > meta = ( EntityMetadata < Object > ) ofy . factory ( ) . getMetadata ( pojo . getClass ( ) ) ; return meta . save ( pojo , new SaveContext ( ) ) ; }


signature:
public class EntityMemcache { /** * < p > Gets the Buckets for the specified keys . A bucket is built around an IdentifiableValue so you can
 * putAll ( ) them without the risk of overwriting other threads ' changes . Buckets also hide the
 * underlying details of storage for negative , empty , and uncacheable results . < / p >
 * < p > Note that worst case ( a cold cache ) , obtaining each bucket might require three memcache requests :
 * a getIdentifiable ( ) which returns null , a put ( null ) , and another getIdentifiable ( ) . Since
 * there is no batch getIdentifiable ( ) , this is * per key * . < / p >
 * < p > When keys are uncacheable ( per CacheControl ) or the memcache is down , you will still get an empty
 * bucket back . The bucket will have null IdentifiableValue so we can identify it as uncacheable . < / p >
 * @ return the buckets requested . Buckets will never be null . You will always get a bucket for every key . */
public Map < Key , Bucket > getAll ( final Iterable < Key > keys ) { } }

implementation:
final Map < Key , Bucket > result = new HashMap < > ( ) ; // Sort out the ones that are uncacheable
final Set < Key > potentials = new HashSet < > ( ) ; for ( final Key key : keys ) { if ( ! cacheControl . isCacheable ( key ) ) result . put ( key , new Bucket ( key ) ) ; else potentials . add ( key ) ; } Map < Key , IdentifiableValue > casValues ; try { casValues = this . memcache . getIdentifiables ( potentials ) ; } catch ( Exception ex ) { // This should really only be a problem if the serialization format for an Entity changes ,
// or someone put a badly - serializing object in the cache underneath us .
log . warn ( "Error obtaining cache for " + potentials , ex ) ; casValues = new HashMap < > ( ) ; } // Now create the remaining buckets
for ( final Key key : keys ) { final IdentifiableValue casValue = casValues . get ( key ) ; // Might be null , which means uncacheable
final Bucket buck = new Bucket ( key , casValue ) ; result . put ( key , buck ) ; if ( buck . isEmpty ( ) ) this . stats . recordMiss ( buck . getKey ( ) ) ; else this . stats . recordHit ( buck . getKey ( ) ) ; } return result ;


signature:
public class EntityMemcache { /** * Update a set of buckets with new values . If collisions occur , resets the memcache value to null .
 * @ param updates can have null Entity values , which will record a negative cache result . Buckets must have
 * been obtained from getAll ( ) . */
public void putAll ( final Collection < Bucket > updates ) { } }

implementation:
final Set < Key > good = this . cachePutIfUntouched ( updates ) ; if ( good . size ( ) == updates . size ( ) ) return ; // Figure out which ones were bad
final List < Key > bad = updates . stream ( ) . map ( Bucket :: getKey ) . filter ( key -> ! good . contains ( key ) ) . collect ( Collectors . toList ( ) ) ; if ( ! bad . isEmpty ( ) ) { // So we had some collisions . We need to reset these back to null , but do it in a safe way - if we
// blindly set null something already null , it will break any putIfUntouched ( ) which saw the first null .
// This could result in write contention starving out a real write . The solution is to only reset things
// that are not already null .
final Map < Key , Object > cached = this . cacheGetAll ( bad ) ; // Remove the stuff we don ' t care about
cached . values ( ) . removeIf ( Objects :: isNull ) ; this . empty ( cached . keySet ( ) ) ; }


signature:
public class EntityMemcache { /** * Revert a set of keys to the empty state . Will loop on this several times just in case
 * the memcache write fails - we don ' t want to leave the cache in a nasty state . */
public void empty ( final Iterable < Key > keys ) { } }

implementation: final Map < Key , Object > updates = new HashMap < > ( ) ; for ( final Key key : keys ) if ( cacheControl . isCacheable ( key ) ) updates . put ( key , null ) ; this . memcacheWithRetry . putAll ( updates ) ;


signature:
public class EntityMemcache { /** * Put buckets in the cache , checking for cacheability and collisions .
 * @ return the set of keys that were * successfully * handled . That includes buckets that were put without collision
 * and buckets that didn ' t need to be cached . */
private Set < Key > cachePutIfUntouched ( final Iterable < Bucket > buckets ) { } }

implementation: final Map < Key , CasPut > payload = new HashMap < > ( ) ; final Set < Key > successes = new HashSet < > ( ) ; for ( final Bucket buck : buckets ) { if ( ! buck . isCacheable ( ) ) { successes . add ( buck . getKey ( ) ) ; continue ; } final Integer expirySeconds = cacheControl . getExpirySeconds ( buck . getKey ( ) ) ; if ( expirySeconds == null ) { successes . add ( buck . getKey ( ) ) ; continue ; } payload . put ( buck . getKey ( ) , new CasPut ( buck . identifiableValue , buck . getNextToStore ( ) , expirySeconds ) ) ; } successes . addAll ( this . memcache . putIfUntouched ( payload ) ) ; return successes ;


signature:
public class EntityMemcache { /** * Bulk get on keys , getting the raw objects */
private Map < Key , Object > cacheGetAll ( final Collection < Key > keys ) { } }

implementation:
try { return this . memcache . getAll ( keys ) ; } catch ( Exception ex ) { // Some sort of serialization error , just wipe out the values
log . warn ( "Error fetching values from memcache, deleting keys" , ex ) ; this . memcache . deleteAll ( keys ) ; return new HashMap < > ( ) ; }


signature:
public class EntityMemcache { /** * Basically a list comprehension of the keys for convenience . */
public static Set < Key > keysOf ( final Collection < Bucket > buckets ) { } }

implementation: return buckets . stream ( ) . map ( Bucket :: getKey ) . collect ( Collectors . toSet ( ) ) ;


signature:
public class KeyMetadata { /** * Recursively go through the class hierarchy looking for the idMeta and parentMeta fields .
 * @ throws IllegalStateException if @ Id or @ Parent shows up twice . */
private void findKeyFields ( Class < ? > inspect , CreateContext ctx , Path path ) { } }

implementation: if ( inspect == Object . class ) return ; findKeyFields ( inspect . getSuperclass ( ) , ctx , path ) ; for ( Field field : inspect . getDeclaredFields ( ) ) { if ( field . getAnnotation ( Id . class ) != null ) { if ( this . idMeta != null ) throw new IllegalStateException ( "Multiple @Id fields in the class hierarchy of " + clazz . getName ( ) ) ; if ( ( field . getType ( ) != Long . class ) && ( field . getType ( ) != long . class ) && ( field . getType ( ) != String . class ) ) throw new IllegalStateException ( "@Id field '" + field . getName ( ) + "' in " + inspect . getName ( ) + " must be of type Long, long, or String" ) ; Property prop = new FieldProperty ( ctx . getFactory ( ) , clazz , field ) ; Translator < Object , Object > translator = ctx . getTranslator ( new TypeKey < > ( prop ) , ctx , path . extend ( prop . getName ( ) ) ) ; this . idMeta = new PropertyPopulator < > ( prop , translator ) ; } else if ( field . getAnnotation ( Parent . class ) != null ) { if ( this . parentMeta != null ) throw new IllegalStateException ( "Multiple @Parent fields in the class hierarchy of " + clazz . getName ( ) ) ; if ( ! isAllowedParentFieldType ( field . getType ( ) ) ) throw new IllegalStateException ( "@Parent fields must be Ref<?>, Key<?>, or datastore Key. Illegal parent: " + field ) ; Property prop = new FieldProperty ( ctx . getFactory ( ) , clazz , field ) ; Translator < Object , Object > translator = ctx . getTranslator ( new TypeKey < > ( prop ) , ctx , path . extend ( prop . getName ( ) ) ) ; this . parentMeta = new PropertyPopulator < > ( prop , translator ) ; } }


signature:
public class KeyMetadata { /** * Sets the key ( from the container ) onto the POJO id / parent fields . Also doublechecks to make sure
 * that the key fields aren ' t present in the container , which means we ' re in a very bad state . */
public void setKey ( final P pojo , final FullEntity < ? > container , final LoadContext ctx , final Path containerPath ) { } }

implementation: if ( container . contains ( idMeta . getProperty ( ) . getName ( ) ) ) throw new IllegalStateException ( "Datastore has a property present for the id field " + idMeta . getProperty ( ) + " which would conflict with the key: " + container ) ; if ( parentMeta != null && container . contains ( parentMeta . getProperty ( ) . getName ( ) ) ) throw new IllegalStateException ( "Datastore has a property present for the parent field " + parentMeta . getProperty ( ) + " which would conflict with the key: " + container ) ; this . setKey ( pojo , container . getKey ( ) , ctx , containerPath ) ;


signature:
public class KeyMetadata { /** * Sets the key onto the POJO id / parent fields */
@ SuppressWarnings ( "unchecked" ) private void setKey ( final P pojo , final IncompleteKey key , final LoadContext ctx , final Path containerPath ) { } }

implementation:
if ( ! clazz . isAssignableFrom ( pojo . getClass ( ) ) ) throw new IllegalArgumentException ( "Trying to use metadata for " + clazz . getName ( ) + " to set key of " + pojo . getClass ( ) . getName ( ) ) ; // If no key , don ' t need to do anything
if ( key == null ) return ; idMeta . setValue ( pojo , Keys . getIdValue ( key ) , ctx , containerPath ) ; final com . google . cloud . datastore . Key parentKey = key . getParent ( ) ; if ( parentKey != null ) { if ( this . parentMeta == null ) throw new IllegalStateException ( "Loaded Entity has parent but " + clazz . getName ( ) + " has no @Parent" ) ; parentMeta . setValue ( pojo , ( Value ) KeyValue . of ( parentKey ) , ctx , containerPath ) ; }


signature:
public class KeyMetadata { /** * Sets the key on a container from the POJO . */
@ SuppressWarnings ( "unchecked" ) public < K extends IncompleteKey > void setKey ( final FullEntity . Builder < K > container , final P pojo ) { } }

implementation:
final IncompleteKey rawKey = getIncompleteKey ( pojo ) ; if ( ! ( rawKey instanceof com . google . cloud . datastore . Key ) ) { // it ' s incomplete , make sure we can save it
Preconditions . checkState ( isIdNumeric ( ) , "Cannot save an entity with a null String @Id: %s" , pojo ) ; } container . setKey ( ( K ) rawKey ) ;


signature:
public class KeyMetadata { /** * Gets a key composed of the relevant id and parent fields in the object .
 * @ param pojo must be of the entityClass type for this metadata .
 * @ return either a Key or IncompleteKey depending on whether the id is null or not */
public IncompleteKey getIncompleteKey ( final P pojo ) { } }

implementation: log . trace ( "Getting key from {}" , pojo ) ; if ( ! clazz . isAssignableFrom ( pojo . getClass ( ) ) ) throw new IllegalArgumentException ( "Trying to use metadata for " + clazz . getName ( ) + " to get key of " + pojo . getClass ( ) . getName ( ) ) ; final Object id = getId ( pojo ) ; final com . google . cloud . datastore . Key parent = getParentRaw ( pojo ) ; if ( id == null ) return factory . keys ( ) . createRawIncomplete ( parent , kind ) ; else return factory . keys ( ) . createRawAny ( parent , kind , id ) ;


signature:
public class KeyMetadata { /** * Gets a key composed of the relevant id and parent fields in the object .
 * @ param pojo must be of the entityClass type for this metadata .
 * @ throws IllegalArgumentException if pojo has an incomplete key */
public com . google . cloud . datastore . Key getCompleteKey ( final P pojo ) { } }

implementation: final com . google . cloud . datastore . IncompleteKey key = getIncompleteKey ( pojo ) ; if ( key instanceof com . google . cloud . datastore . Key ) return ( com . google . cloud . datastore . Key ) key ; else throw new IllegalArgumentException ( "You cannot create a Key for an object with a null @Id. Object was " + pojo ) ;


signature:
public class KeyMetadata { /** * Sets the numeric id field */
public void setLongId ( P pojo , Long id ) { } }

implementation: if ( ! clazz . isAssignableFrom ( pojo . getClass ( ) ) ) throw new IllegalArgumentException ( "Trying to use metadata for " + clazz . getName ( ) + " to set key of " + pojo . getClass ( ) . getName ( ) ) ; this . idMeta . getProperty ( ) . set ( pojo , id ) ;


signature:
public class KeyMetadata { /** * Get the contents of the @ Parent field as a datastore key .
 * @ return null if there was no @ Parent field , or the field is null . */
private com . google . cloud . datastore . Key getParentRaw ( P pojo ) { } }

implementation: if ( parentMeta == null ) return null ; final Value < Object > value = parentMeta . getValue ( pojo , new SaveContext ( ) , Path . root ( ) ) ; return ( value == null || value . getType ( ) == ValueType . NULL ) ? null : ( com . google . cloud . datastore . Key ) value . get ( ) ;


signature:
public class ClassTranslatorFactory { /** * Recursively register this subclass with all the superclass translators . This works because we cache
 * translators uniquely in the factory . */
private void registerSubclass ( final ClassTranslator < P > translator , final TypeKey < ? super P > superclassTypeKey , final CreateContext ctx , final Path path ) { } }

implementation: if ( superclassTypeKey . getTypeAsClass ( ) == Object . class ) return ; @ SuppressWarnings ( "unchecked" ) final ClassTranslator < ? super P > superTranslator = create ( ( TypeKey ) superclassTypeKey , ctx , path ) ; superTranslator . registerSubclass ( translator ) ; registerSubclass ( translator , new TypeKey < > ( superclassTypeKey . getTypeAsClass ( ) . getSuperclass ( ) ) , ctx , path ) ;


signature:
public class TypeFactory { /** * Creates a type of class < tt > clazz < / tt > with < tt > arguments < / tt > as type arguments .
 * For example : < tt > parameterizedClass ( Map . class , Integer . class , String . class ) < / tt >
 * returns the type < tt > Map & lt ; Integer , String & gt ; < / tt > .
 * @ param clazz Type class of the type to create
 * @ param arguments Type arguments for the variables of < tt > clazz < / tt > , or null if these are not known .
 * @ return A { @ link ParameterizedType } ,
 * or simply < tt > clazz < / tt > if < tt > arguments < / tt > is < tt > null < / tt > or empty . */
public static Type parameterizedClass ( Class < ? > clazz , Type ... arguments ) { } }

implementation: return parameterizedInnerClass ( null , clazz , arguments ) ;


signature:
public class TypeFactory { /** * Creates a type of < tt > clazz < / tt > nested in < tt > owner < / tt > .
 * @ param owner The owner type . This should be a subtype of < tt > clazz . getDeclaringClass ( ) < / tt > ,
 * or < tt > null < / tt > if no owner is known .
 * @ param clazz Type class of the type to create
 * @ return A { @ link ParameterizedType } if the class declaring < tt > clazz < / tt > is generic and its type parameters
 * are known in < tt > owner < / tt > and < tt > clazz < / tt > itself has no type parameters .
 * Otherwise , just returns < tt > clazz < / tt > . */
public static Type innerClass ( Type owner , Class < ? > clazz ) { } }

implementation: return parameterizedInnerClass ( owner , clazz , ( Type [ ] ) null ) ;


signature:
public class TypeFactory { /** * Creates a type of < tt > clazz < / tt > with < tt > arguments < / tt > as type arguments , nested in < tt > owner < / tt > .
 * In the ideal case , this returns a { @ link ParameterizedType } with all generic information in it .
 * If some type arguments are missing or if the resulting type simply doesn ' t need any type parameters ,
 * it returns the raw < tt > clazz < / tt > .
 * Note that types with some parameters specified and others not , don ' t exist in Java .
 * If the caller does not know the exact < tt > owner < / tt > type or < tt > arguments < / tt > , < tt > null < / tt > should be given
 * ( or { @ link # parameterizedClass ( Class , Type . . . ) } or { @ link # innerClass ( Type , Class ) } could be used ) .
 * If they are not needed ( non - generic owner and / or < tt > clazz < / tt > has no type parameters ) , they will be filled in
 * automatically . If they are needed but are not given , the raw < tt > clazz < / tt > is returned .
 * The specified < tt > owner < / tt > may be any subtype of < tt > clazz . getDeclaringClass ( ) < / tt > . It is automatically
 * converted into the right parameterized version of the declaring class .
 * If < tt > clazz < / tt > is a < tt > static < / tt > ( nested ) class , the owner is not used .
 * @ param owner The owner type . This should be a subtype of < tt > clazz . getDeclaringClass ( ) < / tt > ,
 * or < tt > null < / tt > if no owner is known .
 * @ param clazz Type class of the type to create
 * @ param arguments Type arguments for the variables of < tt > clazz < / tt > , or null if these are not known .
 * @ return A { @ link ParameterizedType } if < tt > clazz < / tt > or the class declaring < tt > clazz < / tt > is generic ,
 * and all the needed type arguments are specified in < tt > owner < / tt > and < tt > arguments < / tt > .
 * Otherwise , just returns < tt > clazz < / tt > .
 * @ throws IllegalArgumentException if < tt > arguments < / tt > ( is non - null and ) has an incorrect length ,
 * or if one of the < tt > arguments < / tt > is not within the bounds declared on the matching type variable ,
 * or if owner is non - null but < tt > clazz < / tt > has no declaring class ( e . g . is a top - level class ) ,
 * or if owner is not a a subtype of < tt > clazz . getDeclaringClass ( ) < / tt > .
 * @ throws NullPointerException if < tt > clazz < / tt > or one of the elements in < tt > arguments < / tt > is null . */
public static Type parameterizedInnerClass ( Type owner , Class < ? > clazz , Type ... arguments ) { } }

implementation:
// never allow an owner on a class that doesn ' t have one
if ( clazz . getDeclaringClass ( ) == null && owner != null ) { throw new IllegalArgumentException ( "Cannot specify an owner type for a top level class" ) ; } Type realOwner = transformOwner ( owner , clazz ) ; if ( arguments == null ) { if ( clazz . getTypeParameters ( ) . length == 0 ) { // no arguments known , but no needed so just use an empty argument list .
// ( we can still end up with a generic type if the owner is generic )
arguments = new Type [ 0 ] ; } else { // missing type arguments , return the raw type
return clazz ; } } else { if ( arguments . length != clazz . getTypeParameters ( ) . length ) { throw new IllegalArgumentException ( "Incorrect number of type arguments for [" + clazz + "]: " + "expected " + clazz . getTypeParameters ( ) . length + ", but got " + arguments . length ) ; } } // if the class and its owner simply have no parameters at all , this is not a parameterized type
if ( ! GenericTypeReflector . isMissingTypeParameters ( clazz ) ) { return clazz ; } // if the owner type is missing type parameters and clazz is non - static , this is a raw type
if ( realOwner != null && ! Modifier . isStatic ( clazz . getModifiers ( ) ) && GenericTypeReflector . isMissingTypeParameters ( realOwner ) ) { return clazz ; } ParameterizedType result = new ParameterizedTypeImpl ( clazz , arguments , realOwner ) ; checkParametersWithinBound ( result ) ; return result ;


signature:
public class TypeFactory { /** * Check if the type arguments of the given type are within the bounds declared on the type parameters .
 * Only the type arguments of the type itself are checked , the possible owner type is assumed to be valid .
 * It does not follow the checks defined in the
 * < a href = " http : / / java . sun . com / docs / books / jls / third _ edition / html / typesValues . html # 4.5 " > JLS < / a > because there are
 * several problems with those ( see http : / / stackoverflow . com / questions / 7003009 for one ) .
 * Instead , this applies some intuition and follows what Java compilers seem to do .
 * @ param type possibly inconsistent type to check .
 * @ throws IllegalArgumentException if the type arguments are not within the bounds */
private static void checkParametersWithinBound ( ParameterizedType type ) { } }

implementation:
Type [ ] arguments = type . getActualTypeArguments ( ) ; TypeVariable < ? > [ ] typeParameters = ( ( Class < ? > ) type . getRawType ( ) ) . getTypeParameters ( ) ; // a map of type arguments in the type , to fill in variables in the bounds
VarMap varMap = new VarMap ( type ) ; // for every bound on every parameter
for ( int i = 0 ; i < arguments . length ; i ++ ) { for ( Type bound : typeParameters [ i ] . getBounds ( ) ) { // replace type variables in the bound by their value
Type replacedBound = varMap . map ( bound ) ; if ( arguments [ i ] instanceof WildcardType ) { WildcardType wildcardTypeParameter = ( WildcardType ) arguments [ i ] ; // Check if a type satisfying both the bounds of the variable and of the wildcard could exist
// upper bounds must not be mutually exclusive
for ( Type wildcardUpperBound : wildcardTypeParameter . getUpperBounds ( ) ) { if ( ! couldHaveCommonSubtype ( replacedBound , wildcardUpperBound ) ) { throw new TypeArgumentNotInBoundException ( arguments [ i ] , typeParameters [ i ] , bound ) ; } } // a lowerbound in the wildcard must satisfy every upperbound
for ( Type wildcardLowerBound : wildcardTypeParameter . getLowerBounds ( ) ) { if ( ! GenericTypeReflector . isSuperType ( replacedBound , wildcardLowerBound ) ) { throw new TypeArgumentNotInBoundException ( arguments [ i ] , typeParameters [ i ] , bound ) ; } } } else { if ( ! GenericTypeReflector . isSuperType ( replacedBound , arguments [ i ] ) ) { throw new TypeArgumentNotInBoundException ( arguments [ i ] , typeParameters [ i ] , bound ) ; } } } }


signature:
public class TypeFactory { /** * Checks if the intersection of two types is not empty . */
private static boolean couldHaveCommonSubtype ( Type type1 , Type type2 ) { } }

implementation:
// this is an optimistically naive implementation .
// if they are parameterized types their parameters need to be checked , . . .
// so we ' re just a bit too lenient here
Class < ? > erased1 = GenericTypeReflector . erase ( type1 ) ; Class < ? > erased2 = GenericTypeReflector . erase ( type2 ) ; // if they are both classes
if ( ! erased1 . isInterface ( ) && ! erased2 . isInterface ( ) ) { // then one needs to be a subclass of another
if ( ! erased1 . isAssignableFrom ( erased2 ) && ! erased2 . isAssignableFrom ( erased1 ) ) { return false ; } } return true ;


signature:
public class TypeFactory { /** * Transforms the given owner type into an appropriate one when constructing a parameterized type . */
private static Type transformOwner ( Type givenOwner , Class < ? > clazz ) { } }

implementation:
if ( givenOwner == null ) { // be lenient : if this is an inner class but no owner was specified , assume a raw owner type
// ( or if there is no owner just return null )
return clazz . getDeclaringClass ( ) ; } else { // If the specified owner is not of the declaring class ' type , but instead a subtype ,
// transform it into the declaring class with the exact type parameters .
// For example with " class StringOuter extends GenericOuter < String > " , transform
// " StringOuter . Inner " into " GenericOuter < String > . Inner " , just like the Java compiler does .
Type transformedOwner = GenericTypeReflector . getExactSuperType ( givenOwner , clazz . getDeclaringClass ( ) ) ; if ( transformedOwner == null ) { // null means it ' s not a supertype
throw new IllegalArgumentException ( "Given owner type [" + givenOwner + "] is not appropriate for [" + clazz + "]: it should be a subtype of " + clazz . getDeclaringClass ( ) ) ; } if ( Modifier . isStatic ( clazz . getModifiers ( ) ) ) { // for a static inner class , the owner shouldn ' t have type parameters
return GenericTypeReflector . erase ( transformedOwner ) ; } else { return transformedOwner ; } }


signature:
public class TypeFactory { /** * Creates a wildcard type with an upper bound .
 * For example < tt > wildcardExtends ( String . class ) < / tt > returns the type < tt > ? extends String < / tt > .
 * @ param upperBound Upper bound of the wildcard
 * @ return A wildcard type */
public static WildcardType wildcardExtends ( Type upperBound ) { } }

implementation: if ( upperBound == null ) { throw new NullPointerException ( ) ; } return new WildcardTypeImpl ( new Type [ ] { upperBound } , new Type [ ] { } ) ;


signature:
public class TypeFactory { /** * Creates a wildcard type with a lower bound .
 * For example < tt > wildcardSuper ( String . class ) < / tt > returns the type < tt > ? super String < / tt > .
 * @ param lowerBound Lower bound of the wildcard
 * @ return A wildcard type */
public static WildcardType wildcardSuper ( Type lowerBound ) { } }

implementation: if ( lowerBound == null ) { throw new NullPointerException ( ) ; } return new WildcardTypeImpl ( new Type [ ] { Object . class } , new Type [ ] { lowerBound } ) ;


signature:
public class TypeKey { /** * Checks not only the listed annotations but also annotations on the class . */
public < A extends Annotation > A getAnnotationAnywhere ( Class < A > annotationType ) { } }

implementation: A anno = getAnnotation ( annotationType ) ; if ( anno == null ) { Class < ? > clazz = ( Class < ? > ) GenericTypeReflector . erase ( type ) ; return clazz . getAnnotation ( annotationType ) ; } else { return anno ; }


signature:
public class Session { /** * Add / overwrite a SV . */
public void add ( final Key < ? > key , final SessionValue < ? > value ) { } }

implementation: if ( log . isTraceEnabled ( ) ) log . trace ( "Adding to session: {} -> {}" , key , value . getResult ( ) ) ; map . put ( key , value ) ;


signature:
public class Session { /** * Convenience method */
public void addValue ( final Key < ? > key , final Object value ) { } }

implementation: add ( key , new SessionValue < > ( new ResultNow < > ( value ) ) ) ;


signature:
public class Session { /** * Add all entries in the other session to this one */
public void addAll ( final Session other ) { } }

implementation: if ( log . isTraceEnabled ( ) ) log . trace ( "Adding all values to session: {}" , other . map . keySet ( ) ) ; map . putAll ( other . map ) ;


signature:
public class Deferrer { /** * Eliminate any deferred operations against the entity . Used when an explicit save ( or delete ) was
 * executed against the key , so we no longer need the deferred operation .
 * @ param keyOrEntity can be a Key , Key < ? > , Entity , or entity pojo */
public void undefer ( final Object keyOrEntity ) { } }

implementation:
if ( keyOrEntity instanceof Key < ? > ) { operations . remove ( ( Key < ? > ) keyOrEntity ) ; } else if ( keyOrEntity instanceof com . google . cloud . datastore . Key ) { operations . remove ( Key . create ( ( com . google . cloud . datastore . Key ) keyOrEntity ) ) ; } else if ( factory ( ) . keys ( ) . requiresAutogeneratedId ( keyOrEntity ) ) { // note might be FullEntity without complete key
autogeneratedIdSaves . remove ( keyOrEntity ) ; } else { final Key < ? > key = factory ( ) . keys ( ) . keyOf ( keyOrEntity ) ; operations . remove ( key ) ; }


signature:
public class LoadEngine { /** * Gets the result , possibly from the session , putting it in the session if necessary .
 * Also will recursively prepare the session with @ Load parents as appropriate .
 * @ throws NullPointerException if key is null */
public < T > Result < T > load ( final Key < T > key ) { } }

implementation:
if ( key == null ) throw new NullPointerException ( "You tried to load a null key!" ) ; final Result < T > result = round . get ( key ) ; // If we are running a transaction , enlist the result so that it gets processed on commit even
// if the client never materializes the result .
if ( ofy . getTransaction ( ) != null ) ( ( PrivateAsyncTransaction ) ofy . getTransaction ( ) ) . enlist ( result ) ; // Now check to see if we need to recurse and add our parent ( s ) to the round
if ( key . getParent ( ) != null ) { final KeyMetadata < ? > meta = ofy . factory ( ) . keys ( ) . getMetadata ( key ) ; // Is it really possible for this to be null ?
if ( meta != null ) { if ( meta . shouldLoadParent ( loadArrangement ) ) { load ( key . getParent ( ) ) ; } } } return result ;


signature:
public class LoadEngine { /** * Starts asychronous fetching of the batch . */
public void execute ( ) { } }

implementation: if ( round . needsExecution ( ) ) { Round old = round ; round = old . next ( ) ; old . execute ( ) ; }


signature:
public class LoadEngine { /** * Create a Ref for the key , and maybe start a load operation depending on current load groups .
 * @ param rootEntity is the entity key which holds this property ( possibly through some level of embedded objects ) */
public < T > Ref < T > makeRef ( final Key < ? > rootEntity , final LoadConditions loadConditions , final Key < T > key ) { } }

implementation: final Ref < T > ref = new LiveRef < > ( key , ofy ) ; if ( shouldLoad ( loadConditions ) ) { load ( key ) ; } return ref ;


signature:
public class LoadEngine { /** * Fetch the keys from the async datastore using the current transaction context */
public Result < Map < com . google . cloud . datastore . Key , Entity > > fetch ( Set < com . google . cloud . datastore . Key > keys ) { } }

implementation: log . debug ( "Fetching {} keys: {}" , keys . size ( ) , keys ) ; final Future < Map < com . google . cloud . datastore . Key , Entity > > fut = datastore . get ( keys , readOptions . toArray ( new ReadOption [ readOptions . size ( ) ] ) ) ; return ResultAdapter . create ( fut ) ;


signature:
public class LoadEngine { /** * Converts a datastore entity into a typed pojo object
 * @ return an assembled pojo , or the Entity itself if the kind is not registered , or null if the input value was null */
@ SuppressWarnings ( "unchecked" ) public < T > T load ( final BaseEntity < com . google . cloud . datastore . Key > ent , final LoadContext ctx ) { } }

implementation: if ( ent == null ) return null ; final EntityMetadata < T > meta = ofy . factory ( ) . getMetadata ( ent . getKey ( ) . getKind ( ) ) ; if ( meta == null ) return ( T ) ent ; else return meta . load ( ent , ctx ) ;


signature:
public class QueryDef { /** * Convenince method that creates a composite filter with any existing filter ( if present ) */
public QueryDef andFilter ( final Filter addFilter ) { } }

implementation: return filter ( this . filter == null ? addFilter : CompositeFilter . and ( this . filter , addFilter ) ) ;


signature:
public class DeleteTypeImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . DeleteType # parent ( java . lang . Object ) */
@ Override public DeleteIds parent ( final Object keyOrEntity ) { } }

implementation: final Key < ? > parentKey = factory ( ) . keys ( ) . anythingToKey ( keyOrEntity ) ; return new DeleteTypeImpl ( deleter , type , parentKey ) ;


signature:
public class DeleteTypeImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . DeleteIds # id ( java . lang . String ) */
@ Override public Result < Void > id ( final String id ) { } }

implementation: return ids ( Collections . singleton ( id ) ) ;


signature:
public class DeleteTypeImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . DeleteIds # ids ( java . lang . String [ ] ) */
@ Override public Result < Void > ids ( final String ... ids ) { } }

implementation: return ids ( Arrays . asList ( ids ) ) ;


signature:
public class DeleteTypeImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . DeleteIds # ids ( java . lang . Iterable ) */
@ Override public < S > Result < Void > ids ( final Iterable < S > ids ) { } }

implementation: return this . deleter . keys ( factory ( ) . keys ( ) . createKeys ( parent , type , ids ) ) ;


signature:
public class MergeFuture { /** * / * ( non - Javadoc )
 * @ see java . util . concurrent . Future # get ( ) */
@ Override public Map < K , V > get ( ) throws InterruptedException , ExecutionException { } }

implementation: if ( this . pending != null ) { this . loaded . putAll ( this . pending . get ( ) ) ; this . pending = null ; } return this . loaded ;


signature:
public class MergeFuture { /** * / * ( non - Javadoc )
 * @ see java . util . concurrent . Future # get ( long , java . util . concurrent . TimeUnit ) */
@ Override public Map < K , V > get ( long timeout , TimeUnit unit ) throws InterruptedException , ExecutionException , TimeoutException { } }

implementation: if ( this . pending != null ) { this . loaded . putAll ( this . pending . get ( timeout , unit ) ) ; this . pending = null ; } return this . loaded ;


signature:
public class Keys { /** * < p > Gets the Key < T > given an object that might be a Key , Key < T > , or entity . < / p >
 * @ param keyOrEntity must be a Key , Key < T > , or registered entity .
 * @ throws NullPointerException if keyOrEntity is null
 * @ throws IllegalArgumentException if keyOrEntity is not a Key , Key < T > , or registered entity */
@ SuppressWarnings ( "unchecked" ) public < T > Key < T > anythingToKey ( final Object keyOrEntity ) { } }

implementation: if ( keyOrEntity instanceof Key < ? > ) return ( Key < T > ) keyOrEntity ; else if ( keyOrEntity instanceof com . google . cloud . datastore . Key ) return Key . create ( ( com . google . cloud . datastore . Key ) keyOrEntity ) ; else if ( keyOrEntity instanceof Ref ) return ( ( Ref < T > ) keyOrEntity ) . key ( ) ; else if ( keyOrEntity instanceof FullEntity < ? > ) return Key . create ( getKey ( ( FullEntity < ? > ) keyOrEntity ) ) ; else return keyOf ( ( T ) keyOrEntity ) ;


signature:
public class Keys { /** * < p > Gets the raw datstore Key given an object that might be a Key , Key < T > , or entity . < / p >
 * @ param keyOrEntity must be a Key , Key < T > , or registered entity .
 * @ throws NullPointerException if keyOrEntity is null
 * @ throws IllegalArgumentException if keyOrEntity is not a Key , Key < T > , or registered entity */
public com . google . cloud . datastore . Key anythingToRawKey ( final Object keyOrEntity ) { } }

implementation: if ( keyOrEntity instanceof com . google . cloud . datastore . Key ) return ( com . google . cloud . datastore . Key ) keyOrEntity ; else if ( keyOrEntity instanceof Key < ? > ) return ( ( Key < ? > ) keyOrEntity ) . getRaw ( ) ; else if ( keyOrEntity instanceof Ref ) return ( ( Ref < ? > ) keyOrEntity ) . key ( ) . getRaw ( ) ; else if ( keyOrEntity instanceof FullEntity < ? > ) return getKey ( ( FullEntity < ? > ) keyOrEntity ) ; else return rawKeyOf ( keyOrEntity ) ;


signature:
public class Keys { /** * Construct a Key from a Long or String id
 * @ param id must be either Long or String */
public com . google . cloud . datastore . Key createRawAny ( final com . google . cloud . datastore . Key parent , final String kind , final Object id ) { } }

implementation: if ( id instanceof String ) return createRaw ( parent , kind , ( String ) id ) ; else if ( id instanceof Long ) return createRaw ( parent , kind , ( Long ) id ) ; else throw new IllegalArgumentException ( "id '" + id + "' must be String or Long" ) ;


signature:
public class Keys { /** * Construct a Key < ? > from a Long or String id
 * @ param id must be either Long or String */
public < T > Key < T > createKeyAny ( final Key < ? > parent , final Class < T > kind , final Object id ) { } }

implementation: if ( id instanceof String ) return createKey ( parent , kind , ( String ) id ) ; else if ( id instanceof Long ) return createKey ( parent , kind , ( Long ) id ) ; else throw new IllegalArgumentException ( "id '" + id + "' must be String or Long" ) ;


signature:
public class Keys { /** * Null - safe extraction of the raw key */
public static com . google . cloud . datastore . Key raw ( final Key < ? > key ) { } }

implementation: return key == null ? null : key . getRaw ( ) ;


signature:
public class Keys { /** * Make a list of Key < ? > s
 * @ param ids must contain either Long or String */
public < T > List < Key < T > > createKeys ( final Key < ? > parent , final Class < T > kind , final Iterable < ? > ids ) { } }

implementation: return StreamSupport . stream ( ids . spliterator ( ) , false ) . map ( id -> createKeyAny ( parent , kind , id ) ) . collect ( Collectors . toList ( ) ) ;


signature:
public class Keys { /** * Gets the String or Long id from the key as a Value , or null if incomplete */
@ SuppressWarnings ( "unchecked" ) public static < S > Value < S > getIdValue ( final IncompleteKey key ) { } }

implementation: if ( key instanceof com . google . cloud . datastore . Key ) { final com . google . cloud . datastore . Key completeKey = ( com . google . cloud . datastore . Key ) key ; if ( completeKey . hasId ( ) ) return ( Value < S > ) LongValue . of ( completeKey . getId ( ) ) ; else return ( Value < S > ) StringValue . of ( completeKey . getName ( ) ) ; } else { return null ; }


signature:
public class Keys { /** * Understands both the legacy format " ag1zfnZvb2Rvb2R5bmUwcgcLEgFCGAEM " and new format ,
 * providing the key either way . */
@ SneakyThrows public static com . google . cloud . datastore . Key fromUrlSafe ( final String urlSafeKey ) { } }

implementation: if ( urlSafeKey . startsWith ( "a" ) ) { return KeyFormat . INSTANCE . parseOldStyleAppEngineKey ( urlSafeKey ) ; } else { return com . google . cloud . datastore . Key . fromUrlSafe ( urlSafeKey ) ; }


signature:
public class TransactorYes { /** * This version goes back to life without a transaction , but preserves current options .
 * We use the session from the parent , ie life before transactions . */
@ Override public ObjectifyImpl transactionless ( final ObjectifyImpl parent ) { } }

implementation: return parent . makeNew ( next -> new TransactorNo ( next , parentTransactor . getSession ( ) ) ) ;


signature:
public class TransactorYes { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . impl . cmd . Transactor # execute ( com . googlecode . objectify . TxnType , com . googlecode . objectify . Work ) */
@ Override public < R > R execute ( final ObjectifyImpl parent , final TxnType txnType , final Work < R > work ) { } }

implementation: switch ( txnType ) { case MANDATORY : case REQUIRED : case SUPPORTS : return work . run ( ) ; case NOT_SUPPORTED : return transactionless ( parent , work ) ; case NEVER : throw new IllegalStateException ( "MANDATORY transaction but no transaction present" ) ; case REQUIRES_NEW : return transactNew ( parent , Transactor . DEFAULT_TRY_LIMIT , work ) ; default : throw new IllegalStateException ( "Impossible, some unknown txn type" ) ; }


signature:
public class TransactorYes { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . impl . Transactor # transact ( com . googlecode . objectify . impl . ObjectifyImpl , com . googlecode . objectify . Work ) */
@ Override public < R > R transact ( final ObjectifyImpl parent , final Work < R > work ) { } }

implementation: return work . run ( ) ;


signature:
public class TransactorYes { /** * We need to make sure the parentSession is the transactionless session , not the session
 * for our transaction . This gives proper transaction isolation . */
@ Override public < R > R transactNew ( final ObjectifyImpl parent , final int limitTries , final Work < R > work ) { } }

implementation: return transactionless ( parent ) . transactNew ( limitTries , work ) ;


signature: public class LoadTypeImpl { @ Override public Query < T > filter ( final Filter filter ) { } }

implementation: final QueryImpl < T > q = createQuery ( ) ; q . addFilter ( filter ) ; return q ;


signature:
public class LoadTypeImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . Query # order ( java . lang . String ) */
@ Override public Query < T > order ( String condition ) { } }

implementation: QueryImpl < T > q = createQuery ( ) ; q . addOrder ( condition ) ; return q ;


signature:
public class LoadTypeImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . LoadIds # id ( java . lang . String ) */
@ Override public LoadResult < T > id ( final String id ) { } }

implementation: return loader . key ( this . makeKey ( id ) ) ;


signature:
public class LoadTypeImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . LoadIds # ids ( Long [ ] ) */
@ Override public Map < Long , T > ids ( final Long ... ids ) { } }

implementation: return ids ( Arrays . asList ( ids ) ) ;


signature:
public class LoadTypeImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . LoadIds # ids ( java . lang . String [ ] ) */
@ Override public Map < String , T > ids ( final String ... ids ) { } }


signature:
public class TransactorNo { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . impl . cmd . Transactor # execute ( com . googlecode . objectify . TxnType , com . googlecode . objectify . Work ) */
@ Override public < R > R execute ( final ObjectifyImpl parent , final TxnType txnType , final Work < R > work ) { } }

implementation: switch ( txnType ) { case MANDATORY : throw new IllegalStateException ( "MANDATORY transaction but no transaction present" ) ; case NOT_SUPPORTED : case NEVER : case SUPPORTS : return work . run ( ) ; case REQUIRED : case REQUIRES_NEW : return transact ( parent , work ) ; default : throw new IllegalStateException ( "Impossible, some unknown txn type" ) ; }


signature:
public class TransactorNo { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . impl . Transactor # transact ( com . googlecode . objectify . impl . ObjectifyImpl , com . googlecode . objectify . Work ) */
@ Override public < R > R transact ( final ObjectifyImpl parent , final Work < R > work ) { } }

implementation: return this . transactNew ( parent , DEFAULT_TRY_LIMIT , work ) ;


signature:
public class TransactorNo { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . impl . Transactor # transactNew ( com . googlecode . objectify . impl . ObjectifyImpl , int , com . googlecode . objectify . Work ) */
@ Override public < R > R transactNew ( final ObjectifyImpl parent , int limitTries , final Work < R > work ) { } }

implementation:
Preconditions . checkArgument ( limitTries >= 1 ) ; final int ORIGINAL_TRIES = limitTries ; while ( true ) { try { return transactOnce ( parent , work ) ; } catch ( DatastoreException ex ) { // This doesn ' t work because the SDK considers all transactions to be non - retryable . Objectify has always
// assumed that transactions are idempotent and retries accordingly . So we have to explicitly check against
// code 10 , which is ABORTED . https : / / cloud . google . com / datastore / docs / concepts / errors
// if ( ! ex . isRetryable ( ) )
// throw ex ;
// I hate this so much . Sometimes the transaction gets closed by the datastore during contention and
// then it proceeds to freak out and 503.
if ( Code . ABORTED . getNumber ( ) == ex . getCode ( ) || ( Code . INVALID_ARGUMENT . getNumber ( ) == ex . getCode ( ) && ex . getMessage ( ) . contains ( "transaction closed" ) ) ) { // Continue to retry logic
} else { throw ex ; } if ( -- limitTries > 0 ) { log . warn ( "Retrying {} failure for {}: {}" , ex . getReason ( ) , work , ex ) ; log . trace ( "Details of transaction failure" , ex ) ; try { // Do increasing backoffs with randomness
Thread . sleep ( Math . min ( 10000 , ( long ) ( 0.5 * Math . random ( ) + 0.5 ) * 200 * ( ORIGINAL_TRIES - limitTries + 2 ) ) ) ; } catch ( InterruptedException ignored ) { } } else { throw new DatastoreException ( ex . getCode ( ) , "Failed retrying datastore " + ORIGINAL_TRIES + " times " , ex . getReason ( ) , ex ) ; } } }


signature:
public class TransactorNo { /** * One attempt at executing a transaction */
private < R > R transactOnce ( final ObjectifyImpl parent , final Work < R > work ) { } }

implementation: final ObjectifyImpl txnOfy = factory . open ( parent . getOptions ( ) , next -> new TransactorYes ( next , this ) ) ; boolean committedSuccessfully = false ; try { final R result = work . run ( ) ; txnOfy . flush ( ) ; txnOfy . getTransaction ( ) . commit ( ) ; committedSuccessfully = true ; return result ; } finally { if ( txnOfy . getTransaction ( ) . isActive ( ) ) { try { txnOfy . getTransaction ( ) . rollback ( ) ; } catch ( RuntimeException ex ) { log . error ( "Rollback failed, suppressing error" , ex ) ; } } txnOfy . close ( ) ; if ( committedSuccessfully ) { ( ( PrivateAsyncTransaction ) txnOfy . getTransaction ( ) ) . runCommitListeners ( ) ; } }


signature:
public class FieldProperty { /** * Tests whether a set of conditions match .
 * @ param conditions can be null ; this always matches false
 * @ return true if we match the conditions , false if we do not */
private boolean matches ( Object onPojo , If < ? , ? > [ ] conditions ) { } }

implementation: if ( conditions == null ) return false ; Object value = this . get ( onPojo ) ; for ( If < ? , ? > condition : conditions ) { @ SuppressWarnings ( "unchecked" ) If < Object , Object > cond = ( If < Object , Object > ) condition ; if ( cond . matchesValue ( value ) ) return true ; if ( cond . matchesPojo ( onPojo ) ) return true ; } return false ;


signature:
public class LiveRef { /** * Get the current objectify instance associated with this ref */
private Objectify ofy ( ) { } }

implementation:
// If we have an expired transaction context , we need a new context
if ( ofy == null || ( ofy . getTransaction ( ) != null && ! ofy . getTransaction ( ) . isActive ( ) ) ) ofy = ObjectifyService . ofy ( ) ; return ofy ;


signature:
public class ObjectifyFactory { /** * Might produce a caching version if caching is enabled . */
public AsyncDatastore asyncDatastore ( final boolean enableGlobalCache ) { } }

implementation: if ( this . entityMemcache != null && enableGlobalCache && this . registrar . isCacheEnabled ( ) ) return new CachingAsyncDatastore ( asyncDatastore ( ) , this . entityMemcache ) ; else return asyncDatastore ( ) ;


signature:
public class ObjectifyFactory { /** * < p > Construct an instance of the specified type . Objectify uses this method whenever possible to create
 * instances of entities , condition classes , or other types ; by overriding this method you can substitute Guice or other
 * dependency injection mechanisms . By default it constructs with a simple no - args constructor . < / p > */
@ Override public < T > T construct ( final Class < T > type ) { } }

implementation:
// We do this instead of calling newInstance directly because this lets us work around accessiblity
final Constructor < T > ctor = TypeUtils . getNoArgConstructor ( type ) ; return TypeUtils . newInstance ( ctor ) ;


signature:
public class ObjectifyFactory { /** * < p > Construct a collection of the specified type and the specified size for use on a POJO field . You can override
 * this with Guice or whatnot . < / p >
 * < p > The default is to call construct ( Class ) , with one twist - if a Set , SortedSet , or List interface is presented ,
 * Objectify will construct a HashSet , TreeSet , or ArrayList ( respectively ) . If you override this method with
 * dependency injection and you use uninitialized fields of these interface types in your entity pojos , you will
 * need to bind these interfaces to concrete types . < / p > */
@ SuppressWarnings ( "unchecked" ) public < T extends Collection < ? > > T constructCollection ( final Class < T > type , final int size ) { } }

implementation: if ( ( Class < ? > ) type == List . class || ( Class < ? > ) type == Collection . class ) return ( T ) new ArrayList < > ( size ) ; else if ( ( Class < ? > ) type == Set . class ) return ( T ) new HashSet < > ( ( int ) ( size * 1.5 ) ) ; else if ( ( Class < ? > ) type == SortedSet . class ) return ( T ) new TreeSet < > ( ) ; else return construct ( type ) ;


signature:
public class ObjectifyFactory { /** * < p > Construct a map of the specified type for use on a POJO field . You can override this with Guice or whatnot . < / p >
 * < p > The default is to call construct ( Class ) , with one twist - if a Map or SortedMap List interface is presented ,
 * Objectify will construct a HashMap or TreeMap ( respectively ) . If you override this method with
 * dependency injection and you use uninitialized fields of these interface types in your entity pojos , you will
 * need to bind these interfaces to concrete types . < / p > */
@ SuppressWarnings ( "unchecked" ) public < T extends Map < ? , ? > > T constructMap ( final Class < T > type ) { } }

implementation: if ( ( Class < ? > ) type == Map . class ) return ( T ) new HashMap < > ( ) ; else if ( ( Class < ? > ) type == SortedMap . class ) return ( T ) new TreeMap < > ( ) ; else return construct ( type ) ;


signature:
public class ObjectifyFactory { /** * Named differently so you don ' t accidentally use the Object form
 * @ return the metadata for a kind of typed object .
 * @ throws IllegalArgumentException if the kind has not been registered */
@ SuppressWarnings ( "unchecked" ) public < T > EntityMetadata < T > getMetadataForEntity ( final T obj ) throws IllegalArgumentException { } }

implementation:
// Type erasure sucks
return ( EntityMetadata < T > ) this . getMetadata ( obj . getClass ( ) ) ;


signature:
public class ObjectifyFactory { /** * Allocates a single id from the allocator for the specified kind . Safe to use in concert
 * with the automatic generator . This is just a convenience method for allocateIds ( ) .
 * @ param clazz must be a registered entity class with a Long or long id field .
 * @ return a key with an id that is unique to the kind */
public < T > Key < T > allocateId ( final Class < T > clazz ) { } }

implementation: return allocateIds ( clazz , 1 ) . iterator ( ) . next ( ) ;


signature:
public class ObjectifyFactory { /** * < p > Preallocate multiple unique ids within the namespace of the
 * specified entity class . These ids can be used in concert with the normal
 * automatic allocation of ids when save ( ) ing entities with null Long id fields . < / p >
 * < p > The { @ code KeyRange < ? > } class is deprecated ; when using this method ,
 * treat the return value as { @ code List < Key < T > > } . < / p >
 * @ param clazz must be a registered entity class with a Long or long id field .
 * @ param num must be > = 1 and small enough we can fit a set of keys in RAM . */
public < T > KeyRange < T > allocateIds ( final Class < T > clazz , final int num ) { } }

implementation: final String kind = Key . getKind ( clazz ) ; final IncompleteKey incompleteKey = datastore ( ) . newKeyFactory ( ) . setKind ( kind ) . newKey ( ) ; return allocate ( incompleteKey , num ) ;


signature:
public class ObjectifyFactory { /** * Preallocate a contiguous range of unique ids within the namespace of the
 * specified entity class and the parent key . These ids can be used in concert with the normal
 * automatic allocation of ids when put ( ) ing entities with null Long id fields .
 * @ param parentKeyOrEntity must be a legitimate parent for the class type . It need not
 * point to an existent entity , but it must be the correct type for clazz .
 * @ param clazz must be a registered entity class with a Long or long id field , and
 * a parent key of the correct type .
 * @ param num must be > = 1 and < = 1 billion */
public < T > KeyRange < T > allocateIds ( final Object parentKeyOrEntity , final Class < T > clazz , final int num ) { } }

implementation: final Key < ? > parent = keys ( ) . anythingToKey ( parentKeyOrEntity ) ; final String kind = Key . getKind ( clazz ) ; final IncompleteKey incompleteKey = com . google . cloud . datastore . Key . newBuilder ( parent . getRaw ( ) , kind ) . build ( ) ; return allocate ( incompleteKey , num ) ;


signature:
public class ObjectifyFactory { /** * Allocate num copies of the incompleteKey */
private < T > KeyRange < T > allocate ( final IncompleteKey incompleteKey , final int num ) { } }

implementation: final IncompleteKey [ ] allocations = new IncompleteKey [ num ] ; Arrays . fill ( allocations , incompleteKey ) ; final List < Key < T > > typedKeys = datastore ( ) . allocateId ( allocations ) . stream ( ) . map ( Key :: < T > create ) . collect ( Collectors . toList ( ) ) ; return new KeyRange < > ( typedKeys ) ;


signature:
public class ObjectifyFactory { /** * The method to call at any time to get the current Objectify , which may change depending on txn context .
 * Normally you should use the static { @ link ObjectifyService # ofy ( ) } which calls this method . */
public Objectify ofy ( ) { } }

implementation: final Deque < Objectify > stack = stacks . get ( ) ; if ( stack . isEmpty ( ) ) throw new IllegalStateException ( "You have not started an Objectify context. You are probably missing the " + "ObjectifyFilter. If you are not running in the context of an http request, see the " + "ObjectifyService.run() method." ) ; return stack . getLast ( ) ;


signature:
public class ObjectifyFactory { /** * < p > Start a scope of work . This is the outermost scope of work , typically created by the ObjectifyFilter
 * or by one of the methods on ObjectifyService . You need one of these to do anything at all . < / p > */
public ObjectifyImpl open ( ) { } }

implementation: final ObjectifyImpl objectify = new ObjectifyImpl ( this ) ; stacks . get ( ) . add ( objectify ) ; return objectify ;


signature:
public class ObjectifyFactory { /** * This is only public because it is used from the impl package ; don ' t use this as a public API */
public ObjectifyImpl open ( final ObjectifyOptions opts , final TransactorSupplier transactorSupplier ) { } }

implementation: final ObjectifyImpl objectify = new ObjectifyImpl ( this , opts , transactorSupplier ) ; stacks . get ( ) . add ( objectify ) ; return objectify ;


signature:
public class ObjectifyFactory { /** * Pops context off of stack after a transaction completes . For internal housekeeping only . */
public void close ( final Objectify ofy ) { } }

implementation: final Deque < Objectify > stack = stacks . get ( ) ; if ( stack . isEmpty ( ) ) throw new IllegalStateException ( "You have already destroyed the Objectify context." ) ; final Objectify popped = stack . removeLast ( ) ; assert popped == ofy : "Mismatched objectify instances; somehow the stack was corrupted" ;


signature: public class RawValueTranslatorFactory { @ Override public Translator < Value < Object > , Object > create ( final TypeKey < Value < Object > > tk , final CreateContext ctx , final Path path ) { } }

implementation: if ( ! tk . isAssignableTo ( Value . class ) ) return null ; return new NullSafeTranslator < Value < Object > , Object > ( ) { @ Override protected Value < Object > loadSafe ( final Value < Object > value , final LoadContext ctx , final Path path ) throws SkipException { return value ; } @ Override protected Value < Object > saveSafe ( final Value < Object > pojo , final boolean index , final SaveContext ctx , final Path path ) throws SkipException { return pojo ; } } ;


signature:
public class ObjectifyService { /** * < p > Runs one unit of work , making the root Objectify context available . This does not start a transaction ,
 * but it makes the static ofy ( ) method return an appropriate object . < / p >
 * < p > Normally you do not need to use this method . When servicing a normal request , the ObjectifyFilter
 * will run this for you . This method is useful for using Objectify outside of a normal request -
 * using the remote api , for example . < / p >
 * < p > Alternatively , you can use the begin ( ) method and close the session manually . < / p >
 * @ return the result of the work . */
public static < R > R run ( final Work < R > work ) { } }

implementation: try ( Closeable closeable = begin ( ) ) { return work . run ( ) ; }


signature:
public class Values { /** * The datastore has a weird behavior of reordering values in a list so that indexed ones come before nonindexed
 * ones . This can really mess up ordered lists . So if we find a heterogeneous list , we need to force index everything . */
public static void homogenizeIndexes ( final List < Value < ? > > list ) { } }

implementation: if ( isIndexHomogeneous ( list ) ) return ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { final Value < ? > value = list . get ( i ) ; if ( value . excludeFromIndexes ( ) ) list . set ( i , index ( value , true ) ) ; }


signature:
public class IntegerTranslatorFactory { /** * Coerces the value to be a number of the specified type ; needed because
 * all numbers come back from the datastore as Long / Double and this screws up
 * any type that expects something smaller . We don ' t need to worry about primitive
 * types because we wrapped the class earlier . */
private Number coerceNumber ( final Number value , final Class < ? > type ) { } }

implementation: if ( type == Byte . class ) return value . byteValue ( ) ; else if ( type == Short . class ) return value . shortValue ( ) ; else if ( type == Integer . class ) return value . intValue ( ) ; else if ( type == Long . class ) return value . longValue ( ) ; else throw new IllegalArgumentException ( ) ; // should be impossible


signature:
public class SimpleQueryImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . QueryCommon # filterKey ( java . lang . String , java . lang . Object ) */
@ Override public QueryImpl < T > filterKey ( String condition , Object value ) { } }

implementation: QueryImpl < T > q = createQuery ( ) ; q . addFilter ( KEY_RESERVED_PROPERTY + " " + condition . trim ( ) , value ) ; return q ;


signature:
public class SimpleQueryImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . Query # ancestor ( java . lang . Object ) */
@ Override public QueryImpl < T > ancestor ( Object keyOrEntity ) { } }

implementation: QueryImpl < T > q = createQuery ( ) ; q . setAncestor ( keyOrEntity ) ; return q ;


signature:
public class SimpleQueryImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . Query # limit ( int ) */
@ Override public QueryImpl < T > limit ( int value ) { } }

implementation: QueryImpl < T > q = createQuery ( ) ; q . setLimit ( value ) ; return q ;


signature:
public class SimpleQueryImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . Query # offset ( int ) */
@ Override public QueryImpl < T > offset ( int value ) { } }

implementation: QueryImpl < T > q = createQuery ( ) ; q . setOffset ( value ) ; return q ;


signature:
public class SimpleQueryImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . Query # startCursor ( com . google . cloud . datastore . Cursor ) */
@ Override public QueryImpl < T > startAt ( Cursor value ) { } }

implementation: QueryImpl < T > q = createQuery ( ) ; q . setStartCursor ( value ) ; return q ;


signature:
public class SimpleQueryImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . Query # endCursor ( com . google . cloud . datastore . Cursor ) */
@ Override public QueryImpl < T > endAt ( Cursor value ) { } }

implementation: QueryImpl < T > q = createQuery ( ) ; q . setEndCursor ( value ) ; return q ;


signature:
public class SimpleQueryImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . Query # chunk ( int ) */
@ Override public QueryImpl < T > chunk ( int value ) { } }

implementation: QueryImpl < T > q = createQuery ( ) ; q . setChunk ( value ) ; return q ;


signature:
public class SimpleQueryImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . SimpleQuery # hybrid ( boolean ) */
@ Override public QueryImpl < T > hybrid ( boolean force ) { } }

implementation: QueryImpl < T > q = createQuery ( ) ; q . setHybrid ( force ) ; return q ;


signature:
public class SimpleQueryImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . Query # keys ( ) */
@ Override public QueryKeys < T > keys ( ) { } }

implementation: QueryImpl < T > q = createQuery ( ) ; q . checkKeysOnlyOk ( ) ; return new QueryKeysImpl < > ( q ) ;


signature:
public class SimpleQueryImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . SimpleQuery # distinct ( boolean ) */
@ Override public QueryImpl < T > distinct ( boolean value ) { } }

implementation: QueryImpl < T > q = createQuery ( ) ; q . setDistinct ( value ) ; return q ;


signature:
public class SimpleQueryImpl { /** * / * ( non - Javadoc )
 * @ see com . googlecode . objectify . cmd . SimpleQuery # project ( String . . . ) */
@ Override public QueryImpl < T > project ( String ... fields ) { } }

implementation: QueryImpl < T > q = createQuery ( ) ; q . addProjection ( fields ) ; return q ;


signature:
public class Ref { /** * Key . create ( Blah . class , id ) is easier to type than new Key < Blah > ( Blah . class , id ) */
public static < T > Ref < T > create ( Key < T > key ) { } }

implementation: if ( key == null ) throw new NullPointerException ( "Cannot create a Ref from a null key" ) ; return new LiveRef < > ( key ) ;


signature:
public class Ref { /** * Creates a Ref from a registered pojo entity */
public static < T > Ref < T > create ( T value ) { } }

implementation: Key < T > key = Key . create ( value ) ; return create ( key ) ;


signature:
public class Ref { /** * Obtain the entity value , throwing an exception if the entity was not found .
 * @ return the entity referenced . Never returns null .
 * @ throws NotFoundException if the specified entity was not found */
final public T safe ( ) throws NotFoundException { } }

implementation: T t = this . get ( ) ; if ( t == null ) throw new NotFoundException ( key ( ) ) ; else return t ;