code stringlengths 73 34.1k | label stringclasses 1 value |
|---|---|
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;
} | java |
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 );
} | java |
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;
} | java |
public boolean isAssociation(String targetTypeName, List<String> pathWithoutAlias) {
OgmEntityPersister persister = getPersister( targetTypeName );
Type propertyType = persister.getPropertyType( pathWithoutAlias.get( 0 ) );
return propertyType.isAssociationType();
} | java |
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;
} | java |
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 );
} | java |
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 );
} | java |
public static boolean isPartOfRegularEmbedded(String[] keyColumnNames, String column) {
return isPartOfEmbedded( column ) && !ArrayHelper.contains( keyColumnNames, column );
} | java |
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 );
} | java |
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 );
} | java |
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 );
}
}
}
} | java |
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();
} | java |
private static Row row(List<StatementResult> results) {
Row row = results.get( 0 ).getData().get( 0 );
return row;
} | java |
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;
} | java |
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() );
}
} | java |
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;
} | java |
private static Document getProjection(List<String> fieldNames) {
Document projection = new Document();
for ( String column : fieldNames ) {
projection.put( column, 1 );
}
return projection;
} | java |
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;
} | java |
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 ) ) );
} | java |
@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 );
}
} | java |
@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 );
} | java |
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 );
} | java |
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 );
} | java |
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 );
}
} | java |
public Association getAssociation(String collectionRole) {
if ( associations == null ) {
return null;
}
return associations.get( collectionRole );
} | java |
public void setAssociation(String collectionRole, Association association) {
if ( associations == null ) {
associations = new HashMap<>();
}
associations.put( collectionRole, association );
} | java |
@Override
public void addExtraState(EntityEntryExtraState extraState) {
if ( next == null ) {
next = extraState;
}
else {
next.addExtraState( extraState );
}
} | java |
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;
} | java |
public Set<TupleOperation> getOperations() {
if ( currentState == null ) {
return Collections.emptySet();
}
else {
return new SetFromCollection<TupleOperation>( currentState.values() );
}
} | java |
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 );
}
} | java |
public static String[] slice(String[] strings, int begin, int length) {
String[] result = new String[length];
System.arraycopy( strings, begin, result, 0, length );
return result;
} | java |
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;
} | java |
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;
} | java |
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;
} | java |
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;
} | java |
public static void registerOgmExternalizers(SerializationConfigurationBuilder cfg) {
for ( AdvancedExternalizer<?> advancedExternalizer : ogmExternalizers.values() ) {
cfg.addAdvancedExternalizer( advancedExternalizer );
}
} | java |
public static void registerOgmExternalizers(GlobalConfiguration globalCfg) {
Map<Integer, AdvancedExternalizer<?>> externalizerMap = globalCfg.serialization().advancedExternalizers();
externalizerMap.putAll( ogmExternalizers );
} | java |
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 );
}
}
}
} | java |
public void writeLock(EntityKey key, int timeout) {
ReadWriteLock lock = getLock( key );
Lock writeLock = lock.writeLock();
acquireLock( key, timeout, writeLock );
} | java |
public void readLock(EntityKey key, int timeout) {
ReadWriteLock lock = getLock( key );
Lock readLock = lock.readLock();
acquireLock( key, timeout, readLock );
} | java |
public Map<AssociationKey, Map<RowKey, Map<String, Object>>> getAssociationsMap() {
return Collections.unmodifiableMap( associationsKeyValueStorage );
} | java |
public static String flatten(String left, String right) {
return left == null || left.isEmpty() ? right : left + "." + right;
} | java |
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;
} | java |
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 );
}
}
} | java |
public GeoMultiPoint addPoint(GeoPoint point) {
Contracts.assertNotNull( point, "point" );
this.points.add( point );
return this;
} | java |
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();
} | java |
public Node createEmbedded(GraphDatabaseService executionEngine, Object[] columnValues) {
Map<String, Object> params = params( columnValues );
Result result = executionEngine.execute( getCreateEmbeddedNodeQuery(), params );
return singleResult( result );
} | java |
public Node findEntity(GraphDatabaseService executionEngine, Object[] columnValues) {
Map<String, Object> params = params( columnValues );
Result result = executionEngine.execute( getFindEntityQuery(), params );
return singleResult( result );
} | java |
public Node insertEntity(GraphDatabaseService executionEngine, Object[] columnValues) {
Map<String, Object> params = params( columnValues );
Result result = executionEngine.execute( getCreateEntityQuery(), params );
return singleResult( result );
} | java |
public ResourceIterator<Node> findEntities(GraphDatabaseService executionEngine) {
Result result = executionEngine.execute( getFindEntitiesQuery() );
return result.columnAs( BaseNeo4jEntityQueries.ENTITY_ALIAS );
} | java |
public void removeEntity(GraphDatabaseService executionEngine, Object[] columnValues) {
Map<String, Object> params = params( columnValues );
executionEngine.execute( getRemoveEntityQuery(), params );
} | java |
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 );
} | java |
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;
} | java |
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;
} | java |
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;
} | java |
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() );
} | java |
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 );
}
}
}
} | java |
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 );
}
} | java |
private void validateAsMongoDBFieldName(String fieldName) {
if ( fieldName.startsWith( "$" ) ) {
throw log.fieldNameHasInvalidDollarPrefix( fieldName );
}
else if ( fieldName.contains( "\u0000" ) ) {
throw log.fieldNameContainsNULCharacter( fieldName );
}
} | java |
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;
}
} | java |
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;
} | java |
@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;
} | java |
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" );
} | java |
@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 );
}
} | java |
private boolean isAllOrDirtyOptLocking() {
EntityMetamodel entityMetamodel = getEntityMetamodel();
return entityMetamodel.getOptimisticLockStyle() == OptimisticLockStyle.DIRTY
|| entityMetamodel.getOptimisticLockStyle() == OptimisticLockStyle.ALL;
} | java |
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();
} | java |
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();
} | java |
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] );
}
}
} | java |
private boolean isReadRequired(ValueGeneration valueGeneration, GenerationTiming matchTiming) {
return valueGeneration != null && valueGeneration.getValueGenerator() == null &&
timingsMatch( valueGeneration.getGenerationTiming(), matchTiming );
} | java |
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 );
} | java |
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
} | java |
private void afterBatch(BatchBackend backend) {
IndexedTypeSet targetedTypes = searchFactoryImplementor.getIndexedTypesPolymorphic( rootIndexedTypes );
if ( this.optimizeAtEnd ) {
backend.optimize( targetedTypes );
}
backend.flush( targetedTypes );
} | java |
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 );
}
}
} | java |
@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 );
}
} | java |
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 );
}
} | java |
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 );
} | java |
public static String getPrefix(String column) {
return column.contains( "." ) ? DOT_SEPARATOR_PATTERN.split( column )[0] : null;
} | java |
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;
} | java |
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() );
} | java |
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 );
}
} | java |
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;
} | java |
public GeoPolygon addHoles(List<List<GeoPoint>> holes) {
Contracts.assertNotNull( holes, "holes" );
this.rings.addAll( holes );
return this;
} | java |
public void addAll(OptionsContainerBuilder container) {
for ( Entry<Class<? extends Option<?, ?>>, ValueContainerBuilder<?, ?>> entry : container.optionValues.entrySet() ) {
addAll( entry.getKey(), entry.getValue().build() );
}
} | java |
private static IndexedTypeSet toRootEntities(ExtendedSearchIntegrator extendedIntegrator, Class<?>... selection) {
Set<Class<?>> entities = new HashSet<Class<?>>();
//first build the "entities" set containing all indexed subtypes of "selection".
for ( Class<?> entityType : selection ) {
IndexedTypeSet targetedClasses = extendedIntegrator.getIndexedTypesPolymorphic( IndexedTypeSets.fromClass( entityType ) );
if ( targetedClasses.isEmpty() ) {
String msg = entityType.getName() + " is not an indexed entity or a subclass of an indexed entity";
throw new IllegalArgumentException( msg );
}
entities.addAll( targetedClasses.toPojosSet() );
}
Set<Class<?>> cleaned = new HashSet<Class<?>>();
Set<Class<?>> toRemove = new HashSet<Class<?>>();
//now remove all repeated types to avoid duplicate loading by polymorphic query loading
for ( Class<?> type : entities ) {
boolean typeIsOk = true;
for ( Class<?> existing : cleaned ) {
if ( existing.isAssignableFrom( type ) ) {
typeIsOk = false;
break;
}
if ( type.isAssignableFrom( existing ) ) {
toRemove.add( existing );
}
}
if ( typeIsOk ) {
cleaned.add( type );
}
}
cleaned.removeAll( toRemove );
log.debugf( "Targets for indexing job: %s", cleaned );
return IndexedTypeSets.fromClasses( cleaned.toArray( new Class[cleaned.size()] ) );
} | java |
private void updateHostingEntityIfRequired() {
if ( hostingEntity != null && hostingEntityRequiresReadAfterUpdate() ) {
OgmEntityPersister entityPersister = getHostingEntityPersister();
if ( GridDialects.hasFacet( gridDialect, GroupingByEntityDialect.class ) ) {
( (GroupingByEntityDialect) gridDialect ).flushPendingOperations( getAssociationKey().getEntityKey(),
entityPersister.getTupleContext( session ) );
}
entityPersister.processUpdateGeneratedProperties(
entityPersister.getIdentifier( hostingEntity, session ),
hostingEntity,
new Object[entityPersister.getPropertyNames().length],
session
);
}
} | java |
private static List<Class<?>> getClassHierarchy(Class<?> clazz) {
List<Class<?>> hierarchy = new ArrayList<Class<?>>( 4 );
for ( Class<?> current = clazz; current != null; current = current.getSuperclass() ) {
hierarchy.add( current );
}
return hierarchy;
} | java |
public static PersistenceStrategy<?, ?, ?> getInstance(
CacheMappingType cacheMapping,
EmbeddedCacheManager externalCacheManager,
URL configurationUrl,
JtaPlatform jtaPlatform,
Set<EntityKeyMetadata> entityTypes,
Set<AssociationKeyMetadata> associationTypes,
Set<IdSourceKeyMetadata> idSourceTypes ) {
if ( cacheMapping == CacheMappingType.CACHE_PER_KIND ) {
return getPerKindStrategy(
externalCacheManager,
configurationUrl,
jtaPlatform
);
}
else {
return getPerTableStrategy(
externalCacheManager,
configurationUrl,
jtaPlatform,
entityTypes,
associationTypes,
idSourceTypes
);
}
} | java |
private Iterable<PersistentNoSqlIdentifierGenerator> getPersistentGenerators() {
Map<String, EntityPersister> entityPersisters = factory.getMetamodel().entityPersisters();
Set<PersistentNoSqlIdentifierGenerator> persistentGenerators = new HashSet<PersistentNoSqlIdentifierGenerator>( entityPersisters.size() );
for ( EntityPersister persister : entityPersisters.values() ) {
if ( persister.getIdentifierGenerator() instanceof PersistentNoSqlIdentifierGenerator ) {
persistentGenerators.add( (PersistentNoSqlIdentifierGenerator) persister.getIdentifierGenerator() );
}
}
return persistentGenerators;
} | java |
public Relationship createRelationshipForEmbeddedAssociation(GraphDatabaseService executionEngine, AssociationKey associationKey, EntityKey embeddedKey) {
String query = initCreateEmbeddedAssociationQuery( associationKey, embeddedKey );
Object[] queryValues = createRelationshipForEmbeddedQueryValues( associationKey, embeddedKey );
return executeQuery( executionEngine, query, queryValues );
} | java |
private RowKeyAndTuple createAndPutAssociationRowForInsert(Serializable key, PersistentCollection collection,
AssociationPersister associationPersister, SharedSessionContractImplementor session, int i, Object entry) {
RowKeyBuilder rowKeyBuilder = initializeRowKeyBuilder();
Tuple associationRow = new Tuple();
// the collection has a surrogate key (see @CollectionId)
if ( hasIdentifier ) {
final Object identifier = collection.getIdentifier( entry, i );
String[] names = { getIdentifierColumnName() };
identifierGridType.nullSafeSet( associationRow, identifier, names, session );
}
getKeyGridType().nullSafeSet( associationRow, key, getKeyColumnNames(), session );
// No need to write to where as we don't do where clauses in OGM :)
if ( hasIndex ) {
Object index = collection.getIndex( entry, i, this );
indexGridType.nullSafeSet( associationRow, incrementIndexByBase( index ), getIndexColumnNames(), session );
}
// columns of referenced key
final Object element = collection.getElement( entry );
getElementGridType().nullSafeSet( associationRow, element, getElementColumnNames(), session );
RowKeyAndTuple result = new RowKeyAndTuple();
result.key = rowKeyBuilder.values( associationRow ).build();
result.tuple = associationRow;
associationPersister.getAssociation().put( result.key, result.tuple );
return result;
} | java |
@Override
protected void doProcessQueuedOps(PersistentCollection collection, Serializable key, int nextIndex, SharedSessionContractImplementor session)
throws HibernateException {
// nothing to do
} | java |
public boolean isIdProperty(OgmEntityPersister persister, List<String> namesWithoutAlias) {
String join = StringHelper.join( namesWithoutAlias, "." );
Type propertyType = persister.getPropertyType( namesWithoutAlias.get( 0 ) );
String[] identifierColumnNames = persister.getIdentifierColumnNames();
if ( propertyType.isComponentType() ) {
String[] embeddedColumnNames = persister.getPropertyColumnNames( join );
for ( String embeddedColumn : embeddedColumnNames ) {
if ( !ArrayHelper.contains( identifierColumnNames, embeddedColumn ) ) {
return false;
}
}
return true;
}
return ArrayHelper.contains( identifierColumnNames, join );
} | java |
public void deploySchema(String generatedProtobufName, RemoteCache<String, String> protobufCache, SchemaCapture schemaCapture, SchemaOverride schemaOverrideService,
URL schemaOverrideResource) {
// user defined schema
if ( schemaOverrideService != null || schemaOverrideResource != null ) {
cachedSchema = new SchemaValidator( this, schemaOverrideService, schemaOverrideResource, generatedProtobufName ).provideSchema();
}
// or generate them
generateProtoschema();
try {
protobufCache.put( generatedProtobufName, cachedSchema );
String errors = protobufCache.get( generatedProtobufName + ".errors" );
if ( errors != null ) {
throw LOG.errorAtSchemaDeploy( generatedProtobufName, errors );
}
LOG.successfulSchemaDeploy( generatedProtobufName );
}
catch (HotRodClientException hrce) {
throw LOG.errorAtSchemaDeploy( generatedProtobufName, hrce );
}
if ( schemaCapture != null ) {
schemaCapture.put( generatedProtobufName, cachedSchema );
}
} | java |
public static void archiveFile(@NotNull final ArchiveOutputStream out,
@NotNull final VirtualFileDescriptor source,
final long fileSize) throws IOException {
if (!source.hasContent()) {
throw new IllegalArgumentException("Provided source is not a file: " + source.getPath());
}
//noinspection ChainOfInstanceofChecks
if (out instanceof TarArchiveOutputStream) {
final TarArchiveEntry entry = new TarArchiveEntry(source.getPath() + source.getName());
entry.setSize(fileSize);
entry.setModTime(source.getTimeStamp());
out.putArchiveEntry(entry);
} else if (out instanceof ZipArchiveOutputStream) {
final ZipArchiveEntry entry = new ZipArchiveEntry(source.getPath() + source.getName());
entry.setSize(fileSize);
entry.setTime(source.getTimeStamp());
out.putArchiveEntry(entry);
} else {
throw new IOException("Unknown archive output stream");
}
final InputStream input = source.getInputStream();
try {
IOUtil.copyStreams(input, fileSize, out, IOUtil.BUFFER_ALLOCATOR);
} finally {
if (source.shouldCloseStream()) {
input.close();
}
}
out.closeArchiveEntry();
} | java |
void setRightChild(final byte b, @NotNull final MutableNode child) {
final ChildReference right = children.getRight();
if (right == null || (right.firstByte & 0xff) != (b & 0xff)) {
throw new IllegalArgumentException();
}
children.setAt(children.size() - 1, new ChildReferenceMutable(b, child));
} | java |
public boolean needMerge(@NotNull final BasePage left, @NotNull final BasePage right) {
final int leftSize = left.getSize();
final int rightSize = right.getSize();
return leftSize == 0 || rightSize == 0 ||
leftSize + rightSize <= (((isDupTree(left) ? getDupPageMaxSize() : getPageMaxSize()) * 7) >> 3);
} | java |
@NotNull
static MetaTreeImpl.Proto saveMetaTree(@NotNull final ITreeMutable metaTree,
@NotNull final EnvironmentImpl env,
@NotNull final ExpiredLoggableCollection expired) {
final long newMetaTreeAddress = metaTree.save();
final Log log = env.getLog();
final int lastStructureId = env.getLastStructureId();
final long dbRootAddress = log.write(DatabaseRoot.DATABASE_ROOT_TYPE, Loggable.NO_STRUCTURE_ID,
DatabaseRoot.asByteIterable(newMetaTreeAddress, lastStructureId));
expired.add(dbRootAddress, (int) (log.getWrittenHighAddress() - dbRootAddress));
return new MetaTreeImpl.Proto(newMetaTreeAddress, dbRootAddress);
} | java |
@SuppressWarnings({"OverlyLongMethod"})
public void clearProperties(@NotNull final PersistentStoreTransaction txn, @NotNull final Entity entity) {
final Transaction envTxn = txn.getEnvironmentTransaction();
final PersistentEntityId id = (PersistentEntityId) entity.getId();
final int entityTypeId = id.getTypeId();
final long entityLocalId = id.getLocalId();
final PropertiesTable properties = getPropertiesTable(txn, entityTypeId);
final PropertyKey propertyKey = new PropertyKey(entityLocalId, 0);
try (Cursor cursor = getPrimaryPropertyIndexCursor(txn, properties)) {
for (boolean success = cursor.getSearchKeyRange(PropertyKey.propertyKeyToEntry(propertyKey)) != null;
success; success = cursor.getNext()) {
ByteIterable keyEntry = cursor.getKey();
final PropertyKey key = PropertyKey.entryToPropertyKey(keyEntry);
if (key.getEntityLocalId() != entityLocalId) {
break;
}
final int propertyId = key.getPropertyId();
final ByteIterable value = cursor.getValue();
final PropertyValue propValue = propertyTypes.entryToPropertyValue(value);
txn.propertyChanged(id, propertyId, propValue.getData(), null);
properties.deleteNoFail(txn, entityLocalId, value, propertyId, propValue.getType());
}
}
} | java |
boolean deleteEntity(@NotNull final PersistentStoreTransaction txn, @NotNull final PersistentEntity entity) {
clearProperties(txn, entity);
clearBlobs(txn, entity);
deleteLinks(txn, entity);
final PersistentEntityId id = entity.getId();
final int entityTypeId = id.getTypeId();
final long entityLocalId = id.getLocalId();
final ByteIterable key = LongBinding.longToCompressedEntry(entityLocalId);
if (config.isDebugSearchForIncomingLinksOnDelete()) {
// search for incoming links
final List<String> allLinkNames = getAllLinkNames(txn);
for (final String entityType : txn.getEntityTypes()) {
for (final String linkName : allLinkNames) {
//noinspection LoopStatementThatDoesntLoop
for (final Entity referrer : txn.findLinks(entityType, entity, linkName)) {
throw new EntityStoreException(entity +
" is about to be deleted, but it is referenced by " + referrer + ", link name: " + linkName);
}
}
}
}
if (getEntitiesTable(txn, entityTypeId).delete(txn.getEnvironmentTransaction(), key)) {
txn.entityDeleted(id);
return true;
}
return false;
} | java |
private void deleteLinks(@NotNull final PersistentStoreTransaction txn, @NotNull final PersistentEntity entity) {
final PersistentEntityId id = entity.getId();
final int entityTypeId = id.getTypeId();
final long entityLocalId = id.getLocalId();
final Transaction envTxn = txn.getEnvironmentTransaction();
final LinksTable links = getLinksTable(txn, entityTypeId);
final IntHashSet deletedLinks = new IntHashSet();
try (Cursor cursor = links.getFirstIndexCursor(envTxn)) {
for (boolean success = cursor.getSearchKeyRange(PropertyKey.propertyKeyToEntry(new PropertyKey(entityLocalId, 0))) != null;
success; success = cursor.getNext()) {
final ByteIterable keyEntry = cursor.getKey();
final PropertyKey key = PropertyKey.entryToPropertyKey(keyEntry);
if (key.getEntityLocalId() != entityLocalId) {
break;
}
final ByteIterable valueEntry = cursor.getValue();
if (links.delete(envTxn, keyEntry, valueEntry)) {
int linkId = key.getPropertyId();
if (getLinkName(txn, linkId) != null) {
deletedLinks.add(linkId);
final LinkValue linkValue = LinkValue.entryToLinkValue(valueEntry);
txn.linkDeleted(entity.getId(), (PersistentEntityId) linkValue.getEntityId(), linkValue.getLinkId());
}
}
}
}
for (Integer linkId : deletedLinks) {
links.deleteAllIndex(envTxn, linkId, entityLocalId);
}
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.