idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
14,300
private void process ( ) { metadata = new EmbeddedMetadata ( field ) ; // Make sure the class has @Embeddable annotation if ( ! clazz . isAnnotationPresent ( Embeddable . class ) ) { String message = String . format ( "Class %s must have %s annotation" , clazz . getName ( ) , Embeddable . class . getName ( ) ) ; throw new EntityManagerException ( message ) ; } // Check the mapped name and indexed attributes Embedded embeddedAnnotation = field . getField ( ) . getAnnotation ( Embedded . class ) ; String mappedName = embeddedAnnotation . name ( ) ; if ( mappedName == null || mappedName . trim ( ) . length ( ) == 0 ) { mappedName = field . getName ( ) ; } metadata . setMappedName ( mappedName ) ; metadata . setIndexed ( embeddedAnnotation . indexed ( ) ) ; metadata . setOptional ( embeddedAnnotation . optional ( ) ) ; // If there is an annotation for storing the embedded with Imploded // strategy... if ( field . getField ( ) . isAnnotationPresent ( Imploded . class ) ) { metadata . setStorageStrategy ( StorageStrategy . IMPLODED ) ; } processFields ( ) ; }
Worker class for introspection .
272
7
14,301
private void processFields ( ) { List < Field > children = IntrospectionUtils . getPersistableFields ( clazz ) ; for ( Field child : children ) { if ( child . isAnnotationPresent ( Embedded . class ) ) { processEmbeddedField ( child ) ; } else { processSimpleField ( child ) ; } } }
Processes each field in this embedded object and updates the metadata .
75
13
14,302
private void processPropertyOverride ( PropertyMetadata propertyMetadata ) { String qualifiedName = field . getQualifiedName ( ) + "." + propertyMetadata . getField ( ) . getName ( ) ; Property override = entityMetadata . getPropertyOverride ( qualifiedName ) ; if ( override != null ) { String mappedName = override . name ( ) ; if ( mappedName != null && mappedName . trim ( ) . length ( ) > 0 ) { propertyMetadata . setMappedName ( mappedName ) ; } propertyMetadata . setIndexed ( override . indexed ( ) ) ; propertyMetadata . setOptional ( override . optional ( ) ) ; } }
Processes the override if any for the given property .
142
11
14,303
private void validateIntent ( ) { if ( entityMetadata . isProjectedEntity ( ) && ! intent . isValidOnProjectedEntities ( ) ) { String message = String . format ( "Operation %s is not allowed for ProjectedEntity %s" , intent , entity . getClass ( ) . getName ( ) ) ; throw new EntityManagerException ( message ) ; } }
Validates if the Intent is legal for the entity being marshalled .
83
14
14,304
private BaseEntity < ? > marshal ( ) { marshalKey ( ) ; if ( key instanceof Key ) { entityBuilder = Entity . newBuilder ( ( Key ) key ) ; } else { entityBuilder = FullEntity . newBuilder ( key ) ; } marshalFields ( ) ; marshalAutoTimestampFields ( ) ; if ( intent == Intent . UPDATE ) { marshalVersionField ( ) ; } marshalEmbeddedFields ( ) ; return entityBuilder . build ( ) ; }
Marshals the given entity and and returns the equivalent Entity needed for the underlying Cloud Datastore API .
107
21
14,305
public static Key marshalKey ( DefaultEntityManager entityManager , Object entity ) { Marshaller marshaller = new Marshaller ( entityManager , entity , Intent . DELETE ) ; marshaller . marshalKey ( ) ; return ( Key ) marshaller . key ; }
Extracts the key from the given object entity and returns it . The entity must have its ID set .
60
22
14,306
private void marshalKey ( ) { Key parent = null ; ParentKeyMetadata parentKeyMetadata = entityMetadata . getParentKeyMetadata ( ) ; if ( parentKeyMetadata != null ) { DatastoreKey parentDatastoreKey = ( DatastoreKey ) getFieldValue ( parentKeyMetadata ) ; if ( parentDatastoreKey != null ) { parent = parentDatastoreKey . nativeKey ( ) ; } } IdentifierMetadata identifierMetadata = entityMetadata . getIdentifierMetadata ( ) ; IdClassMetadata idClassMetadata = identifierMetadata . getIdClassMetadata ( ) ; DataType identifierType = identifierMetadata . getDataType ( ) ; Object idValue = getFieldValue ( identifierMetadata ) ; // If ID value is null, we don't have to worry about if it is a simple // type of a complex type. Otherwise, we need to see if the ID is a // complex type, and if it is, extract the real ID. if ( idValue != null && idClassMetadata != null ) { try { idValue = idClassMetadata . getReadMethod ( ) . invoke ( idValue ) ; } catch ( Throwable t ) { throw new EntityManagerException ( t ) ; } } boolean validId = isValidId ( idValue , identifierType ) ; boolean autoGenerateId = identifierMetadata . isAutoGenerated ( ) ; if ( validId ) { if ( identifierType == DataType . STRING ) { createCompleteKey ( parent , ( String ) idValue ) ; } else { createCompleteKey ( parent , ( long ) idValue ) ; } } else { if ( intent . isKeyRequired ( ) ) { throw new EntityManagerException ( String . format ( "Identifier is not set or valid for entity of type %s" , entity . getClass ( ) ) ) ; } if ( ! autoGenerateId ) { String pattern = "Identifier is not set or valid for entity of type %s. Auto generation " + "of ID is explicitly turned off. " ; throw new EntityManagerException ( String . format ( pattern , entity . getClass ( ) ) ) ; } else { if ( identifierType == DataType . STRING ) { createCompleteKey ( parent ) ; } else { createIncompleteKey ( parent ) ; } } } }
Marshals the key .
501
5
14,307
private static boolean isValidId ( Object idValue , DataType identifierType ) { boolean validId = false ; if ( idValue != null ) { switch ( identifierType ) { case LONG : case LONG_OBJECT : validId = ( long ) idValue != 0 ; break ; case STRING : validId = ( ( String ) idValue ) . trim ( ) . length ( ) > 0 ; break ; default : // we should never get here break ; } } return validId ; }
Checks to see if the given value is a valid identifier for the given ID type .
103
18
14,308
private void createCompleteKey ( Key parent , long id ) { String kind = entityMetadata . getKind ( ) ; if ( parent == null ) { key = entityManager . newNativeKeyFactory ( ) . setKind ( kind ) . newKey ( id ) ; } else { key = Key . newBuilder ( parent , kind , id ) . build ( ) ; } }
Creates a complete key using the given parameters .
79
10
14,309
private void createIncompleteKey ( Key parent ) { String kind = entityMetadata . getKind ( ) ; if ( parent == null ) { key = entityManager . newNativeKeyFactory ( ) . setKind ( kind ) . newKey ( ) ; } else { key = IncompleteKey . newBuilder ( parent , kind ) . build ( ) ; } }
Creates an IncompleteKey .
76
7
14,310
private void marshalFields ( ) { Collection < PropertyMetadata > propertyMetadataCollection = entityMetadata . getPropertyMetadataCollection ( ) ; for ( PropertyMetadata propertyMetadata : propertyMetadataCollection ) { marshalField ( propertyMetadata , entity ) ; } }
Marshals all the fields .
60
6
14,311
private static void marshalField ( PropertyMetadata propertyMetadata , Object target , BaseEntity . Builder < ? , ? > entityBuilder ) { Object fieldValue = IntrospectionUtils . getFieldValue ( propertyMetadata , target ) ; if ( fieldValue == null && propertyMetadata . isOptional ( ) ) { return ; } ValueBuilder < ? , ? , ? > valueBuilder = propertyMetadata . getMapper ( ) . toDatastore ( fieldValue ) ; // ListValues cannot have indexing turned off. Indexing is turned on by // default, so we don't touch excludeFromIndexes for ListValues. if ( valueBuilder . getValueType ( ) != ValueType . LIST ) { valueBuilder . setExcludeFromIndexes ( ! propertyMetadata . isIndexed ( ) ) ; } Value < ? > datastoreValue = valueBuilder . build ( ) ; entityBuilder . set ( propertyMetadata . getMappedName ( ) , datastoreValue ) ; Indexer indexer = propertyMetadata . getSecondaryIndexer ( ) ; if ( indexer != null ) { entityBuilder . set ( propertyMetadata . getSecondaryIndexName ( ) , indexer . index ( datastoreValue ) ) ; } }
Marshals the field with the given property metadata .
267
10
14,312
private void marshalEmbeddedFields ( ) { for ( EmbeddedMetadata embeddedMetadata : entityMetadata . getEmbeddedMetadataCollection ( ) ) { if ( embeddedMetadata . getStorageStrategy ( ) == StorageStrategy . EXPLODED ) { marshalWithExplodedStrategy ( embeddedMetadata , entity ) ; } else { ValueBuilder < ? , ? , ? > embeddedEntityBuilder = marshalWithImplodedStrategy ( embeddedMetadata , entity ) ; if ( embeddedEntityBuilder != null ) { entityBuilder . set ( embeddedMetadata . getMappedName ( ) , embeddedEntityBuilder . build ( ) ) ; } } } }
Marshals the embedded fields .
142
6
14,313
private void marshalWithExplodedStrategy ( EmbeddedMetadata embeddedMetadata , Object target ) { try { Object embeddedObject = initializeEmbedded ( embeddedMetadata , target ) ; for ( PropertyMetadata propertyMetadata : embeddedMetadata . getPropertyMetadataCollection ( ) ) { marshalField ( propertyMetadata , embeddedObject ) ; } for ( EmbeddedMetadata embeddedMetadata2 : embeddedMetadata . getEmbeddedMetadataCollection ( ) ) { marshalWithExplodedStrategy ( embeddedMetadata2 , embeddedObject ) ; } } catch ( Throwable t ) { throw new EntityManagerException ( t ) ; } }
Marshals an embedded field represented by the given metadata .
136
11
14,314
private ValueBuilder < ? , ? , ? > marshalWithImplodedStrategy ( EmbeddedMetadata embeddedMetadata , Object target ) { try { Object embeddedObject = embeddedMetadata . getReadMethod ( ) . invoke ( target ) ; if ( embeddedObject == null ) { if ( embeddedMetadata . isOptional ( ) ) { return null ; } NullValue . Builder nullValueBuilder = NullValue . newBuilder ( ) ; nullValueBuilder . setExcludeFromIndexes ( ! embeddedMetadata . isIndexed ( ) ) ; return nullValueBuilder ; } FullEntity . Builder < IncompleteKey > embeddedEntityBuilder = FullEntity . newBuilder ( ) ; for ( PropertyMetadata propertyMetadata : embeddedMetadata . getPropertyMetadataCollection ( ) ) { marshalField ( propertyMetadata , embeddedObject , embeddedEntityBuilder ) ; } for ( EmbeddedMetadata embeddedMetadata2 : embeddedMetadata . getEmbeddedMetadataCollection ( ) ) { ValueBuilder < ? , ? , ? > embeddedEntityBuilder2 = marshalWithImplodedStrategy ( embeddedMetadata2 , embeddedObject ) ; if ( embeddedEntityBuilder2 != null ) { embeddedEntityBuilder . set ( embeddedMetadata2 . getMappedName ( ) , embeddedEntityBuilder2 . build ( ) ) ; } } EntityValue . Builder valueBuilder = EntityValue . newBuilder ( embeddedEntityBuilder . build ( ) ) ; valueBuilder . setExcludeFromIndexes ( ! embeddedMetadata . isIndexed ( ) ) ; return valueBuilder ; } catch ( Throwable t ) { throw new EntityManagerException ( t ) ; } }
Marshals the embedded field represented by the given metadata .
343
11
14,315
private void marshalUpdatedTimestamp ( ) { PropertyMetadata updatedTimestampMetadata = entityMetadata . getUpdatedTimestampMetadata ( ) ; if ( updatedTimestampMetadata != null ) { applyAutoTimestamp ( updatedTimestampMetadata , System . currentTimeMillis ( ) ) ; } }
Marshals the updated timestamp field .
66
7
14,316
private void marshalCreatedAndUpdatedTimestamp ( ) { PropertyMetadata createdTimestampMetadata = entityMetadata . getCreatedTimestampMetadata ( ) ; PropertyMetadata updatedTimestampMetadata = entityMetadata . getUpdatedTimestampMetadata ( ) ; long millis = System . currentTimeMillis ( ) ; if ( createdTimestampMetadata != null ) { applyAutoTimestamp ( createdTimestampMetadata , millis ) ; } if ( updatedTimestampMetadata != null ) { applyAutoTimestamp ( updatedTimestampMetadata , millis ) ; } }
Marshals both created and updated timestamp fields .
124
9
14,317
private void marshalVersionField ( ) { PropertyMetadata versionMetadata = entityMetadata . getVersionMetadata ( ) ; if ( versionMetadata != null ) { long version = ( long ) IntrospectionUtils . getFieldValue ( versionMetadata , entity ) ; ValueBuilder < ? , ? , ? > valueBuilder = versionMetadata . getMapper ( ) . toDatastore ( version + 1 ) ; valueBuilder . setExcludeFromIndexes ( ! versionMetadata . isIndexed ( ) ) ; entityBuilder . set ( versionMetadata . getMappedName ( ) , valueBuilder . build ( ) ) ; } }
Marshals the version field if it exists . The version will be set to one more than the previous value .
138
22
14,318
private void initializeMapper ( ) { if ( itemClass == null ) { itemMapper = CatchAllMapper . getInstance ( ) ; } else { try { itemMapper = MapperFactory . getInstance ( ) . getMapper ( itemClass ) ; } catch ( NoSuitableMapperException exp ) { itemMapper = CatchAllMapper . getInstance ( ) ; } } }
Initializes the mapper for items in the List .
85
11
14,319
public void setJsonCredentialsFile ( String jsonCredentialsPath ) { if ( ! Utility . isNullOrEmpty ( jsonCredentialsPath ) ) { setJsonCredentialsFile ( new File ( jsonCredentialsPath ) ) ; } else { setJsonCredentialsFile ( ( File ) null ) ; } }
Sets the JSON credentials path .
74
7
14,320
private void initializeMapper ( ) { if ( valueClass == null ) { valueMapper = CatchAllMapper . getInstance ( ) ; } else { try { valueMapper = MapperFactory . getInstance ( ) . getMapper ( valueClass ) ; } catch ( NoSuitableMapperException exp ) { valueMapper = CatchAllMapper . getInstance ( ) ; } } }
Initializes the mapper for values in the Map .
85
11
14,321
public static InternalListenerMetadata introspect ( Class < ? > listenerClass ) { InternalListenerMetadata cachedMetadata = cache . get ( listenerClass ) ; if ( cachedMetadata != null ) { return cachedMetadata ; } synchronized ( listenerClass ) { cachedMetadata = cache . get ( listenerClass ) ; if ( cachedMetadata != null ) { return cachedMetadata ; } InternalListenerIntrospector introspector = new InternalListenerIntrospector ( listenerClass ) ; introspector . introspect ( ) ; cache . put ( listenerClass , introspector . metadata ) ; return introspector . metadata ; } }
Introspects the given class for any defined listeners and returns the metadata .
135
16
14,322
private void processMethods ( ) { Method [ ] methods = listenerClass . getDeclaredMethods ( ) ; for ( Method method : methods ) { for ( CallbackType callbackType : CallbackType . values ( ) ) { if ( method . isAnnotationPresent ( callbackType . getAnnotationClass ( ) ) ) { validateMethod ( method , callbackType ) ; metadata . putListener ( callbackType , method ) ; } } } }
Processes the methods in the listener class and updates the metadata for any valid methods found .
92
18
14,323
private void validateMethod ( Method method , CallbackType callbackType ) { int modifiers = method . getModifiers ( ) ; if ( ! Modifier . isPublic ( modifiers ) ) { String message = String . format ( "Method %s in class %s must be public" , method . getName ( ) , method . getDeclaringClass ( ) . getName ( ) ) ; throw new EntityManagerException ( message ) ; } if ( Modifier . isStatic ( modifiers ) ) { String message = String . format ( "Method %s in class %s must not be static" , method . getName ( ) , method . getDeclaringClass ( ) . getName ( ) ) ; throw new EntityManagerException ( message ) ; } if ( Modifier . isAbstract ( modifiers ) ) { String message = String . format ( "Method %s in class %s must not be abstract" , method . getName ( ) , method . getDeclaringClass ( ) . getName ( ) ) ; throw new EntityManagerException ( message ) ; } Class < ? > [ ] parameters = method . getParameterTypes ( ) ; if ( parameters . length != 0 ) { String pattern = "Method %s in class %s is not a valid %s callback method. Method must not " + "have any parameters. " ; String message = String . format ( pattern , method . getName ( ) , method . getDeclaringClass ( ) . getName ( ) , callbackType ) ; throw new EntityManagerException ( message ) ; } if ( method . getReturnType ( ) != void . class ) { String message = String . format ( "Method %s in class %s must have a return type of %s" , method . getName ( ) , method . getDeclaringClass ( ) . getName ( ) , void . class . getName ( ) ) ; throw new EntityManagerException ( message ) ; } }
Validates the given method to ensure if it is a valid callback method for the given event type .
404
20
14,324
public < E > E insert ( E entity ) { try { entityManager . executeEntityListeners ( CallbackType . PRE_INSERT , entity ) ; FullEntity < ? > nativeEntity = ( FullEntity < ? > ) Marshaller . marshal ( entityManager , entity , Intent . INSERT ) ; Entity insertedNativeEntity = nativeWriter . add ( nativeEntity ) ; @ SuppressWarnings ( "unchecked" ) E insertedEntity = ( E ) Unmarshaller . unmarshal ( insertedNativeEntity , entity . getClass ( ) ) ; entityManager . executeEntityListeners ( CallbackType . POST_INSERT , insertedEntity ) ; return insertedEntity ; } catch ( DatastoreException exp ) { throw DatastoreUtils . wrap ( exp ) ; } }
Inserts the given entity into the Cloud Datastore .
169
12
14,325
@ SuppressWarnings ( "unchecked" ) public < E > List < E > insert ( List < E > entities ) { if ( entities == null || entities . isEmpty ( ) ) { return new ArrayList <> ( ) ; } try { entityManager . executeEntityListeners ( CallbackType . PRE_INSERT , entities ) ; FullEntity < ? > [ ] nativeEntities = toNativeFullEntities ( entities , entityManager , Intent . INSERT ) ; Class < ? > entityClass = entities . get ( 0 ) . getClass ( ) ; List < Entity > insertedNativeEntities = nativeWriter . add ( nativeEntities ) ; List < E > insertedEntities = ( List < E > ) toEntities ( entityClass , insertedNativeEntities ) ; entityManager . executeEntityListeners ( CallbackType . POST_INSERT , insertedEntities ) ; return insertedEntities ; } catch ( DatastoreException exp ) { throw DatastoreUtils . wrap ( exp ) ; } }
Inserts the given list of entities into the Cloud Datastore .
219
14
14,326
@ SuppressWarnings ( "unchecked" ) public < E > E update ( E entity ) { try { entityManager . executeEntityListeners ( CallbackType . PRE_UPDATE , entity ) ; Intent intent = ( nativeWriter instanceof Batch ) ? Intent . BATCH_UPDATE : Intent . UPDATE ; Entity nativeEntity = ( Entity ) Marshaller . marshal ( entityManager , entity , intent ) ; nativeWriter . update ( nativeEntity ) ; E updatedEntity = ( E ) Unmarshaller . unmarshal ( nativeEntity , entity . getClass ( ) ) ; entityManager . executeEntityListeners ( CallbackType . POST_UPDATE , updatedEntity ) ; return updatedEntity ; } catch ( DatastoreException exp ) { throw DatastoreUtils . wrap ( exp ) ; } }
Updates the given entity in the Cloud Datastore . The passed in Entity must have its ID set for the update to work .
173
27
14,327
@ SuppressWarnings ( "unchecked" ) public < E > List < E > update ( List < E > entities ) { if ( entities == null || entities . isEmpty ( ) ) { return new ArrayList <> ( ) ; } try { Class < E > entityClass = ( Class < E > ) entities . get ( 0 ) . getClass ( ) ; entityManager . executeEntityListeners ( CallbackType . PRE_UPDATE , entities ) ; Intent intent = ( nativeWriter instanceof Batch ) ? Intent . BATCH_UPDATE : Intent . UPDATE ; Entity [ ] nativeEntities = toNativeEntities ( entities , entityManager , intent ) ; nativeWriter . update ( nativeEntities ) ; List < E > updatedEntities = toEntities ( entityClass , nativeEntities ) ; entityManager . executeEntityListeners ( CallbackType . POST_UPDATE , updatedEntities ) ; return updatedEntities ; } catch ( DatastoreException exp ) { throw DatastoreUtils . wrap ( exp ) ; } }
Updates the given list of entities in the Cloud Datastore .
222
14
14,328
public < E > E updateWithOptimisticLock ( E entity ) { PropertyMetadata versionMetadata = EntityIntrospector . getVersionMetadata ( entity ) ; if ( versionMetadata == null ) { return update ( entity ) ; } else { return updateWithOptimisticLockingInternal ( entity , versionMetadata ) ; } }
Updates the given entity with optimistic locking if the entity is set up to support optimistic locking . Otherwise a normal update is performed .
74
26
14,329
public < E > List < E > updateWithOptimisticLock ( List < E > entities ) { if ( entities == null || entities . isEmpty ( ) ) { return new ArrayList <> ( ) ; } Class < ? > entityClass = entities . get ( 0 ) . getClass ( ) ; PropertyMetadata versionMetadata = EntityIntrospector . getVersionMetadata ( entityClass ) ; if ( versionMetadata == null ) { return update ( entities ) ; } else { return updateWithOptimisticLockInternal ( entities , versionMetadata ) ; } }
Updates the given list of entities using optimistic locking feature if the entities are set up to support optimistic locking . Otherwise a normal update is performed .
123
29
14,330
@ SuppressWarnings ( "unchecked" ) protected < E > E updateWithOptimisticLockingInternal ( E entity , PropertyMetadata versionMetadata ) { Transaction transaction = null ; try { entityManager . executeEntityListeners ( CallbackType . PRE_UPDATE , entity ) ; Entity nativeEntity = ( Entity ) Marshaller . marshal ( entityManager , entity , Intent . UPDATE ) ; transaction = datastore . newTransaction ( ) ; Entity storedNativeEntity = transaction . get ( nativeEntity . getKey ( ) ) ; if ( storedNativeEntity == null ) { throw new OptimisticLockException ( String . format ( "Entity does not exist: %s" , nativeEntity . getKey ( ) ) ) ; } String versionPropertyName = versionMetadata . getMappedName ( ) ; long version = nativeEntity . getLong ( versionPropertyName ) - 1 ; long storedVersion = storedNativeEntity . getLong ( versionPropertyName ) ; if ( version != storedVersion ) { throw new OptimisticLockException ( String . format ( "Expecting version %d, but found %d" , version , storedVersion ) ) ; } transaction . update ( nativeEntity ) ; transaction . commit ( ) ; E updatedEntity = ( E ) Unmarshaller . unmarshal ( nativeEntity , entity . getClass ( ) ) ; entityManager . executeEntityListeners ( CallbackType . POST_UPDATE , updatedEntity ) ; return updatedEntity ; } catch ( DatastoreException exp ) { throw DatastoreUtils . wrap ( exp ) ; } finally { rollbackIfActive ( transaction ) ; } }
Worker method for updating the given entity with optimistic locking .
345
12
14,331
@ SuppressWarnings ( "unchecked" ) protected < E > List < E > updateWithOptimisticLockInternal ( List < E > entities , PropertyMetadata versionMetadata ) { Transaction transaction = null ; try { entityManager . executeEntityListeners ( CallbackType . PRE_UPDATE , entities ) ; Entity [ ] nativeEntities = toNativeEntities ( entities , entityManager , Intent . UPDATE ) ; // The above native entities already have the version incremented by // the marshalling process Key [ ] nativeKeys = new Key [ nativeEntities . length ] ; for ( int i = 0 ; i < nativeEntities . length ; i ++ ) { nativeKeys [ i ] = nativeEntities [ i ] . getKey ( ) ; } transaction = datastore . newTransaction ( ) ; List < Entity > storedNativeEntities = transaction . fetch ( nativeKeys ) ; String versionPropertyName = versionMetadata . getMappedName ( ) ; for ( int i = 0 ; i < nativeEntities . length ; i ++ ) { long version = nativeEntities [ i ] . getLong ( versionPropertyName ) - 1 ; Entity storedNativeEntity = storedNativeEntities . get ( i ) ; if ( storedNativeEntity == null ) { throw new OptimisticLockException ( String . format ( "Entity does not exist: %s" , nativeKeys [ i ] ) ) ; } long storedVersion = storedNativeEntities . get ( i ) . getLong ( versionPropertyName ) ; if ( version != storedVersion ) { throw new OptimisticLockException ( String . format ( "Expecting version %d, but found %d" , version , storedVersion ) ) ; } } transaction . update ( nativeEntities ) ; transaction . commit ( ) ; List < E > updatedEntities = ( List < E > ) toEntities ( entities . get ( 0 ) . getClass ( ) , nativeEntities ) ; entityManager . executeEntityListeners ( CallbackType . POST_UPDATE , updatedEntities ) ; return updatedEntities ; } catch ( DatastoreException exp ) { throw DatastoreUtils . wrap ( exp ) ; } finally { rollbackIfActive ( transaction ) ; } }
Internal worker method for updating the entities using optimistic locking .
472
11
14,332
public < E > E upsert ( E entity ) { try { entityManager . executeEntityListeners ( CallbackType . PRE_UPSERT , entity ) ; FullEntity < ? > nativeEntity = ( FullEntity < ? > ) Marshaller . marshal ( entityManager , entity , Intent . UPSERT ) ; Entity upsertedNativeEntity = nativeWriter . put ( nativeEntity ) ; @ SuppressWarnings ( "unchecked" ) E upsertedEntity = ( E ) Unmarshaller . unmarshal ( upsertedNativeEntity , entity . getClass ( ) ) ; entityManager . executeEntityListeners ( CallbackType . POST_UPSERT , upsertedEntity ) ; return upsertedEntity ; } catch ( DatastoreException exp ) { throw DatastoreUtils . wrap ( exp ) ; } }
Updates or inserts the given entity in the Cloud Datastore . If the entity does not have an ID it may be generated .
182
27
14,333
@ SuppressWarnings ( "unchecked" ) public < E > List < E > upsert ( List < E > entities ) { if ( entities == null || entities . isEmpty ( ) ) { return new ArrayList <> ( ) ; } try { entityManager . executeEntityListeners ( CallbackType . PRE_UPSERT , entities ) ; FullEntity < ? > [ ] nativeEntities = toNativeFullEntities ( entities , entityManager , Intent . UPSERT ) ; Class < ? > entityClass = entities . get ( 0 ) . getClass ( ) ; List < Entity > upsertedNativeEntities = nativeWriter . put ( nativeEntities ) ; List < E > upsertedEntities = ( List < E > ) toEntities ( entityClass , upsertedNativeEntities ) ; entityManager . executeEntityListeners ( CallbackType . POST_UPSERT , upsertedEntities ) ; return upsertedEntities ; } catch ( DatastoreException exp ) { throw DatastoreUtils . wrap ( exp ) ; } }
Updates or inserts the given list of entities in the Cloud Datastore . If the entities do not have a valid ID IDs may be generated .
232
30
14,334
public void delete ( Object entity ) { try { entityManager . executeEntityListeners ( CallbackType . PRE_DELETE , entity ) ; Key nativeKey = Marshaller . marshalKey ( entityManager , entity ) ; nativeWriter . delete ( nativeKey ) ; entityManager . executeEntityListeners ( CallbackType . POST_DELETE , entity ) ; } catch ( DatastoreException exp ) { throw DatastoreUtils . wrap ( exp ) ; } }
Deletes the given entity from the Cloud Datastore .
102
12
14,335
public void delete ( List < ? > entities ) { try { entityManager . executeEntityListeners ( CallbackType . PRE_DELETE , entities ) ; Key [ ] nativeKeys = new Key [ entities . size ( ) ] ; for ( int i = 0 ; i < entities . size ( ) ; i ++ ) { nativeKeys [ i ] = Marshaller . marshalKey ( entityManager , entities . get ( i ) ) ; } nativeWriter . delete ( nativeKeys ) ; entityManager . executeEntityListeners ( CallbackType . POST_DELETE , entities ) ; } catch ( DatastoreException exp ) { throw DatastoreUtils . wrap ( exp ) ; } }
Deletes the given entities from the Cloud Datastore .
148
12
14,336
public < E > void delete ( Class < E > entityClass , DatastoreKey parentKey , long id ) { try { EntityMetadata entityMetadata = EntityIntrospector . introspect ( entityClass ) ; Key nativeKey = Key . newBuilder ( parentKey . nativeKey ( ) , entityMetadata . getKind ( ) , id ) . build ( ) ; nativeWriter . delete ( nativeKey ) ; } catch ( DatastoreException exp ) { throw DatastoreUtils . wrap ( exp ) ; } }
Deletes the entity with the given ID and parent key .
113
12
14,337
public void deleteByKey ( DatastoreKey key ) { try { nativeWriter . delete ( key . nativeKey ( ) ) ; } catch ( DatastoreException exp ) { throw DatastoreUtils . wrap ( exp ) ; } }
Deletes an entity given its key .
52
8
14,338
public void deleteByKey ( List < DatastoreKey > keys ) { try { Key [ ] nativeKeys = new Key [ keys . size ( ) ] ; for ( int i = 0 ; i < keys . size ( ) ; i ++ ) { nativeKeys [ i ] = keys . get ( i ) . nativeKey ( ) ; } nativeWriter . delete ( nativeKeys ) ; } catch ( DatastoreException exp ) { throw DatastoreUtils . wrap ( exp ) ; } }
Deletes the entities having the given keys .
105
9
14,339
public void setNamedBindings ( Map < String , Object > namedBindings ) { if ( namedBindings == null ) { throw new IllegalArgumentException ( "namedBindings cannot be null" ) ; } this . namedBindings = namedBindings ; }
Sets the named bindings that are needed for any named parameters in the GQL query .
57
18
14,340
public void addPositionalBindings ( Object first , Object ... others ) { positionalBindings . add ( first ) ; positionalBindings . addAll ( Arrays . asList ( others ) ) ; }
Adds the positional bindings that are needed for any positional parameters in the GQL query .
43
17
14,341
private void computeQualifiedName ( ) { if ( parent != null ) { qualifiedName = parent . qualifiedName + "." + field . getName ( ) ; } else { qualifiedName = field . getName ( ) ; } }
Computes and sets the qualified name of this field .
49
11
14,342
public void put ( CallbackType callbackType , CallbackMetadata callbackMetadata ) { if ( callbacks == null ) { callbacks = new EnumMap <> ( CallbackType . class ) ; } List < CallbackMetadata > callbackMetadataList = callbacks . get ( callbackType ) ; if ( callbackMetadataList == null ) { callbackMetadataList = new ArrayList <> ( ) ; callbacks . put ( callbackType , callbackMetadataList ) ; } callbackMetadataList . add ( callbackMetadata ) ; }
Adds the given CallbackEventMetadata .
117
9
14,343
public List < CallbackMetadata > getCallbacks ( CallbackType callbackType ) { return callbacks == null ? null : callbacks . get ( callbackType ) ; }
Returns the callbacks for the given callback type .
37
10
14,344
private static ConstructorMetadata loadMetadata ( Class < ? > clazz ) { synchronized ( clazz ) { ConstructorMetadata metadata = cache . get ( clazz ) ; if ( metadata == null ) { ConstructorIntrospector introspector = new ConstructorIntrospector ( clazz ) ; introspector . process ( ) ; metadata = introspector . metadataBuilder . build ( ) ; cache . put ( clazz , metadata ) ; } return metadata ; } }
Loads the metadata if it does not already exist in the cache .
104
14
14,345
private void process ( ) { metadataBuilder = ConstructorMetadata . newBuilder ( ) . setClazz ( clazz ) ; MethodHandle mh = IntrospectionUtils . findDefaultConstructor ( clazz ) ; if ( mh != null ) { metadataBuilder . setConstructionStrategy ( ConstructorMetadata . ConstructionStrategy . CLASSIC ) . setConstructorMethodHandle ( mh ) ; // We have everything we need for the classic pattern with a default // constructor and accessor/mutator methods, more validations will // follow. return ; } // Now we check for Builder pattern usage mh = findNewBuilderMethod ( clazz ) ; if ( mh == null ) { final String pattern = "Class %s requires a public no-arg constructor or a public static " + "method that returns a corresponding Builder instance. The name of the static method " + "can either be %s or %s" ; String error = String . format ( pattern , clazz . getName ( ) , METHOD_NAME_NEW_BUILDER , METHOD_NAME_BUILDER ) ; throw new UnsupportedConstructionStrategyException ( error ) ; } Class < ? > builderClass = mh . type ( ) . returnType ( ) ; metadataBuilder . setConstructionStrategy ( ConstructorMetadata . ConstructionStrategy . BUILDER ) . setConstructorMethodHandle ( mh ) . setBuilderClass ( builderClass ) ; MethodHandle buildMethodHandle = IntrospectionUtils . findInstanceMethod ( builderClass , METHOD_NAME_BUILD , clazz ) ; if ( buildMethodHandle == null ) { String pattern = "Class %s requires a public instance method, %s, with a return type of %s" ; throw new EntityManagerException ( String . format ( pattern , builderClass . getName ( ) , METHOD_NAME_BUILD , clazz ) ) ; } metadataBuilder . setBuildMethodHandle ( buildMethodHandle ) ; }
Introspects the class and builds the metadata .
417
11
14,346
public static MethodHandle findNewBuilderMethod ( Class < ? > clazz ) { MethodHandle mh = null ; for ( String methodName : NEW_BUILDER_METHOD_NAMES ) { mh = IntrospectionUtils . findStaticMethod ( clazz , methodName , Object . class ) ; if ( mh != null ) { break ; } } return mh ; }
Finds and returns a method handle for new instance of a Builder class .
82
15
14,347
public static < T > T unmarshal ( Entity nativeEntity , Class < T > entityClass ) { return unmarshalBaseEntity ( nativeEntity , entityClass ) ; }
Unmarshals the given native Entity into an object of given type entityClass .
37
17
14,348
public static < T > T unmarshal ( ProjectionEntity nativeEntity , Class < T > entityClass ) { return unmarshalBaseEntity ( nativeEntity , entityClass ) ; }
Unmarshals the given native ProjectionEntity into an object of given type entityClass .
39
19
14,349
@ SuppressWarnings ( "unchecked" ) private < T > T unmarshal ( ) { try { instantiateEntity ( ) ; unmarshalIdentifier ( ) ; unmarshalKeyAndParentKey ( ) ; unmarshalProperties ( ) ; unmarshalEmbeddedFields ( ) ; // If using Builder pattern, invoke build method on the Builder to // get the final entity. ConstructorMetadata constructorMetadata = entityMetadata . getConstructorMetadata ( ) ; if ( constructorMetadata . isBuilderConstructionStrategy ( ) ) { entity = constructorMetadata . getBuildMethodHandle ( ) . invoke ( entity ) ; } return ( T ) entity ; } catch ( EntityManagerException exp ) { throw exp ; } catch ( Throwable t ) { throw new EntityManagerException ( t . getMessage ( ) , t ) ; } }
Unmarshals the given Datastore Entity and returns the equivalent Entity POJO .
184
18
14,350
private static < T > T unmarshalBaseEntity ( BaseEntity < ? > nativeEntity , Class < T > entityClass ) { if ( nativeEntity == null ) { return null ; } Unmarshaller unmarshaller = new Unmarshaller ( nativeEntity , entityClass ) ; return unmarshaller . unmarshal ( ) ; }
Unmarshals the given BaseEntity and returns the equivalent model object .
77
15
14,351
private void unmarshalIdentifier ( ) throws Throwable { IdentifierMetadata identifierMetadata = entityMetadata . getIdentifierMetadata ( ) ; Object id = ( ( Key ) nativeEntity . getKey ( ) ) . getNameOrId ( ) ; // If the ID is not a simple type... IdClassMetadata idClassMetadata = identifierMetadata . getIdClassMetadata ( ) ; if ( idClassMetadata != null ) { Object wrappedId = idClassMetadata . getConstructor ( ) . invoke ( id ) ; id = wrappedId ; } // Now set the ID (either simple or complex) on the Entity MethodHandle writeMethod = identifierMetadata . getWriteMethod ( ) ; writeMethod . invoke ( entity , id ) ; }
Unamrshals the identifier .
163
8
14,352
private void unmarshalKeyAndParentKey ( ) throws Throwable { KeyMetadata keyMetadata = entityMetadata . getKeyMetadata ( ) ; if ( keyMetadata != null ) { MethodHandle writeMethod = keyMetadata . getWriteMethod ( ) ; Key entityKey = ( Key ) nativeEntity . getKey ( ) ; writeMethod . invoke ( entity , new DefaultDatastoreKey ( entityKey ) ) ; } ParentKeyMetadata parentKeyMetadata = entityMetadata . getParentKeyMetadata ( ) ; if ( parentKeyMetadata != null ) { MethodHandle writeMethod = parentKeyMetadata . getWriteMethod ( ) ; Key parentKey = nativeEntity . getKey ( ) . getParent ( ) ; if ( parentKey != null ) { writeMethod . invoke ( entity , new DefaultDatastoreKey ( parentKey ) ) ; } } }
Unamrshals the entity s key and parent key .
186
13
14,353
private void unmarshalProperties ( ) throws Throwable { Collection < PropertyMetadata > propertyMetadataCollection = entityMetadata . getPropertyMetadataCollection ( ) ; for ( PropertyMetadata propertyMetadata : propertyMetadataCollection ) { unmarshalProperty ( propertyMetadata , entity ) ; } }
Unmarshal all the properties .
65
8
14,354
private void unmarshalEmbeddedFields ( ) throws Throwable { for ( EmbeddedMetadata embeddedMetadata : entityMetadata . getEmbeddedMetadataCollection ( ) ) { if ( embeddedMetadata . getStorageStrategy ( ) == StorageStrategy . EXPLODED ) { unmarshalWithExplodedStrategy ( embeddedMetadata , entity ) ; } else { unmarshalWithImplodedStrategy ( embeddedMetadata , entity , nativeEntity ) ; } } }
Unmarshals the embedded fields of this entity .
103
11
14,355
private void unmarshalWithExplodedStrategy ( EmbeddedMetadata embeddedMetadata , Object target ) throws Throwable { Object embeddedObject = initializeEmbedded ( embeddedMetadata , target ) ; for ( PropertyMetadata propertyMetadata : embeddedMetadata . getPropertyMetadataCollection ( ) ) { unmarshalProperty ( propertyMetadata , embeddedObject ) ; } for ( EmbeddedMetadata embeddedMetadata2 : embeddedMetadata . getEmbeddedMetadataCollection ( ) ) { unmarshalWithExplodedStrategy ( embeddedMetadata2 , embeddedObject ) ; } ConstructorMetadata constructorMetadata = embeddedMetadata . getConstructorMetadata ( ) ; if ( constructorMetadata . isBuilderConstructionStrategy ( ) ) { embeddedObject = constructorMetadata . getBuildMethodHandle ( ) . invoke ( embeddedObject ) ; } embeddedMetadata . getWriteMethod ( ) . invoke ( target , embeddedObject ) ; }
Unmarshals the embedded field represented by the given embedded metadata .
196
14
14,356
private static void unmarshalWithImplodedStrategy ( EmbeddedMetadata embeddedMetadata , Object target , BaseEntity < ? > nativeEntity ) throws Throwable { Object embeddedObject = null ; ConstructorMetadata constructorMetadata = embeddedMetadata . getConstructorMetadata ( ) ; FullEntity < ? > nativeEmbeddedEntity = null ; String propertyName = embeddedMetadata . getMappedName ( ) ; if ( nativeEntity . contains ( propertyName ) ) { Value < ? > nativeValue = nativeEntity . getValue ( propertyName ) ; if ( nativeValue instanceof NullValue ) { embeddedMetadata . getWriteMethod ( ) . invoke ( target , embeddedObject ) ; } else { nativeEmbeddedEntity = ( ( EntityValue ) nativeValue ) . get ( ) ; embeddedObject = constructorMetadata . getConstructorMethodHandle ( ) . invoke ( ) ; } } if ( embeddedObject == null ) { return ; } for ( PropertyMetadata propertyMetadata : embeddedMetadata . getPropertyMetadataCollection ( ) ) { unmarshalProperty ( propertyMetadata , embeddedObject , nativeEmbeddedEntity ) ; } for ( EmbeddedMetadata embeddedMetadata2 : embeddedMetadata . getEmbeddedMetadataCollection ( ) ) { unmarshalWithImplodedStrategy ( embeddedMetadata2 , embeddedObject , nativeEmbeddedEntity ) ; } if ( constructorMetadata . isBuilderConstructionStrategy ( ) ) { embeddedObject = constructorMetadata . getBuildMethodHandle ( ) . invoke ( embeddedObject ) ; } embeddedMetadata . getWriteMethod ( ) . invoke ( target , embeddedObject ) ; }
Unmarshals the embedded field represented by the given metadata .
343
13
14,357
private void unmarshalProperty ( PropertyMetadata propertyMetadata , Object target ) throws Throwable { unmarshalProperty ( propertyMetadata , target , nativeEntity ) ; }
Unmarshals the property represented by the given property metadata and updates the target object with the property value .
37
22
14,358
public void setIdentifierMetadata ( IdentifierMetadata identifierMetadata ) { if ( this . identifierMetadata != null ) { String format = "Class %s has at least two fields, %s and %s, marked with %s annotation. " + "Only one field can be marked as an identifier. " ; String message = String . format ( format , entityClass . getName ( ) , this . identifierMetadata . getName ( ) , identifierMetadata . getName ( ) , Identifier . class . getName ( ) ) ; throw new EntityManagerException ( message ) ; } this . identifierMetadata = identifierMetadata ; }
Sets the metadata of the identifier . An exception will be thrown if there is an IdentifierMetadata already set .
137
24
14,359
public void setKeyMetadata ( KeyMetadata keyMetadata ) { if ( this . keyMetadata != null ) { String format = "Class %s has two fields, %s and %s marked with %s annotation. Only one " + "field can be marked as Key. " ; String message = String . format ( format , entityClass . getName ( ) , this . keyMetadata . getName ( ) , keyMetadata . getName ( ) , Key . class . getName ( ) ) ; throw new EntityManagerException ( message ) ; } this . keyMetadata = keyMetadata ; }
Sets the metadata of the Key field .
130
9
14,360
public void setParentKetMetadata ( ParentKeyMetadata parentKeyMetadata ) { if ( this . parentKeyMetadata != null ) { String format = "Class %s has two fields, %s and %s marked with %s annotation. Only one " + "field can be marked as ParentKey. " ; String message = String . format ( format , entityClass . getName ( ) , this . parentKeyMetadata . getName ( ) , parentKeyMetadata . getName ( ) , ParentKey . class . getName ( ) ) ; throw new EntityManagerException ( message ) ; } this . parentKeyMetadata = parentKeyMetadata ; }
Sets the metadata about the parent key .
141
9
14,361
public void setVersionMetadata ( PropertyMetadata versionMetadata ) { if ( this . versionMetadata != null ) { throwDuplicateAnnotationException ( entityClass , Version . class , this . versionMetadata , versionMetadata ) ; } this . versionMetadata = versionMetadata ; }
Sets the metadata of the field that is used for optimistic locking .
64
14
14,362
public void setCreatedTimestampMetadata ( PropertyMetadata createdTimestampMetadata ) { if ( this . createdTimestampMetadata != null ) { throwDuplicateAnnotationException ( entityClass , CreatedTimestamp . class , this . createdTimestampMetadata , createdTimestampMetadata ) ; } this . createdTimestampMetadata = createdTimestampMetadata ; }
Sets the created timestamp metadata to the given value .
80
11
14,363
public void updateMasterPropertyMetadataMap ( String mappedName , String qualifiedName ) { String old = masterPropertyMetadataMap . put ( mappedName , qualifiedName ) ; if ( old != null ) { String message = "Duplicate property %s in entity %s. Check fields %s and %s" ; throw new EntityManagerException ( String . format ( message , mappedName , entityClass . getName ( ) , old , qualifiedName ) ) ; } }
Updates the master property metadata map with the given property metadata .
99
13
14,364
private void ensureUniqueProperties ( EmbeddedMetadata embeddedMetadata , StorageStrategy storageStrategy ) { if ( embeddedMetadata . getStorageStrategy ( ) == StorageStrategy . EXPLODED ) { for ( PropertyMetadata propertyMetadata : embeddedMetadata . getPropertyMetadataCollection ( ) ) { updateMasterPropertyMetadataMap ( propertyMetadata . getMappedName ( ) , embeddedMetadata . getField ( ) . getQualifiedName ( ) + "." + propertyMetadata . getName ( ) ) ; } // Run through the nested embedded objects recursively for ( EmbeddedMetadata embeddedMetadata2 : embeddedMetadata . getEmbeddedMetadataCollection ( ) ) { ensureUniqueProperties ( embeddedMetadata2 , storageStrategy ) ; } } else { // IMPLODED storage strategy... we don't have to check the // individual properties or nested embeddables updateMasterPropertyMetadataMap ( embeddedMetadata . getMappedName ( ) , embeddedMetadata . getField ( ) . getQualifiedName ( ) ) ; } }
Validates the embedded field represented by the given metadata to ensure there are no duplicate property names defined across the entity .
230
23
14,365
private static void throwDuplicateAnnotationException ( Class < ? > entityClass , Class < ? extends Annotation > annotationClass , PropertyMetadata metadata1 , PropertyMetadata metadata2 ) { String format = "Class %s has at least two fields, %s and %s, with an annotation of %s. " + "A given entity can have at most one field with this annotation. " ; String message = String . format ( format , entityClass . getName ( ) , metadata1 . getName ( ) , metadata2 . getName ( ) , annotationClass . getName ( ) ) ; throw new EntityManagerException ( message ) ; }
Raises an exception with a detailed message reporting that the entity has more than one field that has a specific annotation .
137
23
14,366
public static ExternalListenerMetadata introspect ( Class < ? > listenerClass ) { ExternalListenerMetadata cachedMetadata = cache . get ( listenerClass ) ; if ( cachedMetadata != null ) { return cachedMetadata ; } synchronized ( listenerClass ) { cachedMetadata = cache . get ( listenerClass ) ; if ( cachedMetadata != null ) { return cachedMetadata ; } ExternalListenerIntrospector introspector = new ExternalListenerIntrospector ( listenerClass ) ; introspector . introspect ( ) ; cache . put ( listenerClass , introspector . metadata ) ; return introspector . metadata ; } }
Introspects the given entity listener class and returns its metadata .
135
14
14,367
private void introspect ( ) { if ( ! listenerClass . isAnnotationPresent ( EntityListener . class ) ) { String message = String . format ( "Class %s must have %s annotation to be used as an EntityListener" , listenerClass . getName ( ) , EntityListener . class . getName ( ) ) ; throw new EntityManagerException ( message ) ; } metadata = new ExternalListenerMetadata ( listenerClass ) ; processMethods ( ) ; }
Introspects the listener class and creates the metadata .
97
12
14,368
public Mapper getMapper ( Field field ) { PropertyMapper propertyMapperAnnotation = field . getAnnotation ( PropertyMapper . class ) ; if ( propertyMapperAnnotation != null ) { return createCustomMapper ( field , propertyMapperAnnotation ) ; } Class < ? > fieldType = field . getType ( ) ; if ( fieldType . equals ( BigDecimal . class ) ) { Decimal decimalAnnotation = field . getAnnotation ( Decimal . class ) ; if ( decimalAnnotation != null ) { return new DecimalMapper ( decimalAnnotation . precision ( ) , decimalAnnotation . scale ( ) ) ; } } if ( List . class . isAssignableFrom ( fieldType ) || Set . class . isAssignableFrom ( fieldType ) ) { return CollectionMapperFactory . getInstance ( ) . getMapper ( field ) ; } return getMapper ( field . getGenericType ( ) ) ; }
Returns the mapper for the given field . If the field has a custom mapper a new instance of the specified mapper will be created and returned . Otherwise one of the built - in mappers will be returned based on the field type .
207
49
14,369
public Mapper getMapper ( Type type ) { Mapper mapper = cache . get ( type ) ; if ( mapper == null ) { mapper = createMapper ( type ) ; } return mapper ; }
Returns a mapper for the given type . If a mapper that can handle given type exists in the cache it will be returned . Otherwise a new mapper will be created .
47
36
14,370
public void setDefaultMapper ( Type type , Mapper mapper ) { if ( mapper == null ) { throw new IllegalArgumentException ( "mapper cannot be null" ) ; } lock . lock ( ) ; try { cache . put ( type , mapper ) ; } finally { lock . unlock ( ) ; } }
Sets or registers the given mapper for the given type . This method must be called before performing any persistence operations preferably during application startup . Entities that were introspected before calling this method will NOT use the new mapper .
70
47
14,371
private Mapper createMapper ( Type type ) { lock . lock ( ) ; try { Mapper mapper = cache . get ( type ) ; if ( mapper != null ) { return mapper ; } if ( type instanceof Class ) { mapper = createMapper ( ( Class < ? > ) type ) ; } else if ( type instanceof ParameterizedType ) { mapper = createMapper ( ( ParameterizedType ) type ) ; } else { throw new IllegalArgumentException ( String . format ( "Type %s is neither a Class nor ParameterizedType" , type ) ) ; } cache . put ( type , mapper ) ; return mapper ; } finally { lock . unlock ( ) ; } }
Creates a new mapper for the given type .
156
11
14,372
private Mapper createMapper ( Class < ? > clazz ) { Mapper mapper ; if ( Enum . class . isAssignableFrom ( clazz ) ) { mapper = new EnumMapper ( clazz ) ; } else if ( Map . class . isAssignableFrom ( clazz ) ) { mapper = new MapMapper ( clazz ) ; } else if ( clazz . isAnnotationPresent ( Embeddable . class ) ) { mapper = new EmbeddedObjectMapper ( clazz ) ; } else { throw new NoSuitableMapperException ( String . format ( "No mapper found for class %s" , clazz . getName ( ) ) ) ; } return mapper ; }
Creates a mapper for the given class .
159
10
14,373
private void createDefaultMappers ( ) { BooleanMapper booleanMapper = new BooleanMapper ( ) ; CharMapper charMapper = new CharMapper ( ) ; ShortMapper shortMapper = new ShortMapper ( ) ; IntegerMapper integerMapper = new IntegerMapper ( ) ; LongMapper longMapper = new LongMapper ( ) ; FloatMapper floatMapper = new FloatMapper ( ) ; DoubleMapper doubleMapper = new DoubleMapper ( ) ; cache . put ( boolean . class , booleanMapper ) ; cache . put ( Boolean . class , booleanMapper ) ; cache . put ( char . class , charMapper ) ; cache . put ( Character . class , charMapper ) ; cache . put ( short . class , shortMapper ) ; cache . put ( Short . class , shortMapper ) ; cache . put ( int . class , integerMapper ) ; cache . put ( Integer . class , integerMapper ) ; cache . put ( long . class , longMapper ) ; cache . put ( Long . class , longMapper ) ; cache . put ( float . class , floatMapper ) ; cache . put ( Float . class , floatMapper ) ; cache . put ( double . class , doubleMapper ) ; cache . put ( Double . class , doubleMapper ) ; cache . put ( String . class , new StringMapper ( ) ) ; cache . put ( BigDecimal . class , new BigDecimalMapper ( ) ) ; cache . put ( byte [ ] . class , new ByteArrayMapper ( ) ) ; cache . put ( char [ ] . class , new CharArrayMapper ( ) ) ; cache . put ( Date . class , new DateMapper ( ) ) ; cache . put ( Calendar . class , new CalendarMapper ( ) ) ; cache . put ( GeoLocation . class , new GeoLocationMapper ( ) ) ; cache . put ( DatastoreKey . class , new KeyMapper ( ) ) ; cache . put ( LocalDate . class , new LocalDateMapper ( ) ) ; cache . put ( LocalTime . class , new LocalTimeMapper ( ) ) ; cache . put ( LocalDateTime . class , new LocalDateTimeMapper ( ) ) ; cache . put ( OffsetDateTime . class , new OffsetDateTimeMapper ( ) ) ; cache . put ( ZonedDateTime . class , new ZonedDateTimeMapper ( ) ) ; }
Creates and assigns default Mappers various common types .
533
11
14,374
private Mapper createCustomMapper ( Field field , PropertyMapper propertyMapperAnnotation ) { Class < ? extends Mapper > mapperClass = propertyMapperAnnotation . value ( ) ; Constructor < ? extends Mapper > constructor = IntrospectionUtils . getConstructor ( mapperClass , Field . class ) ; if ( constructor != null ) { try { return constructor . newInstance ( field ) ; } catch ( Exception exp ) { throw new EntityManagerException ( exp ) ; } } throw new EntityManagerException ( String . format ( "Mapper class %s must have a public constructor with a parameter type of %s" , mapperClass . getName ( ) , Field . class . getName ( ) ) ) ; }
Creates and returns a custom mapper for the given field .
157
13
14,375
public void putListener ( CallbackType callbackType , Method method ) { if ( callbacks == null ) { callbacks = new EnumMap <> ( CallbackType . class ) ; } Method oldMethod = callbacks . put ( callbackType , method ) ; if ( oldMethod != null ) { String format = "Class %s has at least two methods, %s and %s, with annotation of %s. " + "At most one method is allowed for a given callback type. " ; String message = String . format ( format , listenerClass . getName ( ) , oldMethod . getName ( ) , method . getName ( ) , callbackType . getAnnotationClass ( ) . getName ( ) ) ; throw new EntityManagerException ( message ) ; } }
Registers the given method as the callback method for the given event type .
165
15
14,376
public < E > E load ( Class < E > entityClass , DatastoreKey parentKey , long id ) { EntityMetadata entityMetadata = EntityIntrospector . introspect ( entityClass ) ; Key nativeKey ; if ( parentKey == null ) { nativeKey = entityManager . newNativeKeyFactory ( ) . setKind ( entityMetadata . getKind ( ) ) . newKey ( id ) ; } else { nativeKey = Key . newBuilder ( parentKey . nativeKey ( ) , entityMetadata . getKind ( ) , id ) . build ( ) ; } return fetch ( entityClass , nativeKey ) ; }
Loads and returns the entity with the given ID . The entity kind is determined from the supplied class .
136
21
14,377
public < E > E load ( Class < E > entityClass , DatastoreKey key ) { return fetch ( entityClass , key . nativeKey ( ) ) ; }
Retrieves and returns the entity with the given key .
36
12
14,378
public < E > List < E > loadByKey ( Class < E > entityClass , List < DatastoreKey > keys ) { Key [ ] nativeKeys = DatastoreUtils . toNativeKeys ( keys ) ; return fetch ( entityClass , nativeKeys ) ; }
Retrieves and returns the entities for the given keys .
59
12
14,379
private < E > E fetch ( Class < E > entityClass , Key nativeKey ) { try { Entity nativeEntity = nativeReader . get ( nativeKey ) ; E entity = Unmarshaller . unmarshal ( nativeEntity , entityClass ) ; entityManager . executeEntityListeners ( CallbackType . POST_LOAD , entity ) ; return entity ; } catch ( DatastoreException exp ) { throw new EntityManagerException ( exp ) ; } }
Fetches the entity given the native key .
97
10
14,380
private < E > List < E > fetch ( Class < E > entityClass , Key [ ] nativeKeys ) { try { List < Entity > nativeEntities = nativeReader . fetch ( nativeKeys ) ; List < E > entities = DatastoreUtils . toEntities ( entityClass , nativeEntities ) ; entityManager . executeEntityListeners ( CallbackType . POST_LOAD , entities ) ; return entities ; } catch ( DatastoreException exp ) { throw new EntityManagerException ( exp ) ; } }
Fetches a list of entities for the given native keys .
110
13
14,381
private Key [ ] longListToNativeKeys ( Class < ? > entityClass , List < Long > identifiers ) { if ( identifiers == null || identifiers . isEmpty ( ) ) { return new Key [ 0 ] ; } EntityMetadata entityMetadata = EntityIntrospector . introspect ( entityClass ) ; Key [ ] nativeKeys = new Key [ identifiers . size ( ) ] ; KeyFactory keyFactory = entityManager . newNativeKeyFactory ( ) ; keyFactory . setKind ( entityMetadata . getKind ( ) ) ; for ( int i = 0 ; i < identifiers . size ( ) ; i ++ ) { long id = identifiers . get ( i ) ; nativeKeys [ i ] = keyFactory . newKey ( id ) ; } return nativeKeys ; }
Converts the given list of identifiers into an array of native Key objects .
163
15
14,382
private IncompleteKey getIncompleteKey ( Object entity ) { EntityMetadata entityMetadata = EntityIntrospector . introspect ( entity . getClass ( ) ) ; String kind = entityMetadata . getKind ( ) ; ParentKeyMetadata parentKeyMetadata = entityMetadata . getParentKeyMetadata ( ) ; DatastoreKey parentKey = null ; IncompleteKey incompleteKey = null ; if ( parentKeyMetadata != null ) { parentKey = ( DatastoreKey ) IntrospectionUtils . getFieldValue ( parentKeyMetadata , entity ) ; } if ( parentKey != null ) { incompleteKey = IncompleteKey . newBuilder ( parentKey . nativeKey ( ) , kind ) . build ( ) ; } else { incompleteKey = IncompleteKey . newBuilder ( datastore . getOptions ( ) . getProjectId ( ) , kind ) . setNamespace ( getEffectiveNamespace ( ) ) . build ( ) ; } return incompleteKey ; }
Returns an IncompleteKey of the given entity .
210
10
14,383
public void executeEntityListeners ( CallbackType callbackType , Object entity ) { // We may get null entities here. For example loading a nonexistent ID // or IDs. if ( entity == null ) { return ; } EntityListenersMetadata entityListenersMetadata = EntityIntrospector . getEntityListenersMetadata ( entity ) ; List < CallbackMetadata > callbacks = entityListenersMetadata . getCallbacks ( callbackType ) ; if ( ! entityListenersMetadata . isExcludeDefaultListeners ( ) ) { executeGlobalListeners ( callbackType , entity ) ; } if ( callbacks == null ) { return ; } for ( CallbackMetadata callback : callbacks ) { switch ( callback . getListenerType ( ) ) { case EXTERNAL : Object listener = ListenerFactory . getInstance ( ) . getListener ( callback . getListenerClass ( ) ) ; invokeCallbackMethod ( callback . getCallbackMethod ( ) , listener , entity ) ; break ; case INTERNAL : invokeCallbackMethod ( callback . getCallbackMethod ( ) , entity ) ; break ; default : String message = String . format ( "Unknown or unimplemented callback listener type: %s" , callback . getListenerType ( ) ) ; throw new EntityManagerException ( message ) ; } } }
Executes the entity listeners associated with the given entity .
275
11
14,384
public void executeEntityListeners ( CallbackType callbackType , List < ? > entities ) { for ( Object entity : entities ) { executeEntityListeners ( callbackType , entity ) ; } }
Executes the entity listeners associated with the given list of entities .
41
13
14,385
private void executeGlobalListeners ( CallbackType callbackType , Object entity ) { if ( globalCallbacks == null ) { return ; } List < CallbackMetadata > callbacks = globalCallbacks . get ( callbackType ) ; if ( callbacks == null ) { return ; } for ( CallbackMetadata callback : callbacks ) { Object listener = ListenerFactory . getInstance ( ) . getListener ( callback . getListenerClass ( ) ) ; invokeCallbackMethod ( callback . getCallbackMethod ( ) , listener , entity ) ; } }
Executes the global listeners for the given event type for the given entity .
115
15
14,386
private static void invokeCallbackMethod ( Method callbackMethod , Object listener , Object entity ) { try { callbackMethod . invoke ( listener , entity ) ; } catch ( Exception exp ) { String message = String . format ( "Failed to execute callback method %s of class %s" , callbackMethod . getName ( ) , callbackMethod . getDeclaringClass ( ) . getName ( ) ) ; throw new EntityManagerException ( message , exp ) ; } }
Invokes the given callback method on the given target object .
96
12
14,387
@ SuppressWarnings ( "unchecked" ) private < T extends Indexer > T createIndexer ( Class < T > indexerClass ) { synchronized ( indexerClass ) { Indexer indexer = cache . get ( indexerClass ) ; if ( indexer == null ) { indexer = ( Indexer ) IntrospectionUtils . instantiateObject ( indexerClass ) ; cache . put ( indexerClass , indexer ) ; } return ( T ) indexer ; } }
Creates the Indexer of the given class .
105
10
14,388
private Indexer getDefaultIndexer ( Field field ) { Type type = field . getGenericType ( ) ; if ( type instanceof Class && type . equals ( String . class ) ) { return getIndexer ( LowerCaseStringIndexer . class ) ; } else if ( type instanceof ParameterizedType ) { ParameterizedType parameterizedType = ( ParameterizedType ) type ; Class < ? > rawType = ( Class < ? > ) parameterizedType . getRawType ( ) ; if ( List . class . isAssignableFrom ( rawType ) || Set . class . isAssignableFrom ( rawType ) ) { Class < ? > [ ] collectionType = IntrospectionUtils . resolveCollectionType ( type ) ; if ( String . class . equals ( collectionType [ 1 ] ) ) { return getIndexer ( LowerCaseStringListIndexer . class ) ; } } } String message = String . format ( "No default indexer found for field %s in class %s" , field . getName ( ) , field . getDeclaringClass ( ) . getName ( ) ) ; throw new NoSuitableIndexerException ( message ) ; }
Returns the default indexer for the given field .
250
10
14,389
private void copyRequestHeaders ( HttpServletRequest servletRequest , HttpRequest proxyRequest ) throws URISyntaxException { // Get an Enumeration of all of the header names sent by the client Enumeration < ? > enumerationOfHeaderNames = servletRequest . getHeaderNames ( ) ; while ( enumerationOfHeaderNames . hasMoreElements ( ) ) { String headerName = ( String ) enumerationOfHeaderNames . nextElement ( ) ; //Instead the content-length is effectively set via InputStreamEntity if ( ! headerName . equalsIgnoreCase ( CONTENT_LENGTH ) && ! hopByHopHeaders . containsHeader ( headerName ) ) { Enumeration < ? > headers = servletRequest . getHeaders ( headerName ) ; while ( headers . hasMoreElements ( ) ) { //sometimes more than one value String headerValue = ( String ) headers . nextElement ( ) ; // In case the proxy host is running multiple virtual servers, // rewrite the Host header to ensure that we get content from // the correct virtual server if ( headerName . equalsIgnoreCase ( HOST ) ) { HttpHost host = URIUtils . extractHost ( new URI ( prerenderConfig . getPrerenderServiceUrl ( ) ) ) ; headerValue = host . getHostName ( ) ; if ( host . getPort ( ) != - 1 ) { headerValue += ":" + host . getPort ( ) ; } } proxyRequest . addHeader ( headerName , headerValue ) ; } } } }
Copy request headers from the servlet client to the proxy request .
328
13
14,390
private void copyResponseHeaders ( HttpResponse proxyResponse , final HttpServletResponse servletResponse ) { servletResponse . setCharacterEncoding ( getContentCharSet ( proxyResponse . getEntity ( ) ) ) ; from ( Arrays . asList ( proxyResponse . getAllHeaders ( ) ) ) . filter ( new Predicate < Header > ( ) { @ Override public boolean apply ( Header header ) { return ! hopByHopHeaders . containsHeader ( header . getName ( ) ) ; } } ) . transform ( new Function < Header , Boolean > ( ) { @ Override public Boolean apply ( Header header ) { servletResponse . addHeader ( header . getName ( ) , header . getValue ( ) ) ; return true ; } } ) . toList ( ) ; }
Copy proxied response headers back to the servlet client .
171
12
14,391
private String getContentCharSet ( final HttpEntity entity ) throws ParseException { if ( entity == null ) { return null ; } String charset = null ; if ( entity . getContentType ( ) != null ) { HeaderElement values [ ] = entity . getContentType ( ) . getElements ( ) ; if ( values . length > 0 ) { NameValuePair param = values [ 0 ] . getParameterByName ( "charset" ) ; if ( param != null ) { charset = param . getValue ( ) ; } } } return charset ; }
Get the charset used to encode the http entity .
125
11
14,392
@ SuppressWarnings ( "unchecked" ) public T getDefaultObject ( ) { if ( defaultValue instanceof IModel ) { return ( ( IModel < T > ) defaultValue ) . getObject ( ) ; } else { return ( T ) defaultValue ; } }
Returns default value
60
3
14,393
public JsonResponse getEmail ( String email ) throws IOException { Email emailObj = new Email ( ) ; emailObj . setEmail ( email ) ; return apiGet ( emailObj ) ; }
Get information about one of your users .
41
8
14,394
public JsonResponse getSend ( String sendId ) throws IOException { Map < String , Object > data = new HashMap < String , Object > ( ) ; data . put ( Send . PARAM_SEND_ID , sendId ) ; return apiGet ( ApiAction . send , data ) ; }
Get the status of a transational send
66
8
14,395
public JsonResponse cancelSend ( String sendId ) throws IOException { Map < String , Object > data = new HashMap < String , Object > ( ) ; data . put ( Send . PARAM_SEND_ID , sendId ) ; return apiDelete ( ApiAction . send , data ) ; }
Cancel a send that was scheduled for a future time .
66
12
14,396
public JsonResponse getBlast ( Integer blastId ) throws IOException { Blast blast = new Blast ( ) ; blast . setBlastId ( blastId ) ; return apiGet ( blast ) ; }
get information about a blast
43
5
14,397
public JsonResponse scheduleBlastFromTemplate ( String template , String list , Date scheduleTime , Blast blast ) throws IOException { blast . setCopyTemplate ( template ) ; blast . setList ( list ) ; blast . setScheduleTime ( scheduleTime ) ; return apiPost ( blast ) ; }
Schedule a mass mail from a template
63
8
14,398
public JsonResponse scheduleBlastFromBlast ( Integer blastId , Date scheduleTime , Blast blast ) throws IOException { blast . setCopyBlast ( blastId ) ; blast . setScheduleTime ( scheduleTime ) ; return apiPost ( blast ) ; }
Schedule a mass mail blast from previous blast
56
9
14,399
public JsonResponse updateBlast ( Integer blastId ) throws IOException { Blast blast = new Blast ( ) ; blast . setBlastId ( blastId ) ; return apiPost ( blast ) ; }
Update existing blast
43
3