_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q4200
InfinispanEmbeddedDatastoreProvider.initializePersistenceStrategy
train
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
{ "resource": "" }
q4201
MongoDBDialect.getProjection
train
private static Document getProjection(List<String> fieldNames) { Document projection = new Document(); for ( String column : fieldNames ) { projection.put( column, 1 ); } return projection; }
java
{ "resource": "" }
q4202
MongoDBDialect.objectForInsert
train
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
{ "resource": "" }
q4203
MongoDBDialect.doDistinct
train
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
{ "resource": "" }
q4204
MongoDBDialect.mergeWriteConcern
train
@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
{ "resource": "" }
q4205
MongoDBDialect.callStoredProcedure
train
@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
{ "resource": "" }
q4206
BatchingEntityLoaderBuilder.buildLoader
train
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
{ "resource": "" }
q4207
BatchingEntityLoaderBuilder.buildLoader
train
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
{ "resource": "" }
q4208
EmbeddedNeo4jDialect.applyProperties
train
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
{ "resource": "" }
q4209
OgmEntityEntryState.getAssociation
train
public Association getAssociation(String collectionRole) { if ( associations == null ) { return null; } return associations.get( collectionRole ); }
java
{ "resource": "" }
q4210
OgmEntityEntryState.setAssociation
train
public void setAssociation(String collectionRole, Association association) { if ( associations == null ) { associations = new HashMap<>(); } associations.put( collectionRole, association ); }
java
{ "resource": "" }
q4211
OgmEntityEntryState.addExtraState
train
@Override public void addExtraState(EntityEntryExtraState extraState) { if ( next == null ) { next = extraState; } else { next.addExtraState( extraState ); } }
java
{ "resource": "" }
q4212
ClusteredCounterHandler.getCounterOrCreateIt
train
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
{ "resource": "" }
q4213
Tuple.getOperations
train
public Set<TupleOperation> getOperations() { if ( currentState == null ) { return Collections.emptySet(); } else { return new SetFromCollection<TupleOperation>( currentState.values() ); } }
java
{ "resource": "" }
q4214
AnnotationOptionValueSource.getConverter
train
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
{ "resource": "" }
q4215
ArrayHelper.slice
train
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
{ "resource": "" }
q4216
ArrayHelper.indexOf
train
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
{ "resource": "" }
q4217
ArrayHelper.concat
train
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
{ "resource": "" }
q4218
ArrayHelper.concat
train
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
{ "resource": "" }
q4219
OgmGeneratorBase.doWorkInIsolationTransaction
train
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
{ "resource": "" }
q4220
ExternalizersIntegration.registerOgmExternalizers
train
public static void registerOgmExternalizers(SerializationConfigurationBuilder cfg) { for ( AdvancedExternalizer<?> advancedExternalizer : ogmExternalizers.values() ) { cfg.addAdvancedExternalizer( advancedExternalizer ); } }
java
{ "resource": "" }
q4221
ExternalizersIntegration.registerOgmExternalizers
train
public static void registerOgmExternalizers(GlobalConfiguration globalCfg) { Map<Integer, AdvancedExternalizer<?>> externalizerMap = globalCfg.serialization().advancedExternalizers(); externalizerMap.putAll( ogmExternalizers ); }
java
{ "resource": "" }
q4222
ExternalizersIntegration.validateExternalizersPresent
train
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
{ "resource": "" }
q4223
MapDatastoreProvider.writeLock
train
public void writeLock(EntityKey key, int timeout) { ReadWriteLock lock = getLock( key ); Lock writeLock = lock.writeLock(); acquireLock( key, timeout, writeLock ); }
java
{ "resource": "" }
q4224
MapDatastoreProvider.readLock
train
public void readLock(EntityKey key, int timeout) { ReadWriteLock lock = getLock( key ); Lock readLock = lock.readLock(); acquireLock( key, timeout, readLock ); }
java
{ "resource": "" }
q4225
MapDatastoreProvider.getAssociationsMap
train
public Map<AssociationKey, Map<RowKey, Map<String, Object>>> getAssociationsMap() { return Collections.unmodifiableMap( associationsKeyValueStorage ); }
java
{ "resource": "" }
q4226
DotPatternMapHelpers.flatten
train
public static String flatten(String left, String right) { return left == null || left.isEmpty() ? right : left + "." + right; }
java
{ "resource": "" }
q4227
DotPatternMapHelpers.organizeAssociationMapByRowKey
train
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
{ "resource": "" }
q4228
ManyToOneType.scheduleBatchLoadIfNeeded
train
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
{ "resource": "" }
q4229
GeoMultiPoint.addPoint
train
public GeoMultiPoint addPoint(GeoPoint point) { Contracts.assertNotNull( point, "point" ); this.points.add( point ); return this; }
java
{ "resource": "" }
q4230
Neo4jAliasResolver.findAlias
train
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
{ "resource": "" }
q4231
EmbeddedNeo4jEntityQueries.createEmbedded
train
public Node createEmbedded(GraphDatabaseService executionEngine, Object[] columnValues) { Map<String, Object> params = params( columnValues ); Result result = executionEngine.execute( getCreateEmbeddedNodeQuery(), params ); return singleResult( result ); }
java
{ "resource": "" }
q4232
EmbeddedNeo4jEntityQueries.findEntity
train
public Node findEntity(GraphDatabaseService executionEngine, Object[] columnValues) { Map<String, Object> params = params( columnValues ); Result result = executionEngine.execute( getFindEntityQuery(), params ); return singleResult( result ); }
java
{ "resource": "" }
q4233
EmbeddedNeo4jEntityQueries.insertEntity
train
public Node insertEntity(GraphDatabaseService executionEngine, Object[] columnValues) { Map<String, Object> params = params( columnValues ); Result result = executionEngine.execute( getCreateEntityQuery(), params ); return singleResult( result ); }
java
{ "resource": "" }
q4234
EmbeddedNeo4jEntityQueries.findEntities
train
public ResourceIterator<Node> findEntities(GraphDatabaseService executionEngine) { Result result = executionEngine.execute( getFindEntitiesQuery() ); return result.columnAs( BaseNeo4jEntityQueries.ENTITY_ALIAS ); }
java
{ "resource": "" }
q4235
EmbeddedNeo4jEntityQueries.removeEntity
train
public void removeEntity(GraphDatabaseService executionEngine, Object[] columnValues) { Map<String, Object> params = params( columnValues ); executionEngine.execute( getRemoveEntityQuery(), params ); }
java
{ "resource": "" }
q4236
EmbeddedNeo4jEntityQueries.updateEmbeddedColumn
train
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
{ "resource": "" }
q4237
MongoDBIndexSpec.prepareOptions
train
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
{ "resource": "" }
q4238
BiDirectionalAssociationHelper.getInverseAssociationKeyMetadata
train
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
{ "resource": "" }
q4239
BiDirectionalAssociationHelper.getInverseCollectionPersister
train
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
{ "resource": "" }
q4240
BiDirectionalAssociationHelper.isCollectionMatching
train
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
{ "resource": "" }
q4241
MongoHelpers.resetValue
train
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
{ "resource": "" }
q4242
MongoDBSchemaDefiner.validateAsMongoDBCollectionName
train
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
{ "resource": "" }
q4243
MongoDBSchemaDefiner.validateAsMongoDBFieldName
train
private void validateAsMongoDBFieldName(String fieldName) { if ( fieldName.startsWith( "$" ) ) { throw log.fieldNameHasInvalidDollarPrefix( fieldName ); } else if ( fieldName.contains( "\u0000" ) ) { throw log.fieldNameContainsNULCharacter( fieldName ); } }
java
{ "resource": "" }
q4244
OgmEntityPersister.determineBatchSize
train
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
{ "resource": "" }
q4245
OgmEntityPersister.getInverseOneToOneProperty
train
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
{ "resource": "" }
q4246
OgmEntityPersister.getDatabaseSnapshot
train
@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
{ "resource": "" }
q4247
OgmEntityPersister.initializeLazyPropertiesFromCache
train
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
{ "resource": "" }
q4248
OgmEntityPersister.getCurrentVersion
train
@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
{ "resource": "" }
q4249
OgmEntityPersister.isAllOrDirtyOptLocking
train
private boolean isAllOrDirtyOptLocking() { EntityMetamodel entityMetamodel = getEntityMetamodel(); return entityMetamodel.getOptimisticLockStyle() == OptimisticLockStyle.DIRTY || entityMetamodel.getOptimisticLockStyle() == OptimisticLockStyle.ALL; }
java
{ "resource": "" }
q4250
OgmEntityPersister.removeFromInverseAssociations
train
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
{ "resource": "" }
q4251
OgmEntityPersister.addToInverseAssociations
train
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
{ "resource": "" }
q4252
OgmEntityPersister.processGeneratedProperties
train
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
{ "resource": "" }
q4253
OgmEntityPersister.isReadRequired
train
private boolean isReadRequired(ValueGeneration valueGeneration, GenerationTiming matchTiming) { return valueGeneration != null && valueGeneration.getValueGenerator() == null && timingsMatch( valueGeneration.getGenerationTiming(), matchTiming ); }
java
{ "resource": "" }
q4254
CustomLoaderHelper.listOfEntities
train
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
{ "resource": "" }
q4255
BatchCoordinator.doBatchWork
train
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
{ "resource": "" }
q4256
BatchCoordinator.afterBatch
train
private void afterBatch(BatchBackend backend) { IndexedTypeSet targetedTypes = searchFactoryImplementor.getIndexedTypesPolymorphic( rootIndexedTypes ); if ( this.optimizeAtEnd ) { backend.optimize( targetedTypes ); } backend.flush( targetedTypes ); }
java
{ "resource": "" }
q4257
BatchCoordinator.beforeBatch
train
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
{ "resource": "" }
q4258
CollectionHelper.asSet
train
@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
{ "resource": "" }
q4259
EnumType.isOrdinal
train
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
{ "resource": "" }
q4260
InfinispanEmbeddedStoredProceduresManager.callStoredProcedure
train
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
{ "resource": "" }
q4261
DocumentHelpers.getPrefix
train
public static String getPrefix(String column) { return column.contains( "." ) ? DOT_SEPARATOR_PATTERN.split( column )[0] : null; }
java
{ "resource": "" }
q4262
DocumentHelpers.getColumnSharedPrefix
train
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
{ "resource": "" }
q4263
Executors.newFixedThreadPool
train
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
{ "resource": "" }
q4264
VersionChecker.readAndCheckVersion
train
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
{ "resource": "" }
q4265
RemoteNeo4jHelper.matches
train
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
{ "resource": "" }
q4266
GeoPolygon.addHoles
train
public GeoPolygon addHoles(List<List<GeoPoint>> holes) { Contracts.assertNotNull( holes, "holes" ); this.rings.addAll( holes ); return this; }
java
{ "resource": "" }
q4267
OptionsContainerBuilder.addAll
train
public void addAll(OptionsContainerBuilder container) { for ( Entry<Class<? extends Option<?, ?>>, ValueContainerBuilder<?, ?>> entry : container.optionValues.entrySet() ) { addAll( entry.getKey(), entry.getValue().build() ); } }
java
{ "resource": "" }
q4268
OgmMassIndexer.toRootEntities
train
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
{ "resource": "" }
q4269
AssociationPersister.updateHostingEntityIfRequired
train
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
{ "resource": "" }
q4270
OptionsContextImpl.getClassHierarchy
train
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
{ "resource": "" }
q4271
PersistenceStrategy.getInstance
train
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
{ "resource": "" }
q4272
DefaultSchemaInitializationContext.getPersistentGenerators
train
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
{ "resource": "" }
q4273
EmbeddedNeo4jAssociationQueries.createRelationshipForEmbeddedAssociation
train
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
{ "resource": "" }
q4274
OgmCollectionPersister.createAndPutAssociationRowForInsert
train
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
{ "resource": "" }
q4275
OgmCollectionPersister.doProcessQueuedOps
train
@Override protected void doProcessQueuedOps(PersistentCollection collection, Serializable key, int nextIndex, SharedSessionContractImplementor session) throws HibernateException { // nothing to do }
java
{ "resource": "" }
q4276
Neo4jPropertyHelper.isIdProperty
train
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
{ "resource": "" }
q4277
SchemaDefinitions.deploySchema
train
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
{ "resource": "" }
q4278
CompressBackupUtil.archiveFile
train
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
{ "resource": "" }
q4279
MutableNode.setRightChild
train
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
{ "resource": "" }
q4280
BTreeBalancePolicy.needMerge
train
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
{ "resource": "" }
q4281
MetaTreeImpl.saveMetaTree
train
@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
{ "resource": "" }
q4282
PersistentEntityStoreImpl.clearProperties
train
@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
{ "resource": "" }
q4283
PersistentEntityStoreImpl.deleteEntity
train
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
{ "resource": "" }
q4284
PersistentEntityStoreImpl.deleteLinks
train
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
{ "resource": "" }
q4285
PersistentEntityStoreImpl.getEntityTypeId
train
@Deprecated public int getEntityTypeId(@NotNull final String entityType, final boolean allowCreate) { return getEntityTypeId(txnProvider, entityType, allowCreate); }
java
{ "resource": "" }
q4286
PersistentEntityStoreImpl.getPropertyId
train
public int getPropertyId(@NotNull final PersistentStoreTransaction txn, @NotNull final String propertyName, final boolean allowCreate) { return allowCreate ? propertyIds.getOrAllocateId(txn, propertyName) : propertyIds.getId(txn, propertyName); }
java
{ "resource": "" }
q4287
PersistentEntityStoreImpl.getLinkId
train
public int getLinkId(@NotNull final PersistentStoreTransaction txn, @NotNull final String linkName, final boolean allowCreate) { return allowCreate ? linkIds.getOrAllocateId(txn, linkName) : linkIds.getId(txn, linkName); }
java
{ "resource": "" }
q4288
ThreadJobProcessor.start
train
@Override public synchronized void start() { if (!started.getAndSet(true)) { finished.set(false); thread.start(); } }
java
{ "resource": "" }
q4289
ThreadJobProcessor.finish
train
@Override public void finish() { if (started.get() && !finished.getAndSet(true)) { waitUntilFinished(); super.finish(); // recreate thread (don't start) for processor reuse createProcessorThread(); clearQueues(); started.set(false); } }
java
{ "resource": "" }
q4290
ReentrantTransactionDispatcher.acquireTransaction
train
int acquireTransaction(@NotNull final Thread thread) { try (CriticalSection ignored = criticalSection.enter()) { final int currentThreadPermits = getThreadPermitsToAcquire(thread); waitForPermits(thread, currentThreadPermits > 0 ? nestedQueue : regularQueue, 1, currentThreadPermits); } return 1; }
java
{ "resource": "" }
q4291
ReentrantTransactionDispatcher.releaseTransaction
train
void releaseTransaction(@NotNull final Thread thread, final int permits) { try (CriticalSection ignored = criticalSection.enter()) { int currentThreadPermits = getThreadPermits(thread); if (permits > currentThreadPermits) { throw new ExodusException("Can't release more permits than it was acquired"); } acquiredPermits -= permits; currentThreadPermits -= permits; if (currentThreadPermits == 0) { threadPermits.remove(thread); } else { threadPermits.put(thread, currentThreadPermits); } notifyNextWaiters(); } }
java
{ "resource": "" }
q4292
ReentrantTransactionDispatcher.tryAcquireExclusiveTransaction
train
private int tryAcquireExclusiveTransaction(@NotNull final Thread thread, final int timeout) { long nanos = TimeUnit.MILLISECONDS.toNanos(timeout); try (CriticalSection ignored = criticalSection.enter()) { if (getThreadPermits(thread) > 0) { throw new ExodusException("Exclusive transaction can't be nested"); } final Condition condition = criticalSection.newCondition(); final long currentOrder = acquireOrder++; regularQueue.put(currentOrder, condition); while (acquiredPermits > 0 || regularQueue.firstKey() != currentOrder) { try { nanos = condition.awaitNanos(nanos); if (nanos < 0) { break; } } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } if (acquiredPermits == 0 && regularQueue.firstKey() == currentOrder) { regularQueue.pollFirstEntry(); acquiredPermits = availablePermits; threadPermits.put(thread, availablePermits); return availablePermits; } regularQueue.remove(currentOrder); notifyNextWaiters(); } return 0; }
java
{ "resource": "" }
q4293
JobProcessorQueueAdapter.waitForJobs
train
protected boolean waitForJobs() throws InterruptedException { final Pair<Long, Job> peekPair; try (Guard ignored = timeQueue.lock()) { peekPair = timeQueue.peekPair(); } if (peekPair == null) { awake.acquire(); return true; } final long timeout = Long.MAX_VALUE - peekPair.getFirst() - System.currentTimeMillis(); if (timeout < 0) { return false; } return awake.tryAcquire(timeout, TimeUnit.MILLISECONDS); }
java
{ "resource": "" }
q4294
PersistentStoreTransaction.apply
train
void apply() { final FlushLog log = new FlushLog(); store.logOperations(txn, log); final BlobVault blobVault = store.getBlobVault(); if (blobVault.requiresTxn()) { try { blobVault.flushBlobs(blobStreams, blobFiles, deferredBlobsToDelete, txn); } catch (Exception e) { // out of disk space not expected there throw ExodusException.toEntityStoreException(e); } } txn.setCommitHook(new Runnable() { @Override public void run() { log.flushed(); final EntityIterableCacheAdapterMutable cache = PersistentStoreTransaction.this.mutableCache; if (cache != null) { // mutableCache can be null if only blobs are modified applyAtomicCaches(cache); } } }); }
java
{ "resource": "" }
q4295
StoreNamingRules.getFQName
train
@NotNull private String getFQName(@NotNull final String localName, Object... params) { final StringBuilder builder = new StringBuilder(); builder.append(storeName); builder.append('.'); builder.append(localName); for (final Object param : params) { builder.append('#'); builder.append(param); } //noinspection ConstantConditions return StringInterner.intern(builder.toString()); }
java
{ "resource": "" }
q4296
UTFUtil.writeUTF
train
public static void writeUTF(@NotNull final OutputStream stream, @NotNull final String str) throws IOException { try (DataOutputStream dataStream = new DataOutputStream(stream)) { int len = str.length(); if (len < SINGLE_UTF_CHUNK_SIZE) { dataStream.writeUTF(str); } else { int startIndex = 0; int endIndex; do { endIndex = startIndex + SINGLE_UTF_CHUNK_SIZE; if (endIndex > len) { endIndex = len; } dataStream.writeUTF(str.substring(startIndex, endIndex)); startIndex += SINGLE_UTF_CHUNK_SIZE; } while (endIndex < len); } } }
java
{ "resource": "" }
q4297
UTFUtil.readUTF
train
@Nullable public static String readUTF(@NotNull final InputStream stream) throws IOException { final DataInputStream dataInput = new DataInputStream(stream); if (stream instanceof ByteArraySizedInputStream) { final ByteArraySizedInputStream sizedStream = (ByteArraySizedInputStream) stream; final int streamSize = sizedStream.size(); if (streamSize >= 2) { sizedStream.mark(Integer.MAX_VALUE); final int utfLen = dataInput.readUnsignedShort(); if (utfLen == streamSize - 2) { boolean isAscii = true; final byte[] bytes = sizedStream.toByteArray(); for (int i = 0; i < utfLen; ++i) { if ((bytes[i + 2] & 0xff) > 127) { isAscii = false; break; } } if (isAscii) { return fromAsciiByteArray(bytes, 2, utfLen); } } sizedStream.reset(); } } try { String result = null; StringBuilder builder = null; for (; ; ) { final String temp; try { temp = dataInput.readUTF(); if (result != null && result.length() == 0 && builder != null && builder.length() == 0 && temp.length() == 0) { break; } } catch (EOFException e) { break; } if (result == null) { result = temp; } else { if (builder == null) { builder = new StringBuilder(); builder.append(result); } builder.append(temp); } } return (builder != null) ? builder.toString() : result; } finally { dataInput.close(); } }
java
{ "resource": "" }
q4298
BasePageMutable.save
train
protected long save() { // save leaf nodes ReclaimFlag flag = saveChildren(); // save self. complementary to {@link load()} final byte type = getType(); final BTreeBase tree = getTree(); final int structureId = tree.structureId; final Log log = tree.log; if (flag == ReclaimFlag.PRESERVE) { // there is a chance to update the flag to RECLAIM if (log.getWrittenHighAddress() % log.getFileLengthBound() == 0) { // page will be exactly on file border flag = ReclaimFlag.RECLAIM; } else { final ByteIterable[] iterables = getByteIterables(flag); long result = log.tryWrite(type, structureId, new CompoundByteIterable(iterables)); if (result < 0) { iterables[0] = CompressedUnsignedLongByteIterable.getIterable( (size << 1) + ReclaimFlag.RECLAIM.value ); result = log.writeContinuously(type, structureId, new CompoundByteIterable(iterables)); if (result < 0) { throw new TooBigLoggableException(); } } return result; } } return log.write(type, structureId, new CompoundByteIterable(getByteIterables(flag))); }
java
{ "resource": "" }
q4299
EnvironmentConfig.setSetting
train
@Override public EnvironmentConfig setSetting(@NotNull final String key, @NotNull final Object value) { return (EnvironmentConfig) super.setSetting(key, value); }
java
{ "resource": "" }