Java Code Examples for com.sleepycat.je.Transaction

The following examples show how to use com.sleepycat.je.Transaction. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: bboxdb   Author: jnidzwetzki   File: BDBTupleStore.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void writeTuple(final Tuple tuple) throws IOException {
	Transaction txn = null;
	
	if(USE_TRANSACTIONS) {
		txn = environment.beginTransaction(null, null);
	}
	
	final byte[] tupleBytes = TupleHelper.tupleToBytes(tuple);
	final DatabaseEntry key = new DatabaseEntry(tuple.getKey().getBytes());
	final DatabaseEntry value = new DatabaseEntry(tupleBytes);
	final OperationStatus status = database.put(txn, key, value);

       if (status != OperationStatus.SUCCESS) {
           throw new RuntimeException("Data insertion got status " + status);
       }
       
       if(txn != null) {
       	txn.commit();
       }
}
 
Example #2
Source Project: qpid-broker-j   Author: apache   File: UpgradeFrom5To6Test.java    License: Apache License 2.0 6 votes vote down vote up
private void assertQueueEntries()
{
    final Map<UUID, UpgradeConfiguredObjectRecord> configuredObjects = loadConfiguredObjects();
    final NewQueueEntryBinding newBinding = new NewQueueEntryBinding();
    CursorOperation cursorOperation = new CursorOperation()
    {

        @Override
        public void processEntry(Database sourceDatabase, Database targetDatabase, Transaction transaction,
                DatabaseEntry key, DatabaseEntry value)
        {
            NewQueueEntryKey newEntryRecord = newBinding.entryToObject(key);
            assertTrue("Unexpected queue id", configuredObjects.containsKey(newEntryRecord.getQueueId()));
        }
    };
    new DatabaseTemplate(_environment, NEW_DELIVERY_DB_NAME, null).run(cursorOperation);
}
 
Example #3
Source Project: jstarcraft-core   Author: HongZhaoHua   File: BerkeleyManager.java    License: Apache License 2.0 6 votes vote down vote up
public List<T> queryIntersection(BerkeleyTransactor transactor, Map<String, Object> condition, StoragePagination pagination) {
	Transaction transaction = transactor == null ? null : transactor.getTransaction();
	EntityJoin<K, T> join = new EntityJoin<K, T>(primaryIndex);
	for (Entry<String, Object> keyValue : condition.entrySet()) {
		SecondaryIndex<Object, K, T> secondaryIndex = secondaryIndexes.get(keyValue.getKey());
		join.addCondition(secondaryIndex, keyValue.getValue());
	}
	ArrayList<T> instances = new ArrayList<>();
	long ignore = pagination.getFirst();
	long size = pagination.getSize();
	try (ForwardCursor<T> cursor = join.entities(transaction, transactor.getIsolation().getCursorModel())) {
		if (ignore == 0) {
			collect(instances, cursor, size);
		}
		return instances;
	}
}
 
Example #4
Source Project: jstarcraft-core   Author: HongZhaoHua   File: BerkeleyManager.java    License: Apache License 2.0 6 votes vote down vote up
public List<T> queryUnion(BerkeleyTransactor transactor, Map<String, Object> condition, StoragePagination pagination) {
	Transaction transaction = transactor == null ? null : transactor.getTransaction();
	long ignore = pagination.getFirst();
	long size = pagination.getSize();
	ArrayList<T> instances = new ArrayList<>();
	// TODO 应该考虑实例重复计算的情况.
	for (Entry<String, Object> keyValue : condition.entrySet()) {
		SecondaryIndex<Object, K, T> secondaryIndex = secondaryIndexes.get(keyValue.getKey());
		try (ForwardCursor<T> cursor = secondaryIndex.subIndex(keyValue.getValue()).entities(transaction, transactor.getIsolation().getCursorModel())) {
			if (ignore > 0) {
				ignore -= ignore(cursor, ignore);
			}
			if (ignore == 0) {
				if (size > instances.size()) {
					collect(instances, cursor, size - instances.size());
				}
				if (size == instances.size()) {
					break;
				}
			}
		}
	}
	return instances;
}
 
