idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
147,300
public boolean isEmpty ( ) { int snapshotSize = cleared ? 0 : snapshot . size ( ) ; //nothing in both if ( snapshotSize == 0 && currentState . isEmpty ( ) ) { return true ; } //snapshot bigger than changeset if ( snapshotSize > currentState . size ( ) ) { return false ; } return size ( ) == 0 ; }
Whether this association contains no rows .
77
7
147,301
public int size ( ) { int size = cleared ? 0 : snapshot . size ( ) ; for ( Map . Entry < RowKey , AssociationOperation > op : currentState . entrySet ( ) ) { switch ( op . getValue ( ) . getType ( ) ) { case PUT : if ( cleared || ! snapshot . containsKey ( op . getKey ( ) ) ) { size ++ ; } break ; case REMOVE : if ( ! cleared && snapshot . containsKey ( op . getKey ( ) ) ) { size -- ; } break ; } } return size ; }
Returns the number of rows within this association .
122
9
147,302
public Iterable < RowKey > getKeys ( ) { if ( currentState . isEmpty ( ) ) { if ( cleared ) { // if the association has been cleared and the currentState is empty, we consider that there are no rows. return Collections . emptyList ( ) ; } else { // otherwise, the snapshot rows are the current ones return snapshot . getRowKeys ( ) ; } } else { // It may be a bit too large in case of removals, but that's fine for now Set < RowKey > keys = CollectionHelper . newLinkedHashSet ( cleared ? currentState . size ( ) : snapshot . size ( ) + currentState . size ( ) ) ; if ( ! cleared ) { // we add the snapshot RowKeys only if the association has not been cleared for ( RowKey rowKey : snapshot . getRowKeys ( ) ) { keys . add ( rowKey ) ; } } for ( Map . Entry < RowKey , AssociationOperation > op : currentState . entrySet ( ) ) { switch ( op . getValue ( ) . getType ( ) ) { case PUT : keys . add ( op . getKey ( ) ) ; break ; case REMOVE : keys . remove ( op . getKey ( ) ) ; break ; } } return keys ; } }
Returns all keys of all rows contained within this association .
273
11
147,303
public Object getColumnValue ( String columnName ) { for ( int j = 0 ; j < columnNames . length ; j ++ ) { if ( columnNames [ j ] . equals ( columnName ) ) { return columnValues [ j ] ; } } return null ; }
Get the value of the specified column .
57
8
147,304
public boolean contains ( String column ) { for ( String columnName : columnNames ) { if ( columnName . equals ( column ) ) { return true ; } } return false ; }
Check if a column is part of the row key columns .
38
12
147,305
private void loadResourceFile ( URL configurationResourceUrl , Properties hotRodConfiguration ) { if ( configurationResourceUrl != null ) { try ( InputStream openStream = configurationResourceUrl . openStream ( ) ) { hotRodConfiguration . load ( openStream ) ; } catch ( IOException e ) { throw log . failedLoadingHotRodConfigurationProperties ( e ) ; } } }
Load the properties from the resource file if one is specified
78
11
147,306
private static < D extends DatastoreConfiguration < G > , G extends GlobalContext < ? , ? > > AppendableConfigurationContext invokeOptionConfigurator ( OptionConfigurator configurator ) { ConfigurableImpl configurable = new ConfigurableImpl ( ) ; configurator . configure ( configurable ) ; return configurable . getContext ( ) ; }
Invokes the given configurator obtaining the correct global context type via the datastore configuration type of the current datastore provider .
76
28
147,307
@ Override public boolean isKeyColumn ( String columnName ) { for ( String keyColumName : getColumnNames ( ) ) { if ( keyColumName . equals ( columnName ) ) { return true ; } } return false ; }
Whether the given column is part of this key family or not .
52
13
147,308
@ Override public List < Object > loadEntitiesFromTuples ( SharedSessionContractImplementor session , LockOptions lockOptions , OgmLoadingContext ogmContext ) { return loadEntity ( null , null , session , lockOptions , ogmContext ) ; }
Load a list of entities using the information in the context
56
11
147,309
public final void loadCollection ( final SharedSessionContractImplementor session , final Serializable id , final Type type ) throws HibernateException { if ( log . isDebugEnabled ( ) ) { log . debug ( "loading collection: " + MessageHelper . collectionInfoString ( getCollectionPersisters ( ) [ 0 ] , id , getFactory ( ) ) ) ; } Serializable [ ] ids = new Serializable [ ] { id } ; QueryParameters qp = new QueryParameters ( new Type [ ] { type } , ids , ids ) ; doQueryAndInitializeNonLazyCollections ( session , qp , OgmLoadingContext . EMPTY_CONTEXT , true ) ; log . debug ( "done loading collection" ) ; }
Called by subclasses that initialize collections
161
8
147,310
private List < Object > doQueryAndInitializeNonLazyCollections ( SharedSessionContractImplementor session , QueryParameters qp , OgmLoadingContext ogmLoadingContext , boolean returnProxies ) { //TODO handles the read only final PersistenceContext persistenceContext = session . getPersistenceContext ( ) ; boolean defaultReadOnlyOrig = persistenceContext . isDefaultReadOnly ( ) ; persistenceContext . beforeLoad ( ) ; List < Object > result ; try { try { result = doQuery ( session , qp , ogmLoadingContext , returnProxies ) ; } finally { persistenceContext . afterLoad ( ) ; } persistenceContext . initializeNonLazyCollections ( ) ; } finally { // Restore the original default persistenceContext . setDefaultReadOnly ( defaultReadOnlyOrig ) ; } log . debug ( "done entity load" ) ; return result ; }
Load the entity activating the persistence context execution boundaries
186
9
147,311
private List < Object > doQuery ( SharedSessionContractImplementor session , QueryParameters qp , OgmLoadingContext ogmLoadingContext , boolean returnProxies ) { //TODO support lock timeout int entitySpan = entityPersisters . length ; final List < Object > hydratedObjects = entitySpan == 0 ? null : new ArrayList < Object > ( entitySpan * 10 ) ; //TODO yuk! Is there a cleaner way to access the id? final Serializable id ; // see if we use batching first // then look for direct id // then for a tuple based result set we could extract the id // otherwise that's a collection so we use the collection key boolean loadSeveralIds = loadSeveralIds ( qp ) ; boolean isCollectionLoader ; if ( loadSeveralIds ) { // need to be set to null otherwise the optionalId has precedence // and is used for all tuples regardless of their actual ids id = null ; isCollectionLoader = false ; } else if ( qp . getOptionalId ( ) != null ) { id = qp . getOptionalId ( ) ; isCollectionLoader = false ; } else if ( ogmLoadingContext . hasResultSet ( ) ) { // extract the ids from the tuples directly id = null ; isCollectionLoader = false ; } else { id = qp . getCollectionKeys ( ) [ 0 ] ; isCollectionLoader = true ; } TupleAsMapResultSet resultset = getResultSet ( id , qp , ogmLoadingContext , session ) ; //Todo implement lockmode //final LockMode[] lockModesArray = getLockModes( queryParameters.getLockOptions() ); //FIXME should we use subselects as it's closer to this process?? //TODO is resultset a good marker, or should it be an ad-hoc marker?? //It likely all depends on what resultset ends up being handleEmptyCollections ( qp . getCollectionKeys ( ) , resultset , session ) ; final org . hibernate . engine . spi . EntityKey [ ] keys = new org . hibernate . engine . spi . EntityKey [ entitySpan ] ; //for each element in resultset //TODO should we collect List<Object> as result? Not necessary today Object result = null ; List < Object > results = new ArrayList < Object > ( ) ; if ( isCollectionLoader ) { preLoadBatchFetchingQueue ( session , resultset ) ; } try { while ( resultset . next ( ) ) { result = getRowFromResultSet ( resultset , session , qp , ogmLoadingContext , //lockmodeArray, id , hydratedObjects , keys , returnProxies ) ; results . add ( result ) ; } //TODO collect subselect result key } catch ( SQLException e ) { //never happens this is not a regular ResultSet } //end of for each element in resultset initializeEntitiesAndCollections ( hydratedObjects , resultset , session , qp . isReadOnly ( session ) ) ; //TODO create subselects return results ; }
Execute the physical query and initialize the various entities and collections
677
12
147,312
private void readCollectionElement ( final Object optionalOwner , final Serializable optionalKey , final CollectionPersister persister , final CollectionAliases descriptor , final ResultSet rs , final SharedSessionContractImplementor session ) throws HibernateException , SQLException { final PersistenceContext persistenceContext = session . getPersistenceContext ( ) ; //implement persister.readKey using the grid type (later) final Serializable collectionRowKey = ( Serializable ) persister . readKey ( rs , descriptor . getSuffixedKeyAliases ( ) , session ) ; if ( collectionRowKey != null ) { // we found a collection element in the result set if ( log . isDebugEnabled ( ) ) { log . debug ( "found row of collection: " + MessageHelper . collectionInfoString ( persister , collectionRowKey , getFactory ( ) ) ) ; } Object owner = optionalOwner ; if ( owner == null ) { owner = persistenceContext . getCollectionOwner ( collectionRowKey , persister ) ; if ( owner == null ) { //TODO: This is assertion is disabled because there is a bug that means the // original owner of a transient, uninitialized collection is not known // if the collection is re-referenced by a different object associated // with the current Session //throw new AssertionFailure("bug loading unowned collection"); } } PersistentCollection rowCollection = persistenceContext . getLoadContexts ( ) . getCollectionLoadContext ( rs ) . getLoadingCollection ( persister , collectionRowKey ) ; if ( rowCollection != null ) { hydrateRowCollection ( persister , descriptor , rs , owner , rowCollection ) ; } } else if ( optionalKey != null ) { // we did not find a collection element in the result set, so we // ensure that a collection is created with the owner's identifier, // since what we have is an empty collection if ( log . isDebugEnabled ( ) ) { log . debug ( "result set contains (possibly empty) collection: " + MessageHelper . collectionInfoString ( persister , optionalKey , getFactory ( ) ) ) ; } persistenceContext . getLoadContexts ( ) . getCollectionLoadContext ( rs ) . getLoadingCollection ( persister , optionalKey ) ; // handle empty collection } // else no collection element, but also no owner }
Read one collection element from the current row of the JDBC result set
492
14
147,313
private void instanceAlreadyLoaded ( final Tuple resultset , final int i , //TODO create an interface for this usage final OgmEntityPersister persister , final org . hibernate . engine . spi . EntityKey key , final Object object , final LockMode lockMode , final SharedSessionContractImplementor session ) throws HibernateException { if ( ! persister . isInstance ( object ) ) { throw new WrongClassException ( "loaded object was of wrong class " + object . getClass ( ) , key . getIdentifier ( ) , persister . getEntityName ( ) ) ; } if ( LockMode . NONE != lockMode && upgradeLocks ( ) ) { // no point doing this if NONE was requested final boolean isVersionCheckNeeded = persister . isVersioned ( ) && session . getPersistenceContext ( ) . getEntry ( object ) . getLockMode ( ) . lessThan ( lockMode ) ; // we don't need to worry about existing version being uninitialized // because this block isn't called by a re-entrant load (re-entrant // loads _always_ have lock mode NONE) if ( isVersionCheckNeeded ) { //we only check the version when _upgrading_ lock modes Object oldVersion = session . getPersistenceContext ( ) . getEntry ( object ) . getVersion ( ) ; persister . checkVersionAndRaiseSOSE ( key . getIdentifier ( ) , oldVersion , session , resultset ) ; //we need to upgrade the lock mode to the mode requested session . getPersistenceContext ( ) . getEntry ( object ) . setLockMode ( lockMode ) ; } } }
The entity instance is already in the session cache
361
9
147,314
private Object instanceNotYetLoaded ( final Tuple resultset , final int i , final Loadable persister , final String rowIdAlias , final org . hibernate . engine . spi . EntityKey key , final LockMode lockMode , final org . hibernate . engine . spi . EntityKey optionalObjectKey , final Object optionalObject , final List hydratedObjects , final SharedSessionContractImplementor session ) throws HibernateException { final String instanceClass = getInstanceClass ( resultset , i , persister , key . getIdentifier ( ) , session ) ; final Object object ; if ( optionalObjectKey != null && key . equals ( optionalObjectKey ) ) { //its the given optional object object = optionalObject ; } else { // instantiate a new instance object = session . instantiate ( instanceClass , key . getIdentifier ( ) ) ; } //need to hydrate it. // grab its state from the ResultSet and keep it in the Session // (but don't yet initialize the object itself) // note that we acquire LockMode.READ even if it was not requested LockMode acquiredLockMode = lockMode == LockMode . NONE ? LockMode . READ : lockMode ; loadFromResultSet ( resultset , i , object , instanceClass , key , rowIdAlias , acquiredLockMode , persister , session ) ; //materialize associations (and initialize the object) later hydratedObjects . add ( object ) ; return object ; }
The entity instance is not in the session cache
314
9
147,315
private void registerNonExists ( final org . hibernate . engine . spi . EntityKey [ ] keys , final Loadable [ ] persisters , final SharedSessionContractImplementor session ) { final int [ ] owners = getOwners ( ) ; if ( owners != null ) { EntityType [ ] ownerAssociationTypes = getOwnerAssociationTypes ( ) ; for ( int i = 0 ; i < keys . length ; i ++ ) { int owner = owners [ i ] ; if ( owner > - 1 ) { org . hibernate . engine . spi . EntityKey ownerKey = keys [ owner ] ; if ( keys [ i ] == null && ownerKey != null ) { final PersistenceContext persistenceContext = session . getPersistenceContext ( ) ; /*final boolean isPrimaryKey; final boolean isSpecialOneToOne; if ( ownerAssociationTypes == null || ownerAssociationTypes[i] == null ) { isPrimaryKey = true; isSpecialOneToOne = false; } else { isPrimaryKey = ownerAssociationTypes[i].getRHSUniqueKeyPropertyName()==null; isSpecialOneToOne = ownerAssociationTypes[i].getLHSPropertyName()!=null; }*/ //TODO: can we *always* use the "null property" approach for everything? /*if ( isPrimaryKey && !isSpecialOneToOne ) { persistenceContext.addNonExistantEntityKey( new EntityKey( ownerKey.getIdentifier(), persisters[i], session.getEntityMode() ) ); } else if ( isSpecialOneToOne ) {*/ boolean isOneToOneAssociation = ownerAssociationTypes != null && ownerAssociationTypes [ i ] != null && ownerAssociationTypes [ i ] . isOneToOne ( ) ; if ( isOneToOneAssociation ) { persistenceContext . addNullProperty ( ownerKey , ownerAssociationTypes [ i ] . getPropertyName ( ) ) ; } /*} else { persistenceContext.addNonExistantEntityUniqueKey( new EntityUniqueKey( persisters[i].getEntityName(), ownerAssociationTypes[i].getRHSUniqueKeyPropertyName(), ownerKey.getIdentifier(), persisters[owner].getIdentifierType(), session.getEntityMode() ) ); }*/ } } } } }
For missing objects associated by one - to - one with another object in the result set register the fact that the object is missing with the session .
495
29
147,316
public Rule CriteriaOnlyFindQuery ( ) { return Sequence ( ! peek ( ) . isCliQuery ( ) , JsonParameter ( JsonObject ( ) ) , peek ( ) . setOperation ( Operation . FIND ) , peek ( ) . setCriteria ( match ( ) ) ) ; }
A find query only given as criterion . Leave it to MongoDB s own parser to handle it .
64
20
147,317
public static Map < String , Object > introspect ( Object obj ) throws IntrospectionException , InvocationTargetException , IllegalAccessException { Map < String , Object > result = new HashMap <> ( ) ; BeanInfo info = Introspector . getBeanInfo ( obj . getClass ( ) ) ; for ( PropertyDescriptor pd : info . getPropertyDescriptors ( ) ) { Method reader = pd . getReadMethod ( ) ; String name = pd . getName ( ) ; if ( reader != null && ! "class" . equals ( name ) ) { result . put ( name , reader . invoke ( obj ) ) ; } } return result ; }
Introspect the given object .
145
7
147,318
public static boolean propertyExists ( Class < ? > clazz , String property , ElementType elementType ) { if ( ElementType . FIELD . equals ( elementType ) ) { return getDeclaredField ( clazz , property ) != null ; } else { String capitalizedPropertyName = capitalize ( property ) ; Method method = getMethod ( clazz , PROPERTY_ACCESSOR_PREFIX_GET + capitalizedPropertyName ) ; if ( method != null && method . getReturnType ( ) != void . class ) { return true ; } method = getMethod ( clazz , PROPERTY_ACCESSOR_PREFIX_IS + capitalizedPropertyName ) ; if ( method != null && method . getReturnType ( ) == boolean . class ) { return true ; } } return false ; }
Whether the specified JavaBeans property exists on the given type or not .
174
15
147,319
public static void setField ( Object object , String field , Object value ) throws NoSuchMethodException , InvocationTargetException , IllegalAccessException { Class < ? > clazz = object . getClass ( ) ; Method m = clazz . getMethod ( PROPERTY_ACCESSOR_PREFIX_SET + capitalize ( field ) , value . getClass ( ) ) ; m . invoke ( object , value ) ; }
Set value for given object field .
90
7
147,320
public boolean isEmbeddedProperty ( String targetTypeName , List < String > namesWithoutAlias ) { OgmEntityPersister persister = getPersister ( targetTypeName ) ; Type propertyType = persister . getPropertyType ( namesWithoutAlias . get ( 0 ) ) ; if ( propertyType . isComponentType ( ) ) { // Embedded return true ; } else if ( propertyType . isAssociationType ( ) ) { Joinable associatedJoinable = ( ( AssociationType ) propertyType ) . getAssociatedJoinable ( persister . getFactory ( ) ) ; if ( associatedJoinable . isCollection ( ) ) { OgmCollectionPersister collectionPersister = ( OgmCollectionPersister ) associatedJoinable ; return collectionPersister . getType ( ) . isComponentType ( ) ; } } return false ; }
Checks if the path leads to an embedded property or association .
175
13
147,321
public boolean isAssociation ( String targetTypeName , List < String > pathWithoutAlias ) { OgmEntityPersister persister = getPersister ( targetTypeName ) ; Type propertyType = persister . getPropertyType ( pathWithoutAlias . get ( 0 ) ) ; return propertyType . isAssociationType ( ) ; }
Check if the path to the property correspond to an association .
70
12
147,322
public List < String > findAssociationPath ( String targetTypeName , List < String > pathWithoutAlias ) { List < String > subPath = new ArrayList < String > ( pathWithoutAlias . size ( ) ) ; for ( String name : pathWithoutAlias ) { subPath . add ( name ) ; if ( isAssociation ( targetTypeName , subPath ) ) { return subPath ; } } return null ; }
Find the path to the first association in the property path .
90
12
147,323
private static < R > RowKey buildRowKey ( AssociationKey associationKey , R row , AssociationRowAccessor < R > accessor ) { String [ ] columnNames = associationKey . getMetadata ( ) . getRowKeyColumnNames ( ) ; Object [ ] columnValues = new Object [ columnNames . length ] ; for ( int i = 0 ; i < columnNames . length ; i ++ ) { String columnName = columnNames [ i ] ; columnValues [ i ] = associationKey . getMetadata ( ) . isKeyColumn ( columnName ) ? associationKey . getColumnValue ( columnName ) : accessor . get ( row , columnName ) ; } return new RowKey ( columnNames , columnValues ) ; }
Creates the row key of the given association row ; columns present in the given association key will be obtained from there all other columns from the given native association row .
155
33
147,324
protected EntityKey getEntityKey ( Tuple tuple , AssociatedEntityKeyMetadata associatedEntityKeyMetadata ) { Object [ ] columnValues = new Object [ associatedEntityKeyMetadata . getAssociationKeyColumns ( ) . length ] ; int i = 0 ; for ( String associationKeyColumn : associatedEntityKeyMetadata . getAssociationKeyColumns ( ) ) { columnValues [ i ] = tuple . get ( associationKeyColumn ) ; i ++ ; } return new EntityKey ( associatedEntityKeyMetadata . getEntityKeyMetadata ( ) , columnValues ) ; }
Returns the key of the entity targeted by the represented association retrieved from the given tuple .
121
17
147,325
public static boolean isPartOfRegularEmbedded ( String [ ] keyColumnNames , String column ) { return isPartOfEmbedded ( column ) && ! ArrayHelper . contains ( keyColumnNames , column ) ; }
A regular embedded is an element that it is embedded but it is not a key or a collection .
45
20
147,326
public String getOuterMostNullEmbeddableIfAny ( String column ) { String [ ] path = column . split ( "\\." ) ; if ( ! isEmbeddableColumn ( path ) ) { return null ; } // the cached value may be null hence the explicit key lookup if ( columnToOuterMostNullEmbeddableCache . containsKey ( column ) ) { return columnToOuterMostNullEmbeddableCache . get ( column ) ; } return determineAndCacheOuterMostNullEmbeddable ( column , path ) ; }
Should only called on a column that is being set to null .
116
13
147,327
private String determineAndCacheOuterMostNullEmbeddable ( String column , String [ ] path ) { String embeddable = path [ 0 ] ; // process each embeddable from less specific to most specific // exclude path leaves as it's a column and not an embeddable for ( int index = 0 ; index < path . length - 1 ; index ++ ) { Set < String > columnsOfEmbeddable = getColumnsOfEmbeddableAndComputeEmbeddableNullness ( embeddable ) ; if ( nullEmbeddables . contains ( embeddable ) ) { // the current embeddable only has null columns; cache that info for all the columns for ( String columnOfEmbeddable : columnsOfEmbeddable ) { columnToOuterMostNullEmbeddableCache . put ( columnOfEmbeddable , embeddable ) ; } break ; } else { maybeCacheOnNonNullEmbeddable ( path , index , columnsOfEmbeddable ) ; } // a more specific null embeddable might be present, carry on embeddable += "." + path [ index + 1 ] ; } return columnToOuterMostNullEmbeddableCache . get ( column ) ; }
Walks from the most outer embeddable to the most inner one look for all columns contained in these embeddables and exclude the embeddables that have a non null column because of caching the algorithm is only run once per column parameter
256
48
147,328
public void addNavigationalInformationForInverseSide ( ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "Adding inverse navigational information for entity: " + MessageHelper . infoString ( persister , id , persister . getFactory ( ) ) ) ; } for ( int propertyIndex = 0 ; propertyIndex < persister . getEntityMetamodel ( ) . getPropertySpan ( ) ; propertyIndex ++ ) { if ( persister . isPropertyOfTable ( propertyIndex , tableIndex ) ) { AssociationKeyMetadata associationKeyMetadata = getInverseAssociationKeyMetadata ( propertyIndex ) ; // there is no inverse association for the given property if ( associationKeyMetadata == null ) { continue ; } Object [ ] newColumnValues = LogicalPhysicalConverterHelper . getColumnValuesFromResultset ( resultset , persister . getPropertyColumnNames ( propertyIndex ) ) ; //don't index null columns, this means no association if ( ! CollectionHelper . isEmptyOrContainsOnlyNull ( ( newColumnValues ) ) ) { addNavigationalInformationForInverseSide ( propertyIndex , associationKeyMetadata , newColumnValues ) ; } } } }
Updates all inverse associations managed by a given entity .
259
11
147,329
public static String escapeDoubleQuotesForJson ( String text ) { if ( text == null ) { return null ; } StringBuilder builder = new StringBuilder ( text . length ( ) ) ; for ( int i = 0 ; i < text . length ( ) ; i ++ ) { char c = text . charAt ( i ) ; switch ( c ) { case ' ' : case ' ' : builder . append ( "\\" ) ; default : builder . append ( c ) ; } } return builder . toString ( ) ; }
If a text contains double quotes escape them .
112
9
147,330
private static Row row ( List < StatementResult > results ) { Row row = results . get ( 0 ) . getData ( ) . get ( 0 ) ; return row ; }
When we execute a single statement we only need the corresponding Row with the result .
37
16
147,331
static < T extends GridDialect > T getDialectFacetOrNull ( GridDialect gridDialect , Class < T > facetType ) { if ( hasFacet ( gridDialect , facetType ) ) { @ SuppressWarnings ( "unchecked" ) T asFacet = ( T ) gridDialect ; return asFacet ; } return null ; }
Returns the given dialect narrowed down to the given dialect facet in case it is implemented by the dialect .
81
20
147,332
public static boolean hasFacet ( GridDialect gridDialect , Class < ? extends GridDialect > facetType ) { if ( gridDialect instanceof ForwardingGridDialect ) { return hasFacet ( ( ( ForwardingGridDialect < ? > ) gridDialect ) . getGridDialect ( ) , facetType ) ; } else { return facetType . isAssignableFrom ( gridDialect . getClass ( ) ) ; } }
Whether the given grid dialect implements the specified facet or not .
97
12
147,333
public void initializePersistenceStrategy ( CacheMappingType cacheMappingType , Set < EntityKeyMetadata > entityTypes , Set < AssociationKeyMetadata > associationTypes , Set < IdSourceKeyMetadata > idSourceTypes , Iterable < Namespace > namespaces ) { persistenceStrategy = PersistenceStrategy . getInstance ( cacheMappingType , externalCacheManager , config . getConfigurationUrl ( ) , jtaPlatform , entityTypes , associationTypes , idSourceTypes ) ; // creates handler for TableGenerator Id sources boolean requiresCounter = hasIdGeneration ( idSourceTypes ) ; if ( requiresCounter ) { this . tableClusterHandler = new TableClusteredCounterHandler ( persistenceStrategy . getCacheManager ( ) . getCacheManager ( ) ) ; } // creates handlers for SequenceGenerator Id sources for ( Namespace namespace : namespaces ) { for ( Sequence seq : namespace . getSequences ( ) ) { this . sequenceCounterHandlers . put ( seq . getExportIdentifier ( ) , new SequenceClusteredCounterHandler ( persistenceStrategy . getCacheManager ( ) . getCacheManager ( ) , seq ) ) ; } } // clear resources this . externalCacheManager = null ; this . jtaPlatform = null ; }
Initializes the persistence strategy to be used when accessing the datastore . In particular all the required caches will be configured and initialized .
266
27
147,334
private static Document getProjection ( List < String > fieldNames ) { Document projection = new Document ( ) ; for ( String column : fieldNames ) { projection . put ( column , 1 ) ; } return projection ; }
Returns a projection object for specifying the fields to retrieve during a specific find operation .
46
16
147,335
private static Document objectForInsert ( Tuple tuple , Document dbObject ) { MongoDBTupleSnapshot snapshot = ( MongoDBTupleSnapshot ) tuple . getSnapshot ( ) ; for ( TupleOperation operation : tuple . getOperations ( ) ) { String column = operation . getColumn ( ) ; if ( notInIdField ( snapshot , column ) ) { switch ( operation . getType ( ) ) { case PUT : MongoHelpers . setValue ( dbObject , column , operation . getValue ( ) ) ; break ; case PUT_NULL : case REMOVE : MongoHelpers . resetValue ( dbObject , column ) ; break ; } } } return dbObject ; }
Creates a Document that can be passed to the MongoDB batch insert function
149
15
147,336
private static ClosableIterator < Tuple > doDistinct ( final MongoDBQueryDescriptor queryDescriptor , final MongoCollection < Document > collection ) { DistinctIterable < ? > distinctFieldValues = collection . distinct ( queryDescriptor . getDistinctFieldName ( ) , queryDescriptor . getCriteria ( ) , String . class ) ; Collation collation = getCollation ( queryDescriptor . getOptions ( ) ) ; distinctFieldValues = collation != null ? distinctFieldValues . collation ( collation ) : distinctFieldValues ; MongoCursor < ? > cursor = distinctFieldValues . iterator ( ) ; List < Object > documents = new ArrayList <> ( ) ; while ( cursor . hasNext ( ) ) { documents . add ( cursor . next ( ) ) ; } MapTupleSnapshot snapshot = new MapTupleSnapshot ( Collections . < String , Object > singletonMap ( "n" , documents ) ) ; return CollectionHelper . newClosableIterator ( Collections . singletonList ( new Tuple ( snapshot , SnapshotType . UNKNOWN ) ) ) ; }
do Distinct operation
241
4
147,337
@ SuppressWarnings ( "deprecation" ) private static WriteConcern mergeWriteConcern ( WriteConcern original , WriteConcern writeConcern ) { if ( original == null ) { return writeConcern ; } else if ( writeConcern == null ) { return original ; } else if ( original . equals ( writeConcern ) ) { return original ; } Object wObject ; int wTimeoutMS ; boolean fsync ; Boolean journal ; if ( original . getWObject ( ) instanceof String ) { wObject = original . getWString ( ) ; } else if ( writeConcern . getWObject ( ) instanceof String ) { wObject = writeConcern . getWString ( ) ; } else { wObject = Math . max ( original . getW ( ) , writeConcern . getW ( ) ) ; } wTimeoutMS = Math . min ( original . getWtimeout ( ) , writeConcern . getWtimeout ( ) ) ; fsync = original . getFsync ( ) || writeConcern . getFsync ( ) ; if ( original . getJournal ( ) == null ) { journal = writeConcern . getJournal ( ) ; } else if ( writeConcern . getJournal ( ) == null ) { journal = original . getJournal ( ) ; } else { journal = original . getJournal ( ) || writeConcern . getJournal ( ) ; } if ( wObject instanceof String ) { return new WriteConcern ( ( String ) wObject , wTimeoutMS , fsync , journal ) ; } else { return new WriteConcern ( ( int ) wObject , wTimeoutMS , fsync , journal ) ; } }
As we merge several operations into one operation we need to be sure the write concern applied to the aggregated operation respects all the requirements expressed for each separate operation .
356
32
147,338
@ Override public ClosableIterator < Tuple > callStoredProcedure ( String storedProcedureName , ProcedureQueryParameters params , TupleContext tupleContext ) { validate ( params ) ; StringBuilder commandLine = createCallStoreProcedureCommand ( storedProcedureName , params ) ; Document result = callStoredProcedure ( commandLine ) ; Object resultValue = result . get ( "retval" ) ; List < Tuple > resultTuples = extractTuples ( storedProcedureName , resultValue ) ; return CollectionHelper . newClosableIterator ( resultTuples ) ; }
In MongoDB the equivalent of a stored procedure is a stored Javascript .
132
14
147,339
public UniqueEntityLoader buildLoader ( OuterJoinLoadable persister , int batchSize , LockMode lockMode , SessionFactoryImplementor factory , LoadQueryInfluencers influencers , BatchableEntityLoaderBuilder innerEntityLoaderBuilder ) { if ( batchSize <= 1 ) { // no batching return buildNonBatchingLoader ( persister , lockMode , factory , influencers , innerEntityLoaderBuilder ) ; } return buildBatchingLoader ( persister , batchSize , lockMode , factory , influencers , innerEntityLoaderBuilder ) ; }
Builds a batch - fetch capable loader based on the given persister lock - mode etc .
114
19
147,340
public UniqueEntityLoader buildLoader ( OuterJoinLoadable persister , int batchSize , LockOptions lockOptions , SessionFactoryImplementor factory , LoadQueryInfluencers influencers , BatchableEntityLoaderBuilder innerEntityLoaderBuilder ) { if ( batchSize <= 1 ) { // no batching return buildNonBatchingLoader ( persister , lockOptions , factory , influencers , innerEntityLoaderBuilder ) ; } return buildBatchingLoader ( persister , batchSize , lockOptions , factory , influencers , innerEntityLoaderBuilder ) ; }
Builds a batch - fetch capable loader based on the given persister lock - options etc .
114
19
147,341
private void applyProperties ( AssociationKey associationKey , Tuple associationRow , Relationship relationship ) { String [ ] indexColumns = associationKey . getMetadata ( ) . getRowKeyIndexColumnNames ( ) ; for ( int i = 0 ; i < indexColumns . length ; i ++ ) { String propertyName = indexColumns [ i ] ; Object propertyValue = associationRow . get ( propertyName ) ; relationship . setProperty ( propertyName , propertyValue ) ; } }
The only properties added to a relationship are the columns representing the index of the association .
102
17
147,342
public Association getAssociation ( String collectionRole ) { if ( associations == null ) { return null ; } return associations . get ( collectionRole ) ; }
Return the association as cached in the entry state .
32
10
147,343
public void setAssociation ( String collectionRole , Association association ) { if ( associations == null ) { associations = new HashMap <> ( ) ; } associations . put ( collectionRole , association ) ; }
Set the association in the entry state .
43
8
147,344
@ Override public void addExtraState ( EntityEntryExtraState extraState ) { if ( next == null ) { next = extraState ; } else { next . addExtraState ( extraState ) ; } }
state chain management ops below
44
5
147,345
protected StrongCounter getCounterOrCreateIt ( String counterName , int initialValue ) { CounterManager counterManager = EmbeddedCounterManagerFactory . asCounterManager ( cacheManager ) ; if ( ! counterManager . isDefined ( counterName ) ) { LOG . tracef ( "Counter %s is not defined, creating it" , counterName ) ; // global configuration is mandatory in order to define // a new clustered counter with persistent storage validateGlobalConfiguration ( ) ; counterManager . defineCounter ( counterName , CounterConfiguration . builder ( CounterType . UNBOUNDED_STRONG ) . initialValue ( initialValue ) . storage ( Storage . PERSISTENT ) . build ( ) ) ; } StrongCounter strongCounter = counterManager . getStrongCounter ( counterName ) ; return strongCounter ; }
Create a counter if one is not defined already otherwise return the existing one .
166
15
147,346
public Set < TupleOperation > getOperations ( ) { if ( currentState == null ) { return Collections . emptySet ( ) ; } else { return new SetFromCollection < TupleOperation > ( currentState . values ( ) ) ; } }
Return the list of actions on the tuple . Inherently deduplicated operations
53
17
147,347
private < A extends Annotation > AnnotationConverter < A > getConverter ( Annotation annotation ) { MappingOption mappingOption = annotation . annotationType ( ) . getAnnotation ( MappingOption . class ) ; if ( mappingOption == null ) { return null ; } // wrong type would be a programming error of the annotation developer @ SuppressWarnings ( "unchecked" ) Class < ? extends AnnotationConverter < A > > converterClass = ( Class < ? extends AnnotationConverter < A > > ) mappingOption . value ( ) ; try { return converterClass . newInstance ( ) ; } catch ( Exception e ) { throw log . cannotConvertAnnotation ( converterClass , e ) ; } }
Returns a converter instance for the given annotation .
158
9
147,348
public static String [ ] slice ( String [ ] strings , int begin , int length ) { String [ ] result = new String [ length ] ; System . arraycopy ( strings , begin , result , 0 , length ) ; return result ; }
Create a smaller array from an existing one .
50
9
147,349
public static < T > int indexOf ( T [ ] array , T element ) { for ( int i = 0 ; i < array . length ; i ++ ) { if ( array [ i ] . equals ( element ) ) { return i ; } } return - 1 ; }
Return the position of an element inside an array
58
9
147,350
public static < T > T [ ] concat ( T [ ] first , T ... second ) { int firstLength = first . length ; int secondLength = second . length ; @ SuppressWarnings ( "unchecked" ) T [ ] result = ( T [ ] ) Array . newInstance ( first . getClass ( ) . getComponentType ( ) , firstLength + secondLength ) ; System . arraycopy ( first , 0 , result , 0 , firstLength ) ; System . arraycopy ( second , 0 , result , firstLength , secondLength ) ; return result ; }
Concats two arrays .
123
5
147,351
public static < T > T [ ] concat ( T firstElement , T ... array ) { @ SuppressWarnings ( "unchecked" ) T [ ] result = ( T [ ] ) Array . newInstance ( firstElement . getClass ( ) , 1 + array . length ) ; result [ 0 ] = firstElement ; System . arraycopy ( array , 0 , result , 1 , array . length ) ; return result ; }
Concats an element and an array .
92
8
147,352
private Serializable doWorkInIsolationTransaction ( final SharedSessionContractImplementor session ) throws HibernateException { class Work extends AbstractReturningWork < IntegralDataTypeHolder > { private final SharedSessionContractImplementor localSession = session ; @ Override public IntegralDataTypeHolder execute ( Connection connection ) throws SQLException { try { return doWorkInCurrentTransactionIfAny ( localSession ) ; } catch ( RuntimeException sqle ) { throw new HibernateException ( "Could not get or update next value" , sqle ) ; } } } //we want to work out of transaction boolean workInTransaction = false ; Work work = new Work ( ) ; Serializable generatedValue = session . getTransactionCoordinator ( ) . createIsolationDelegate ( ) . delegateWork ( work , workInTransaction ) ; return generatedValue ; }
copied and altered from TransactionHelper
186
7
147,353
public static void registerOgmExternalizers ( SerializationConfigurationBuilder cfg ) { for ( AdvancedExternalizer < ? > advancedExternalizer : ogmExternalizers . values ( ) ) { cfg . addAdvancedExternalizer ( advancedExternalizer ) ; } }
Registers all custom Externalizer implementations that Hibernate OGM needs into an Infinispan CacheManager configuration .
54
24
147,354
public static void registerOgmExternalizers ( GlobalConfiguration globalCfg ) { Map < Integer , AdvancedExternalizer < ? > > externalizerMap = globalCfg . serialization ( ) . advancedExternalizers ( ) ; externalizerMap . putAll ( ogmExternalizers ) ; }
Registers all custom Externalizer implementations that Hibernate OGM needs into a running Infinispan CacheManager configuration . This is only safe to do when Caches from this CacheManager haven t been started yet or the ones already started do not contain any data needing these .
60
56
147,355
public static void validateExternalizersPresent ( EmbeddedCacheManager externalCacheManager ) { Map < Integer , AdvancedExternalizer < ? > > externalizerMap = externalCacheManager . getCacheManagerConfiguration ( ) . serialization ( ) . advancedExternalizers ( ) ; for ( AdvancedExternalizer < ? > ogmExternalizer : ogmExternalizers . values ( ) ) { final Integer externalizerId = ogmExternalizer . getId ( ) ; AdvancedExternalizer < ? > registeredExternalizer = externalizerMap . get ( externalizerId ) ; if ( registeredExternalizer == null ) { throw log . externalizersNotRegistered ( externalizerId , ogmExternalizer . getClass ( ) ) ; } else if ( ! registeredExternalizer . getClass ( ) . equals ( ogmExternalizer ) ) { if ( registeredExternalizer . getClass ( ) . toString ( ) . equals ( ogmExternalizer . getClass ( ) . toString ( ) ) ) { // same class name, yet different Class definition! throw log . registeredExternalizerNotLoadedFromOGMClassloader ( registeredExternalizer . getClass ( ) ) ; } else { throw log . externalizerIdNotMatchingType ( externalizerId , registeredExternalizer , ogmExternalizer ) ; } } } }
Verify that all OGM custom externalizers are present . N . B . even if some Externalizer is only needed in specific configuration it is not safe to start a CacheManager without one as the same CacheManager might be used or have been used in the past to store data using a different configuration .
271
61
147,356
public void writeLock ( EntityKey key , int timeout ) { ReadWriteLock lock = getLock ( key ) ; Lock writeLock = lock . writeLock ( ) ; acquireLock ( key , timeout , writeLock ) ; }
Acquires a write lock on a specific key .
47
11
147,357
public void readLock ( EntityKey key , int timeout ) { ReadWriteLock lock = getLock ( key ) ; Lock readLock = lock . readLock ( ) ; acquireLock ( key , timeout , readLock ) ; }
Acquires a read lock on a specific key .
47
11
147,358
public Map < AssociationKey , Map < RowKey , Map < String , Object > > > getAssociationsMap ( ) { return Collections . unmodifiableMap ( associationsKeyValueStorage ) ; }
Meant to execute assertions in tests only
42
8
147,359
public static String flatten ( String left , String right ) { return left == null || left . isEmpty ( ) ? right : left + "." + right ; }
Links the two field names into a single left . right field name . If the left field is empty right is returned
35
23
147,360
public static boolean organizeAssociationMapByRowKey ( org . hibernate . ogm . model . spi . Association association , AssociationKey key , AssociationContext associationContext ) { if ( association . isEmpty ( ) ) { return false ; } if ( key . getMetadata ( ) . getRowKeyIndexColumnNames ( ) . length != 1 ) { return false ; } Object valueOfFirstRow = association . get ( association . getKeys ( ) . iterator ( ) . next ( ) ) . get ( key . getMetadata ( ) . getRowKeyIndexColumnNames ( ) [ 0 ] ) ; if ( ! ( valueOfFirstRow instanceof String ) ) { return false ; } // The list style may be explicitly enforced for compatibility reasons return getMapStorage ( associationContext ) == MapStorageType . BY_KEY ; }
Whether the rows of the given association should be stored in a hash using the single row key column as key or not .
176
24
147,361
private void scheduleBatchLoadIfNeeded ( Serializable id , SharedSessionContractImplementor session ) throws MappingException { //cannot batch fetch by unique key (property-ref associations) if ( StringHelper . isEmpty ( delegate . getRHSUniqueKeyPropertyName ( ) ) && id != null ) { EntityPersister persister = session . getFactory ( ) . getMetamodel ( ) . entityPersister ( delegate . getAssociatedEntityName ( ) ) ; EntityKey entityKey = session . generateEntityKey ( id , persister ) ; if ( ! session . getPersistenceContext ( ) . containsEntity ( entityKey ) ) { session . getPersistenceContext ( ) . getBatchFetchQueue ( ) . addBatchLoadableEntityKey ( entityKey ) ; } } }
Register the entity as batch loadable if enabled
172
9
147,362
public GeoMultiPoint addPoint ( GeoPoint point ) { Contracts . assertNotNull ( point , "point" ) ; this . points . add ( point ) ; return this ; }
Adds a new point .
38
5
147,363
public String findAlias ( String entityAlias , List < String > propertyPathWithoutAlias ) { RelationshipAliasTree aliasTree = relationshipAliases . get ( entityAlias ) ; if ( aliasTree == null ) { return null ; } RelationshipAliasTree associationAlias = aliasTree ; for ( int i = 0 ; i < propertyPathWithoutAlias . size ( ) ; i ++ ) { associationAlias = associationAlias . findChild ( propertyPathWithoutAlias . get ( i ) ) ; if ( associationAlias == null ) { return null ; } } return associationAlias . getAlias ( ) ; }
Given the alias of the entity and the path to the relationship it will return the alias of the component .
121
21
147,364
public Node createEmbedded ( GraphDatabaseService executionEngine , Object [ ] columnValues ) { Map < String , Object > params = params ( columnValues ) ; Result result = executionEngine . execute ( getCreateEmbeddedNodeQuery ( ) , params ) ; return singleResult ( result ) ; }
Create a single node representing an embedded element .
61
9
147,365
public Node findEntity ( GraphDatabaseService executionEngine , Object [ ] columnValues ) { Map < String , Object > params = params ( columnValues ) ; Result result = executionEngine . execute ( getFindEntityQuery ( ) , params ) ; return singleResult ( result ) ; }
Find the node corresponding to an entity .
58
8
147,366
public Node insertEntity ( GraphDatabaseService executionEngine , Object [ ] columnValues ) { Map < String , Object > params = params ( columnValues ) ; Result result = executionEngine . execute ( getCreateEntityQuery ( ) , params ) ; return singleResult ( result ) ; }
Creates the node corresponding to an entity .
58
9
147,367
public ResourceIterator < Node > findEntities ( GraphDatabaseService executionEngine ) { Result result = executionEngine . execute ( getFindEntitiesQuery ( ) ) ; return result . columnAs ( BaseNeo4jEntityQueries . ENTITY_ALIAS ) ; }
Find all the node representing the entity .
57
8
147,368
public void removeEntity ( GraphDatabaseService executionEngine , Object [ ] columnValues ) { Map < String , Object > params = params ( columnValues ) ; executionEngine . execute ( getRemoveEntityQuery ( ) , params ) ; }
Remove the nodes representing the entity and the embedded elements attached to it .
48
14
147,369
public void updateEmbeddedColumn ( GraphDatabaseService executionEngine , Object [ ] keyValues , String embeddedColumn , Object value ) { String query = getUpdateEmbeddedColumnQuery ( keyValues , embeddedColumn ) ; Map < String , Object > params = params ( ArrayHelper . concat ( keyValues , value , value ) ) ; executionEngine . execute ( query , params ) ; }
Update the value of an embedded node property .
80
9
147,370
private static IndexOptions prepareOptions ( MongoDBIndexType indexType , Document options , String indexName , boolean unique ) { IndexOptions indexOptions = new IndexOptions ( ) ; indexOptions . name ( indexName ) . unique ( unique ) . background ( options . getBoolean ( "background" , false ) ) ; if ( unique ) { // MongoDB only allows one null value per unique index which is not in line with what we usually consider // as the definition of a unique constraint. Thus, we mark the index as sparse to only index values // defined and avoid this issue. We do this only if a partialFilterExpression has not been defined // as partialFilterExpression and sparse are exclusive. indexOptions . sparse ( ! options . containsKey ( "partialFilterExpression" ) ) ; } else if ( options . containsKey ( "partialFilterExpression" ) ) { indexOptions . partialFilterExpression ( ( Bson ) options . get ( "partialFilterExpression" ) ) ; } if ( options . containsKey ( "expireAfterSeconds" ) ) { //@todo is it correct? indexOptions . expireAfter ( options . getInteger ( "expireAfterSeconds" ) . longValue ( ) , TimeUnit . SECONDS ) ; } if ( MongoDBIndexType . TEXT . equals ( indexType ) ) { // text is an option we take into account to mark an index as a full text index as we cannot put "text" as // the order like MongoDB as ORM explicitly checks that the order is either asc or desc. // we remove the option from the Document so that we don't pass it to MongoDB if ( options . containsKey ( "default_language" ) ) { indexOptions . defaultLanguage ( options . getString ( "default_language" ) ) ; } if ( options . containsKey ( "weights" ) ) { indexOptions . weights ( ( Bson ) options . get ( "weights" ) ) ; } options . remove ( "text" ) ; } return indexOptions ; }
Prepare the options by adding additional information to them .
435
11
147,371
public static AssociationKeyMetadata getInverseAssociationKeyMetadata ( OgmEntityPersister mainSidePersister , int propertyIndex ) { Type propertyType = mainSidePersister . getPropertyTypes ( ) [ propertyIndex ] ; SessionFactoryImplementor factory = mainSidePersister . getFactory ( ) ; // property represents no association, so no inverse meta-data can exist if ( ! propertyType . isAssociationType ( ) ) { return null ; } Joinable mainSideJoinable = ( ( AssociationType ) propertyType ) . getAssociatedJoinable ( factory ) ; OgmEntityPersister inverseSidePersister = null ; // to-many association if ( mainSideJoinable . isCollection ( ) ) { inverseSidePersister = ( OgmEntityPersister ) ( ( OgmCollectionPersister ) mainSideJoinable ) . getElementPersister ( ) ; } // to-one else { inverseSidePersister = ( OgmEntityPersister ) mainSideJoinable ; mainSideJoinable = mainSidePersister ; } String mainSideProperty = mainSidePersister . getPropertyNames ( ) [ propertyIndex ] ; // property is a one-to-one association (a many-to-one cannot be on the inverse side) -> get the meta-data // straight from the main-side persister AssociationKeyMetadata inverseOneToOneMetadata = mainSidePersister . getInverseOneToOneAssociationKeyMetadata ( mainSideProperty ) ; if ( inverseOneToOneMetadata != null ) { return inverseOneToOneMetadata ; } // process properties of inverse side and try to find association back to main side for ( String candidateProperty : inverseSidePersister . getPropertyNames ( ) ) { Type type = inverseSidePersister . getPropertyType ( candidateProperty ) ; // candidate is a *-to-many association if ( type . isCollectionType ( ) ) { OgmCollectionPersister inverseCollectionPersister = getPersister ( factory , ( CollectionType ) type ) ; String mappedByProperty = inverseCollectionPersister . getMappedByProperty ( ) ; if ( mainSideProperty . equals ( mappedByProperty ) ) { if ( isCollectionMatching ( mainSideJoinable , inverseCollectionPersister ) ) { return inverseCollectionPersister . getAssociationKeyMetadata ( ) ; } } } } return null ; }
Returns the meta - data for the inverse side of the association represented by the given property on the given persister in case it represents the main side of a bi - directional one - to - many or many - to - many association .
500
47
147,372
public static OgmCollectionPersister getInverseCollectionPersister ( OgmCollectionPersister mainSidePersister ) { if ( mainSidePersister . isInverse ( ) || ! mainSidePersister . isManyToMany ( ) || ! mainSidePersister . getElementType ( ) . isEntityType ( ) ) { return null ; } EntityPersister inverseSidePersister = mainSidePersister . getElementPersister ( ) ; // process collection-typed properties of inverse side and try to find association back to main side for ( Type type : inverseSidePersister . getPropertyTypes ( ) ) { if ( type . isCollectionType ( ) ) { OgmCollectionPersister inverseCollectionPersister = getPersister ( mainSidePersister . getFactory ( ) , ( CollectionType ) type ) ; if ( isCollectionMatching ( mainSidePersister , inverseCollectionPersister ) ) { return inverseCollectionPersister ; } } } return null ; }
Returns the given collection persister for the inverse side in case the given persister represents the main side of a bi - directional many - to - many association .
204
32
147,373
private static boolean isCollectionMatching ( Joinable mainSideJoinable , OgmCollectionPersister inverseSidePersister ) { boolean isSameTable = mainSideJoinable . getTableName ( ) . equals ( inverseSidePersister . getTableName ( ) ) ; if ( ! isSameTable ) { return false ; } return Arrays . equals ( mainSideJoinable . getKeyColumnNames ( ) , inverseSidePersister . getElementColumnNames ( ) ) ; }
Checks whether table name and key column names of the given joinable and inverse collection persister match .
100
21
147,374
public static void resetValue ( Document entity , String column ) { // fast path for non-embedded case if ( ! column . contains ( "." ) ) { entity . remove ( column ) ; } else { String [ ] path = DOT_SEPARATOR_PATTERN . split ( column ) ; Object field = entity ; int size = path . length ; for ( int index = 0 ; index < size ; index ++ ) { String node = path [ index ] ; Document parent = ( Document ) field ; field = parent . get ( node ) ; if ( field == null && index < size - 1 ) { //TODO clean up the hierarchy of empty containers // no way to reach the leaf, nothing to do return ; } if ( index == size - 1 ) { parent . remove ( node ) ; } } } }
Remove a column from the Document
174
6
147,375
private static void validateAsMongoDBCollectionName ( String collectionName ) { Contracts . assertStringParameterNotEmpty ( collectionName , "requestedName" ) ; //Yes it has some strange requirements. if ( collectionName . startsWith ( "system." ) ) { throw log . collectionNameHasInvalidSystemPrefix ( collectionName ) ; } else if ( collectionName . contains ( "\u0000" ) ) { throw log . collectionNameContainsNULCharacter ( collectionName ) ; } else if ( collectionName . contains ( "$" ) ) { throw log . collectionNameContainsDollarCharacter ( collectionName ) ; } }
Validates a String to be a valid name to be used in MongoDB for a collection name .
135
20
147,376
private void validateAsMongoDBFieldName ( String fieldName ) { if ( fieldName . startsWith ( "$" ) ) { throw log . fieldNameHasInvalidDollarPrefix ( fieldName ) ; } else if ( fieldName . contains ( "\u0000" ) ) { throw log . fieldNameContainsNULCharacter ( fieldName ) ; } }
Validates a String to be a valid name to be used in MongoDB for a field name .
77
20
147,377
private static int determineBatchSize ( boolean canGridDialectDoMultiget , int classBatchSize , int configuredDefaultBatchSize ) { // if the dialect does not support it, don't batch so that we can avoid skewing the ORM fetch statistics if ( ! canGridDialectDoMultiget ) { return - 1 ; } else if ( classBatchSize != - 1 ) { return classBatchSize ; } else if ( configuredDefaultBatchSize != - 1 ) { return configuredDefaultBatchSize ; } else { return DEFAULT_MULTIGET_BATCH_SIZE ; } }
Returns the effective batch size . If the dialect is multiget capable and a batch size has been configured use that one otherwise the default .
132
28
147,378
private String getInverseOneToOneProperty ( String property , OgmEntityPersister otherSidePersister ) { for ( String candidate : otherSidePersister . getPropertyNames ( ) ) { Type candidateType = otherSidePersister . getPropertyType ( candidate ) ; if ( candidateType . isEntityType ( ) && ( ( ( EntityType ) candidateType ) . isOneToOne ( ) && isOneToOneMatching ( this , property , ( OneToOneType ) candidateType ) ) ) { return candidate ; } } return null ; }
Returns the name from the inverse side if the given property de - notes a one - to - one association .
117
22
147,379
@ Override public Object [ ] getDatabaseSnapshot ( Serializable id , SharedSessionContractImplementor session ) throws HibernateException { if ( log . isTraceEnabled ( ) ) { log . trace ( "Getting current persistent state for: " + MessageHelper . infoString ( this , id , getFactory ( ) ) ) ; } //snapshot is a Map in the end final Tuple resultset = getFreshTuple ( EntityKeyBuilder . fromPersister ( this , id , session ) , session ) ; //if there is no resulting row, return null if ( resultset == null || resultset . getSnapshot ( ) . isEmpty ( ) ) { return null ; } //otherwise return the "hydrated" state (ie. associations are not resolved) GridType [ ] types = gridPropertyTypes ; Object [ ] values = new Object [ types . length ] ; boolean [ ] includeProperty = getPropertyUpdateability ( ) ; for ( int i = 0 ; i < types . length ; i ++ ) { if ( includeProperty [ i ] ) { values [ i ] = types [ i ] . hydrate ( resultset , getPropertyAliases ( "" , i ) , session , null ) ; //null owner ok?? } } return values ; }
This snapshot is meant to be used when updating data .
270
11
147,380
private Object initializeLazyPropertiesFromCache ( final String fieldName , final Object entity , final SharedSessionContractImplementor session , final EntityEntry entry , final CacheEntry cacheEntry ) { throw new NotSupportedException ( "OGM-9" , "Lazy properties not supported in OGM" ) ; }
Make superclasses method protected??
66
6
147,381
@ Override public Object getCurrentVersion ( Serializable id , SharedSessionContractImplementor session ) throws HibernateException { if ( log . isTraceEnabled ( ) ) { log . trace ( "Getting version: " + MessageHelper . infoString ( this , id , getFactory ( ) ) ) ; } final Tuple resultset = getFreshTuple ( EntityKeyBuilder . fromPersister ( this , id , session ) , session ) ; if ( resultset == null ) { return null ; } else { return gridVersionType . nullSafeGet ( resultset , getVersionColumnName ( ) , session , null ) ; } }
Retrieve the version number
137
5
147,382
private boolean isAllOrDirtyOptLocking ( ) { EntityMetamodel entityMetamodel = getEntityMetamodel ( ) ; return entityMetamodel . getOptimisticLockStyle ( ) == OptimisticLockStyle . DIRTY || entityMetamodel . getOptimisticLockStyle ( ) == OptimisticLockStyle . ALL ; }
Copied from AbstractEntityPersister
81
7
147,383
private void removeFromInverseAssociations ( Tuple resultset , int tableIndex , Serializable id , SharedSessionContractImplementor session ) { new EntityAssociationUpdater ( this ) . id ( id ) . resultset ( resultset ) . session ( session ) . tableIndex ( tableIndex ) . propertyMightRequireInverseAssociationManagement ( propertyMightBeMainSideOfBidirectionalAssociation ) . removeNavigationalInformationFromInverseSide ( ) ; }
Removes the given entity from the inverse associations it manages .
106
12
147,384
private void addToInverseAssociations ( Tuple resultset , int tableIndex , Serializable id , SharedSessionContractImplementor session ) { new EntityAssociationUpdater ( this ) . id ( id ) . resultset ( resultset ) . session ( session ) . tableIndex ( tableIndex ) . propertyMightRequireInverseAssociationManagement ( propertyMightBeMainSideOfBidirectionalAssociation ) . addNavigationalInformationForInverseSide ( ) ; }
Adds the given entity to the inverse associations it manages .
106
11
147,385
private void processGeneratedProperties ( Serializable id , Object entity , Object [ ] state , SharedSessionContractImplementor session , GenerationTiming matchTiming ) { Tuple tuple = getFreshTuple ( EntityKeyBuilder . fromPersister ( this , id , session ) , session ) ; saveSharedTuple ( entity , tuple , session ) ; if ( tuple == null || tuple . getSnapshot ( ) . isEmpty ( ) ) { throw log . couldNotRetrieveEntityForRetrievalOfGeneratedProperties ( getEntityName ( ) , id ) ; } int propertyIndex = - 1 ; for ( NonIdentifierAttribute attribute : getEntityMetamodel ( ) . getProperties ( ) ) { propertyIndex ++ ; final ValueGeneration valueGeneration = attribute . getValueGenerationStrategy ( ) ; if ( isReadRequired ( valueGeneration , matchTiming ) ) { Object hydratedState = gridPropertyTypes [ propertyIndex ] . hydrate ( tuple , getPropertyAliases ( "" , propertyIndex ) , session , entity ) ; state [ propertyIndex ] = gridPropertyTypes [ propertyIndex ] . resolve ( hydratedState , session , entity ) ; setPropertyValue ( entity , propertyIndex , state [ propertyIndex ] ) ; } } }
Re - reads the given entity refreshing any properties updated on the server - side during insert or update .
272
20
147,386
private boolean isReadRequired ( ValueGeneration valueGeneration , GenerationTiming matchTiming ) { return valueGeneration != null && valueGeneration . getValueGenerator ( ) == null && timingsMatch ( valueGeneration . getGenerationTiming ( ) , matchTiming ) ; }
Whether the given value generation strategy requires to read the value from the database or not .
63
17
147,387
public static List < Object > listOfEntities ( SharedSessionContractImplementor session , Type [ ] resultTypes , ClosableIterator < Tuple > tuples ) { Class < ? > returnedClass = resultTypes [ 0 ] . getReturnedClass ( ) ; TupleBasedEntityLoader loader = getLoader ( session , returnedClass ) ; OgmLoadingContext ogmLoadingContext = new OgmLoadingContext ( ) ; ogmLoadingContext . setTuples ( getTuplesAsList ( tuples ) ) ; return loader . loadEntitiesFromTuples ( session , LockOptions . NONE , ogmLoadingContext ) ; }
At the moment we only support the case where one entity type is returned
135
14
147,388
private void doBatchWork ( BatchBackend backend ) throws InterruptedException { ExecutorService executor = Executors . newFixedThreadPool ( typesToIndexInParallel , "BatchIndexingWorkspace" ) ; for ( IndexedTypeIdentifier indexedTypeIdentifier : rootIndexedTypes ) { executor . execute ( new BatchIndexingWorkspace ( gridDialect , searchFactoryImplementor , sessionFactory , indexedTypeIdentifier , cacheMode , endAllSignal , monitor , backend , tenantId ) ) ; } executor . shutdown ( ) ; endAllSignal . await ( ) ; // waits for the executor to finish }
Will spawn a thread for each type in rootEntities they will all re - join on endAllSignal when finished .
142
25
147,389
private void afterBatch ( BatchBackend backend ) { IndexedTypeSet targetedTypes = searchFactoryImplementor . getIndexedTypesPolymorphic ( rootIndexedTypes ) ; if ( this . optimizeAtEnd ) { backend . optimize ( targetedTypes ) ; } backend . flush ( targetedTypes ) ; }
Operations to do after all subthreads finished their work on index
67
14
147,390
private void beforeBatch ( BatchBackend backend ) { if ( this . purgeAtStart ) { // purgeAll for affected entities IndexedTypeSet targetedTypes = searchFactoryImplementor . getIndexedTypesPolymorphic ( rootIndexedTypes ) ; for ( IndexedTypeIdentifier type : targetedTypes ) { // needs do be in-sync work to make sure we wait for the end of it. backend . doWorkInSync ( new PurgeAllLuceneWork ( tenantId , type ) ) ; } if ( this . optimizeAfterPurge ) { backend . optimize ( targetedTypes ) ; } } }
Optional operations to do before the multiple - threads start indexing
131
12
147,391
@ SafeVarargs public static < T > Set < T > asSet ( T ... ts ) { if ( ts == null ) { return null ; } else if ( ts . length == 0 ) { return Collections . emptySet ( ) ; } else { Set < T > set = new HashSet < T > ( getInitialCapacityFromExpectedSize ( ts . length ) ) ; Collections . addAll ( set , ts ) ; return Collections . unmodifiableSet ( set ) ; } }
Returns an unmodifiable set containing the given elements .
104
11
147,392
private boolean isOrdinal ( int paramType ) { switch ( paramType ) { case Types . INTEGER : case Types . NUMERIC : case Types . SMALLINT : case Types . TINYINT : case Types . BIGINT : case Types . DECIMAL : //for Oracle Driver case Types . DOUBLE : //for Oracle Driver case Types . FLOAT : //for Oracle Driver return true ; case Types . CHAR : case Types . LONGVARCHAR : case Types . VARCHAR : return false ; default : throw new HibernateException ( "Unable to persist an Enum in a column of SQL Type: " + paramType ) ; } }
in truth we probably only need the types as injected by the metadata binder
144
15
147,393
public ClosableIterator < Tuple > callStoredProcedure ( EmbeddedCacheManager embeddedCacheManager , String storedProcedureName , ProcedureQueryParameters queryParameters , ClassLoaderService classLoaderService ) { validate ( queryParameters ) ; Cache < String , String > cache = embeddedCacheManager . getCache ( STORED_PROCEDURES_CACHE_NAME , true ) ; String className = cache . getOrDefault ( storedProcedureName , storedProcedureName ) ; Callable < ? > callable = instantiate ( storedProcedureName , className , classLoaderService ) ; setParams ( storedProcedureName , queryParameters , callable ) ; Object res = execute ( storedProcedureName , embeddedCacheManager , callable ) ; return extractResultSet ( storedProcedureName , res ) ; }
Returns the result of a stored procedure executed on the backend .
182
12
147,394
public static String getPrefix ( String column ) { return column . contains ( "." ) ? DOT_SEPARATOR_PATTERN . split ( column ) [ 0 ] : null ; }
If the column name is a dotted column returns the first part . Returns null otherwise .
41
17
147,395
public static String getColumnSharedPrefix ( String [ ] associationKeyColumns ) { String prefix = null ; for ( String column : associationKeyColumns ) { String newPrefix = getPrefix ( column ) ; if ( prefix == null ) { // first iteration prefix = newPrefix ; if ( prefix == null ) { // no prefix, quit break ; } } else { // subsequent iterations if ( ! equals ( prefix , newPrefix ) ) { // different prefixes prefix = null ; break ; } } } return prefix ; }
Returns the shared prefix of these columns . Null otherwise .
114
11
147,396
public static ThreadPoolExecutor newFixedThreadPool ( int threads , String groupname , int queueSize ) { return new ThreadPoolExecutor ( threads , threads , 0L , TimeUnit . MILLISECONDS , new LinkedBlockingQueue < Runnable > ( queueSize ) , new SearchThreadFactory ( groupname ) , new BlockPolicy ( ) ) ; }
Creates a new fixed size ThreadPoolExecutor
79
10
147,397
public static void readAndCheckVersion ( ObjectInput input , int supportedVersion , Class < ? > externalizedType ) throws IOException { int version = input . readInt ( ) ; if ( version != supportedVersion ) { throw LOG . unexpectedKeyVersion ( externalizedType , version , supportedVersion ) ; } }
Consumes the version field from the given input and raises an exception if the record is in a newer version written by a newer version of Hibernate OGM .
65
34
147,398
public static boolean matches ( Map < String , Object > nodeProperties , String [ ] keyColumnNames , Object [ ] keyColumnValues ) { for ( int i = 0 ; i < keyColumnNames . length ; i ++ ) { String property = keyColumnNames [ i ] ; Object expectedValue = keyColumnValues [ i ] ; boolean containsProperty = nodeProperties . containsKey ( property ) ; if ( containsProperty ) { Object actualValue = nodeProperties . get ( property ) ; if ( ! sameValue ( expectedValue , actualValue ) ) { return false ; } } else if ( expectedValue != null ) { return false ; } } return true ; }
Check if the node matches the column values
140
8
147,399
public GeoPolygon addHoles ( List < List < GeoPoint > > holes ) { Contracts . assertNotNull ( holes , "holes" ) ; this . rings . addAll ( holes ) ; return this ; }
Adds new holes to the polygon .
46
8