Example #5
Source Project: jstarcraft-core   Author: HongZhaoHua   File: BerkeleyManager.java    License: Apache License 2.0 6 votes vote down vote up
public void iterateInstances(StorageIterator<T> iterator, BerkeleyTransactor transactor, StoragePagination pagination) {
	Transaction transaction = transactor == null ? null : transactor.getTransaction();
	long first = pagination.getFirst();
	long last = pagination.getLast();
	long count = 0;
	try (ForwardCursor<T> cursor = primaryIndex.entities(transaction, transactor.getIsolation().getCursorModel())) {
		T element;
		while ((element = cursor.next()) != null) {
			if (count >= first && count < last) {
				iterator.iterate(element);
			}
			count++;
			if (count == last) {
				break;
			}
		}
	}
}
 
Example #6
Source Project: jstarcraft-core   Author: HongZhaoHua   File: BerkeleyManager.java    License: Apache License 2.0 6 votes vote down vote up
public void iterateIntersection(StorageIterator<T> iterator, BerkeleyTransactor transactor, Map<String, Object> condition, StoragePagination pagination) {
	Transaction transaction = transactor == null ? null : transactor.getTransaction();
	EntityJoin<K, T> join = new EntityJoin<K, T>(primaryIndex);
	for (Entry<String, Object> keyValue : condition.entrySet()) {
		SecondaryIndex<Object, K, T> secondaryIndex = secondaryIndexes.get(keyValue.getKey());
		join.addCondition(secondaryIndex, keyValue.getValue());
	}
	long first = pagination.getFirst();
	long last = pagination.getLast();
	long count = 0;
	try (ForwardCursor<T> cursor = join.entities(transaction, transactor.getIsolation().getCursorModel())) {
		T element;
		while ((element = cursor.next()) != null) {
			if (count >= first && count < last) {
				iterator.iterate(element);
			}
			count++;
			if (count == last) {
				break;
			}
		}
	}
}
 
Example #7
Source Project: jstarcraft-core   Author: HongZhaoHua   File: BerkeleyManager.java    License: Apache License 2.0 6 votes vote down vote up
public void iterateUnion(StorageIterator<T> iterator, BerkeleyTransactor transactor, Map<String, Object> condition, StoragePagination pagination) {
	Transaction transaction = transactor == null ? null : transactor.getTransaction();
	long first = pagination.getFirst();
	long last = pagination.getLast();
	long count = 0;
	// TODO 应该考虑实例重复计算的情况.
	for (Entry<String, Object> keyValue : condition.entrySet()) {
		SecondaryIndex<Object, K, T> secondaryIndex = secondaryIndexes.get(keyValue.getKey());
		try (ForwardCursor<T> cursor = secondaryIndex.subIndex(keyValue.getValue()).entities(transaction, transactor.getIsolation().getCursorModel())) {
			T element;
			while ((element = cursor.next()) != null) {
				if (count >= first && count < last) {
					iterator.iterate(element);
				}
				count++;
				if (count == last) {
					break;
				}
			}
		}
		if (count == last) {
			break;
		}
	}
}
 
Example #8
Source Project: qpid-broker-j   Author: apache   File: UpgradeFrom5To6Test.java    License: Apache License 2.0 6 votes vote down vote up
private Map<UUID, UpgradeConfiguredObjectRecord> loadConfiguredObjects()
{
    final Map<UUID, UpgradeConfiguredObjectRecord> configuredObjectsRecords = new HashMap<UUID, UpgradeConfiguredObjectRecord>();
    final ConfiguredObjectBinding binding = new ConfiguredObjectBinding();
    final UpgradeUUIDBinding uuidBinding = new UpgradeUUIDBinding();
    CursorOperation configuredObjectsCursor = new CursorOperation()
    {
        @Override
        public void processEntry(Database sourceDatabase, Database targetDatabase, Transaction transaction,
                DatabaseEntry key, DatabaseEntry value)
        {
            UUID id = uuidBinding.entryToObject(key);
            UpgradeConfiguredObjectRecord object = binding.entryToObject(value);
            configuredObjectsRecords.put(id, object);
        }
    };
    new DatabaseTemplate(_environment, CONFIGURED_OBJECTS_DB_NAME, null).run(configuredObjectsCursor);
    return configuredObjectsRecords;
}
 
Example #9
Source Project: qpid-broker-j   Author: apache   File: UpgradeFrom4to5Test.java    License: Apache License 2.0 6 votes vote down vote up
private void assertMetadataForQueue(final String queueName, final int expectedQueueSize,
        final Set<Long> messageIdsForQueue)
{
    final AtomicInteger metadataCounter = new AtomicInteger();
    CursorOperation databaseOperation = new CursorOperation()
    {

        @Override
        public void processEntry(Database sourceDatabase, Database targetDatabase, Transaction transaction,
                DatabaseEntry key, DatabaseEntry value)
        {
            Long messageId = LongBinding.entryToLong(key);

            boolean messageIsForTheRightQueue = messageIdsForQueue.contains(messageId);
            if (messageIsForTheRightQueue)
            {
                metadataCounter.incrementAndGet();
            }
        }
    };
    new DatabaseTemplate(_environment, MESSAGE_META_DATA_DB_NAME, null).run(databaseOperation);

    assertEquals("Unxpected number of entries in metadata db for queue " + queueName, expectedQueueSize,
            metadataCounter.get());
}
 
Example #10
Source Project: qpid-broker-j   Author: apache   File: AbstractBDBMessageStore.java    License: Apache License 2.0 6 votes vote down vote up
synchronized void flushToStore()
{
    if (_messageDataRef != null)
    {
        if (!stored())
        {
            checkMessageStoreOpen();

            Transaction txn;
            try
            {
                txn = getEnvironmentFacade().beginTransaction(null);
            }
            catch (RuntimeException e)
            {
                throw getEnvironmentFacade().handleDatabaseException("failed to begin transaction", e);
            }
            store(txn);
            getEnvironmentFacade().commit(txn, false);

        }
    }
}
 
Example #11
Source Project: qpid-broker-j   Author: apache   File: UpgradeFrom7To8.java    License: Apache License 2.0 6 votes vote down vote up
private void storeConfiguredObjectEntry(Database configuredObjectsDb, final Transaction txn, ConfiguredObjectRecord configuredObject)
{
    DatabaseEntry key = new DatabaseEntry();
    UUIDTupleBinding uuidBinding = UUIDTupleBinding.getInstance();
    uuidBinding.objectToEntry(configuredObject.getId(), key);

    DatabaseEntry value = new DatabaseEntry();
    ConfiguredObjectBinding configuredObjectBinding = ConfiguredObjectBinding.getInstance();

    configuredObjectBinding.objectToEntry(configuredObject, value);
    OperationStatus status = configuredObjectsDb.put(txn, key, value);
    if (status != OperationStatus.SUCCESS)
    {
        throw new StoreException("Error writing configured object " + configuredObject + " to database: "
                + status);
    }
}
 
Example #12
Source Project: qpid-broker-j   Author: apache   File: DatabaseTemplateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteWithTwoDatabases()
{
    String targetDatabaseName = "targetDatabase";
    Database targetDatabase = mock(Database.class);

    Transaction txn = mock(Transaction.class);

    when(_environment.openDatabase(same(txn), same(targetDatabaseName), isA(DatabaseConfig.class)))
            .thenReturn(targetDatabase);

    DatabaseTemplate databaseTemplate = new DatabaseTemplate(_environment, SOURCE_DATABASE, targetDatabaseName, txn);

    DatabaseRunnable databaseOperation = mock(DatabaseRunnable.class);
    databaseTemplate.run(databaseOperation);

    verify(databaseOperation).run(_sourceDatabase, targetDatabase, txn);
    verify(_sourceDatabase).close();
    verify(targetDatabase).close();
}
 
Example #13
Source Project: bboxdb   Author: jnidzwetzki   File: BDBTupleStore.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Tuple readTuple(final String key) throws IOException {
	final DatabaseEntry keyEntry = new DatabaseEntry(key.getBytes());
    final DatabaseEntry value = new DatabaseEntry();
    
	Transaction txn = null;

	if(USE_TRANSACTIONS) {
		txn = environment.beginTransaction(null, null);
	}
	
    final OperationStatus result = database.get(null, keyEntry, value, LockMode.DEFAULT);
    
    if (result != OperationStatus.SUCCESS) {
        throw new RuntimeException("Data fetch got status " + result + " for " + key);
    }
    
       if(txn != null) {
       	txn.commit();
       }
       
       final ByteBuffer byteBuffer = ByteBuffer.wrap(value.getData());
       
       return TupleHelper.decodeTuple(byteBuffer);
}
 
Example #14
Source Project: qpid-broker-j   Author: apache   File: UpgradeFrom4To5.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void performUpgrade(final Environment environment, final UpgradeInteractionHandler handler, ConfiguredObject<?> parent)
{
    Transaction transaction = null;
    reportStarting(environment, 4);

    transaction = environment.beginTransaction(null, null);

    // find all queues which are bound to a topic exchange and which have a colon in their name
    final List<AMQShortString> potentialDurableSubs = findPotentialDurableSubscriptions(environment, transaction);

    Set<String> existingQueues = upgradeQueues(environment, handler, potentialDurableSubs, transaction);
    upgradeQueueBindings(environment, handler, potentialDurableSubs, transaction);
    Set<Long> messagesToDiscard = upgradeDelivery(environment, existingQueues, handler, transaction);
    upgradeContent(environment, handler, messagesToDiscard, transaction);
    upgradeMetaData(environment, handler, messagesToDiscard, transaction);
    renameRemainingDatabases(environment, handler, transaction);
    transaction.commit();

    reportFinished(environment, 5);
}
 
Example #15
Source Project: qpid-broker-j   Author: apache   File: UpgradeFrom4To5.java    License: Apache License 2.0 6 votes vote down vote up
private List<AMQShortString> findTopicExchanges(final Environment environment)
{
    final List<AMQShortString> topicExchanges = new ArrayList<AMQShortString>();
    final ExchangeRecordBinding binding = new ExchangeRecordBinding();
    CursorOperation databaseOperation = new CursorOperation()
    {

        @Override
        public void processEntry(Database sourceDatabase, Database targetDatabase, Transaction transaction,
                DatabaseEntry key, DatabaseEntry value)
        {
            ExchangeRecord record = binding.entryToObject(value);
            if (AMQShortString.valueOf(ExchangeDefaults.TOPIC_EXCHANGE_CLASS).equals(record.getType()))
            {
                topicExchanges.add(record.getName());
            }
        }
    };
    new DatabaseTemplate(environment, EXCHANGE_DB_NAME, null).run(databaseOperation);
    return topicExchanges;
}
 
Example #16
Source Project: qpid-broker-j   Author: apache   File: UpgraderTest.java    License: Apache License 2.0 6 votes vote down vote up
private void assertContent()
{
    final ByteBufferBinding contentBinding = ByteBufferBinding.getInstance();
    CursorOperation contentCursorOperation = new CursorOperation()
    {

        @Override
        public void processEntry(Database sourceDatabase, Database targetDatabase, Transaction transaction, DatabaseEntry key,
                DatabaseEntry value)
        {
            long id = LongBinding.entryToLong(key);
            assertTrue("Unexpected id", id > 0);
            QpidByteBuffer content = contentBinding.entryToObject(value);
            assertNotNull("Unexpected content", content);
            assertTrue("Expected content", content.hasRemaining());
        }
    };
    new DatabaseTemplate(_environment, "MESSAGE_CONTENT", null).run(contentCursorOperation);
}
 
Example #17
Source Project: qpid-broker-j   Author: apache   File: StandardEnvironmentFacade.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <X> ListenableFuture<X> commitAsync(final Transaction tx, final X val)
{
    try
    {
        tx.commitNoSync();
    }
    catch (DatabaseException de)
    {
        LOGGER.error("Got DatabaseException on commit, closing environment", de);

        closeEnvironmentSafely();

        throw handleDatabaseException("Got DatabaseException on commit", de);
    }
    return _committer.commitAsync(tx, val);
}
 
Example #18
Source Project: qpid-broker-j   Author: apache   File: UpgradeFrom7To8Test.java    License: Apache License 2.0 6 votes vote down vote up
private Map<UUID, UpgradeConfiguredObjectRecord> loadConfiguredObjects()
{
    final Map<UUID, UpgradeConfiguredObjectRecord> configuredObjectsRecords = new HashMap<UUID, UpgradeConfiguredObjectRecord>();
    final UpgradeConfiguredObjectBinding binding = new UpgradeConfiguredObjectBinding();
    final UpgradeUUIDBinding uuidBinding = new UpgradeUUIDBinding();
    CursorOperation configuredObjectsCursor = new CursorOperation()
    {
        @Override
        public void processEntry(Database sourceDatabase, Database targetDatabase, Transaction transaction,
                DatabaseEntry key, DatabaseEntry value)
        {
            UUID id = uuidBinding.entryToObject(key);
            UpgradeConfiguredObjectRecord object = binding.entryToObject(value);
            configuredObjectsRecords.put(id, object);
        }
    };
    new DatabaseTemplate(_environment, CONFIGURED_OBJECTS_DB_NAME, null).run(configuredObjectsCursor);
    return configuredObjectsRecords;
}
 
Example #19
Source Project: qpid-broker-j   Author: apache   File: AbstractBDBPreferenceStore.java    License: Apache License 2.0 6 votes vote down vote up
private void updateOrCreateInternal(final Transaction txn,
                                    final Collection<PreferenceRecord> preferenceRecords)
{
    Database preferencesDb = getPreferencesDb();
    DatabaseEntry key = new DatabaseEntry();
    DatabaseEntry value = new DatabaseEntry();
    UUIDTupleBinding keyBinding = UUIDTupleBinding.getInstance();
    MapBinding valueBinding = MapBinding.getInstance();
    for (PreferenceRecord record : preferenceRecords)
    {
        keyBinding.objectToEntry(record.getId(), key);
        valueBinding.objectToEntry(record.getAttributes(), value);
        OperationStatus status = preferencesDb.put(txn, key, value);
        if (status != OperationStatus.SUCCESS)
        {
            throw new StoreException(String.format("Error writing preference with id '%s' (status %s)",
                                                   record.getId(),
                                                   status.name()));
        }
    }
}
 
Example #20
Source Project: qpid-broker-j   Author: apache   File: UpgradeFrom5To6Test.java    License: Apache License 2.0 6 votes vote down vote up
private void assertContent()
{
    final NewDataBinding contentBinding = new NewDataBinding();
    CursorOperation contentCursorOperation = new CursorOperation()
    {

        @Override
        public void processEntry(Database sourceDatabase, Database targetDatabase, Transaction transaction,
                DatabaseEntry key, DatabaseEntry value)
        {
            long id = LongBinding.entryToLong(key);
            assertTrue("Unexpected id", id > 0);
            byte[] content = contentBinding.entryToObject(value);
            assertNotNull("Unexpected content", content);
        }
    };
    new DatabaseTemplate(_environment, NEW_CONTENT_DB_NAME, null).run(contentCursorOperation);
}
 
Example #21
Source Project: qpid-broker-j   Author: apache   File: UpgradeFrom8To9Test.java    License: Apache License 2.0 6 votes vote down vote up
private List<String> loadVersions()
{
    final List<String> versions = new ArrayList<>();
    CursorOperation configuredObjectsCursor = new CursorOperation()
    {
        @Override
        public void processEntry(Database sourceDatabase, Database targetDatabase, Transaction transaction,
                                 DatabaseEntry key, DatabaseEntry value)
        {
            String version = StringBinding.entryToString(key);
            versions.add(version);
        }
    };
    new DatabaseTemplate(_environment, PREFERENCES_VERSION_DB_NAME, null).run(configuredObjectsCursor);
    return versions;
}
 
Example #22
Source Project: qpid-broker-j   Author: apache   File: ReplicatedEnvironmentFacadeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBeginTransaction() throws Exception
{
    ReplicatedEnvironmentFacade facade = createMaster();
    Transaction txn = null;
    try
    {
        TransactionConfig transactionConfig = new TransactionConfig();
        transactionConfig.setDurability(facade.getRealMessageStoreDurability());
        txn = facade.beginTransaction(transactionConfig);
        assertNotNull("Transaction is not created", txn);
        txn.commit();
        txn = null;
    }
    finally
    {
        if (txn != null)
        {
            txn.abort();
        }
    }
}
 
Example #23
Source Project: qpid-broker-j   Author: apache   File: BDBConfigurationStore.java    License: Apache License 2.0 6 votes vote down vote up
private void writeHierarchyRecords(final Transaction txn, final ConfiguredObjectRecord configuredObject)
{
    OperationStatus status;
    HierarchyKeyBinding hierarchyBinding = HierarchyKeyBinding.getInstance();
    DatabaseEntry hierarchyKey = new DatabaseEntry();
    DatabaseEntry hierarchyValue = new DatabaseEntry();

    for(Map.Entry<String, UUID> parent : configuredObject.getParents().entrySet())
    {

        hierarchyBinding.objectToEntry(new HierarchyKey(configuredObject.getId(), parent.getKey()), hierarchyKey);
        UUIDTupleBinding.getInstance().objectToEntry(parent.getValue(), hierarchyValue);
        status = getConfiguredObjectHierarchyDb().put(txn, hierarchyKey, hierarchyValue);
        if (status != OperationStatus.SUCCESS)
        {
            throw new StoreException("Error writing configured object " + configuredObject + " parent record to database: "
                                     + status);
        }
    }
}
 
Example #24
Source Project: qpid-broker-j   Author: apache   File: UpgradeFrom4to5Test.java    License: Apache License 2.0 6 votes vote down vote up
private void assertQueues(Set<String> expectedQueueNames)
{
    List<AMQShortString> durableSubNames = Collections.emptyList();
    final UpgradeFrom4To5.QueueRecordBinding binding = new UpgradeFrom4To5.QueueRecordBinding(durableSubNames);
    final Set<String> actualQueueNames = new HashSet<String>();

    CursorOperation queueNameCollector = new CursorOperation()
    {

        @Override
        public void processEntry(Database sourceDatabase, Database targetDatabase, Transaction transaction,
                DatabaseEntry key, DatabaseEntry value)
        {
            QueueRecord record = binding.entryToObject(value);
            String queueName = record.getNameShortString().toString();
            actualQueueNames.add(queueName);
        }
    };
    new DatabaseTemplate(_environment, "queueDb_v5", null).run(queueNameCollector);

    assertEquals("Unexpected queue names", expectedQueueNames, actualQueueNames);
}
 
Example #25
Source Project: jstarcraft-core   Author: HongZhaoHua   File: BerkeleyManager.java    License: Apache License 2.0 5 votes vote down vote up
public boolean createInstance(BerkeleyTransactor transactor, T instance) {
	Transaction transaction = transactor == null ? null : transactor.getTransaction();
	if (primaryIndex.putNoOverwrite(transaction, instance)) {
		return true;
	} else {
		String message = StringUtility.format("创建的实例[{}:{}]已存在", metadata.getOrmName(), instance.getId());
		if (logger.isDebugEnabled()) {
			logger.debug(message);
		}
		return false;
	}
}
 
Example #26
Source Project: jstarcraft-core   Author: HongZhaoHua   File: BerkeleyManager.java    License: Apache License 2.0 5 votes vote down vote up
public boolean updateInstance(BerkeleyTransactor transactor, T instance) {
	Transaction transaction = transactor == null ? null : transactor.getTransaction();
	if (primaryIndex.put(transaction, instance) != null) {
		return true;
	} else {
		// TODO 删除保存的实例
		deleteInstance(transactor, instance.getId());
		String message = StringUtility.format("修改的实例[{}:{}]不存在", metadata.getOrmName(), instance.getId());
		if (logger.isDebugEnabled()) {
			logger.debug(message);
		}
		return false;
	}
}
 
Example #27
Source Project: jstarcraft-core   Author: HongZhaoHua   File: BerkeleyManager.java    License: Apache License 2.0 5 votes vote down vote up
public K maximumIdentity(BerkeleyTransactor transactor, K from, K to) {
	CursorConfig cursorModel = transactor == null ? null : transactor.getIsolation().getCursorModel();
	Transaction transaction = transactor == null ? null : transactor.getTransaction();
	try (EntityCursor<K> cursor = primaryIndex.keys(transaction, from, true, to, false, cursorModel)) {
		return cursor.last();
	}
}
 
Example #28
Source Project: jstarcraft-core   Author: HongZhaoHua   File: BerkeleyManager.java    License: Apache License 2.0 5 votes vote down vote up
public K minimumIdentity(BerkeleyTransactor transactor, K from, K to) {
	CursorConfig cursorModel = transactor == null ? null : transactor.getIsolation().getCursorModel();
	Transaction transaction = transactor == null ? null : transactor.getTransaction();
	try (EntityCursor<K> cursor = primaryIndex.keys(transaction, from, true, to, false, cursorModel)) {
		return cursor.first();
	}
}
 
Example #29
Source Project: jstarcraft-core   Author: HongZhaoHua   File: BerkeleyManager.java    License: Apache License 2.0 5 votes vote down vote up
public List<T> queryInstances(BerkeleyTransactor transactor, StoragePagination pagination) {
	Transaction transaction = transactor == null ? null : transactor.getTransaction();
	ArrayList<T> instances = new ArrayList<>();
	long ignore = pagination.getFirst();
	long size = pagination.getSize();
	try (EntityCursor<T> cursor = primaryIndex.entities(transaction, transactor.getIsolation().getCursorModel())) {
		ignore -= ignore(cursor, ignore);
		if (ignore == 0) {
			collect(instances, cursor, size);
		}
		return instances;
	}
}
 
Example #30
Source Project: jstarcraft-core   Author: HongZhaoHua   File: BerkeleyManager.java    License: Apache License 2.0 5 votes vote down vote up
public long countIntersection(BerkeleyTransactor transactor, Map<String, Object> condition) {
	Transaction transaction = transactor == null ? null : transactor.getTransaction();
	EntityJoin<K, T> join = new EntityJoin<K, T>(primaryIndex);
	for (Entry<String, Object> keyValue : condition.entrySet()) {
		SecondaryIndex<Object, K, T> secondaryIndex = secondaryIndexes.get(keyValue.getKey());
		join.addCondition(secondaryIndex, keyValue.getValue());
	}
	try (ForwardCursor<K> cursor = join.keys(transaction, transactor.getIsolation().getCursorModel())) {
		return count(cursor);
	}
}