com.sleepycat.je.Cursor Java Examples

The following examples show how to use com.sleepycat.je.Cursor. 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: qpid-broker-j   Author: apache   File: AbstractBDBMessageStore.java    License: Apache License 2.0 6 votes vote down vote up
private void visitMessagesInternal(MessageHandler handler, EnvironmentFacade environmentFacade)
{
    DatabaseEntry key = new DatabaseEntry();
    DatabaseEntry value = new DatabaseEntry();
    MessageMetaDataBinding valueBinding = MessageMetaDataBinding.getInstance();

    try(Cursor cursor = getMessageMetaDataDb().openCursor(null, null))
    {
        while (cursor.getNext(key, value, LockMode.READ_UNCOMMITTED) == OperationStatus.SUCCESS)
        {
            long messageId = LongBinding.entryToLong(key);
            StorableMessageMetaData metaData = valueBinding.entryToObject(value);
            StoredBDBMessage message = createStoredBDBMessage(messageId, metaData, true);
            if (!handler.handle(message))
            {
                break;
            }
        }
    }
    catch (RuntimeException e)
    {
        throw environmentFacade.handleDatabaseException("Cannot visit messages", e);
    }
}
 
Example #2
Source Project: qpid-broker-j   Author: apache   File: UpgradeFrom7To8.java    License: Apache License 2.0 6 votes vote down vote up
private int getConfigVersion(Database configVersionDb)
{
    Cursor cursor = null;
    try
    {
        cursor = configVersionDb.openCursor(null, null);
        DatabaseEntry key = new DatabaseEntry();
        DatabaseEntry value = new DatabaseEntry();
        while (cursor.getNext(key, value, LockMode.RMW) == OperationStatus.SUCCESS)
        {
            return IntegerBinding.entryToInt(value);
        }
        return -1;
    }
    finally
    {
        if (cursor != null)
        {
            cursor.close();
        }
    }
}
 
Example #3
Source Project: qpid-broker-j   Author: apache   File: AbstractBDBPreferenceStore.java    License: Apache License 2.0 6 votes vote down vote up
private Collection<PreferenceRecord> getPreferenceRecords(final EnvironmentFacade environmentFacade)
{
    Collection<PreferenceRecord> records = new LinkedHashSet<>();

    try(Cursor cursor = getPreferencesDb().openCursor(null, null))
    {
        DatabaseEntry key = new DatabaseEntry();
        DatabaseEntry value = new DatabaseEntry();
        UUIDTupleBinding keyBinding = UUIDTupleBinding.getInstance();
        MapBinding valueBinding = MapBinding.getInstance();

        while (cursor.getNext(key, value, LockMode.READ_UNCOMMITTED) == OperationStatus.SUCCESS)
        {
            UUID preferenceId = keyBinding.entryToObject(key);
            Map<String, Object> preferenceAttributes = valueBinding.entryToObject(value);
            PreferenceRecord record = new PreferenceRecordImpl(preferenceId, preferenceAttributes);
            records.add(record);
        }
    }
    catch (RuntimeException e)
    {
        throw environmentFacade.handleDatabaseException("Cannot visit preferences", e);
    }
    return records;
}
 
Example #4
Source Project: qpid-broker-j   Author: apache   File: OrphanConfigurationRecordPurger.java    License: Apache License 2.0 6 votes vote down vote up
private int getVersion(final Environment env, final DatabaseConfig dbConfig)
{
    try (Database versionDb = env.openDatabase(null, VERSION_DB_NAME, dbConfig);
         Cursor cursor = versionDb.openCursor(null, null))
    {
        DatabaseEntry key = new DatabaseEntry();
        DatabaseEntry value = new DatabaseEntry();

        int version = 0;

        while (cursor.getNext(key, value, null) == OperationStatus.SUCCESS)
        {
            int ver = IntegerBinding.entryToInt(key);
            if (ver > version)
            {
                version = ver;
            }
        }

        return version;
    }
}
 
Example #5
Source Project: qpid-broker-j   Author: apache   File: UpgraderFailOnNewerVersionTest.java    License: Apache License 2.0 6 votes vote down vote up
private int getStoreVersion()
{
    DatabaseConfig dbConfig = new DatabaseConfig();
    dbConfig.setTransactional(true);
    dbConfig.setAllowCreate(true);
    int storeVersion = -1;
    try(Database versionDb = _environment.openDatabase(null, Upgrader.VERSION_DB_NAME, dbConfig);
        Cursor cursor = versionDb.openCursor(null, null))
    {
        DatabaseEntry key = new DatabaseEntry();
        DatabaseEntry value = new DatabaseEntry();
        while (cursor.getNext(key, value, null) == OperationStatus.SUCCESS)
        {
            int version = IntegerBinding.entryToInt(key);
            if (storeVersion < version)
            {
                storeVersion = version;
            }
        }
    }
    return storeVersion;
}
 
Example #6
Source Project: qpid-broker-j   Author: apache   File: UpgraderTest.java    License: Apache License 2.0 6 votes vote down vote up
private int getStoreVersion(Environment environment)
{
    DatabaseConfig dbConfig = new DatabaseConfig();
    dbConfig.setTransactional(true);
    dbConfig.setAllowCreate(true);
    int storeVersion = -1;
    try(Database versionDb = environment.openDatabase(null, Upgrader.VERSION_DB_NAME, dbConfig);
        Cursor cursor = versionDb.openCursor(null, null))
    {
        DatabaseEntry key = new DatabaseEntry();
        DatabaseEntry value = new DatabaseEntry();
        while (cursor.getNext(key, value, null) == OperationStatus.SUCCESS)
        {
            int version = IntegerBinding.entryToInt(key);
            if (storeVersion < version)
            {
                storeVersion = version;
            }
        }
    }
    return storeVersion;
}
 
Example #7
Source Project: SPADE   Author: ashish-gehani   File: BerkeleyDB.java    License: GNU General Public License v3.0 6 votes vote down vote up
@VisibleForTesting
public void readData(int limit)
{
    Cursor cursor = scaffoldDatabase.openCursor(null, null);
    DatabaseEntry key = new DatabaseEntry();
    DatabaseEntry data = new DatabaseEntry();
    int i = 0;
    while(cursor.getNext(key, data, LockMode.DEFAULT) == OperationStatus.SUCCESS)
    {
        if(i >= limit)
            break;
        String keyString = new String(key.getData());
        System.out.println("hash: " + keyString);
        i++;
    }
    cursor.close();
}
 
Example #8
Source Project: hypergraphdb   Author: hypergraphdb   File: BerkeleyDBStore.java    License: Apache License 2.0 6 votes vote down vote up
private Set privateLoadAllKeys() {
    Set keys = new java.util.HashSet((int) _db.count());
    Cursor cursor = null;
    try {
        cursor = _db.openCursor(null, null);
        DatabaseEntry foundKey = new DatabaseEntry();
        DatabaseEntry foundData = new DatabaseEntry();

        while (cursor.getNext(foundKey, foundData, LockMode.DEFAULT) == OperationStatus.SUCCESS) {
            keys.add((K) entryToObject(foundKey));
        }
    } catch (Exception e) {
        _logger.log(Level.SEVERE, e.getMessage(), e);
    } finally {
        cursor.close();
    }

    _logger.log(Level.INFO, this.getClass().getCanonicalName() + ":" + _mapName + ":loadAllKeys:" + keys.size());

    return keys;
}
 
Example #9
Source Project: WebCollector   Author: CrawlScript   File: BerkeleyDBManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void list() throws Exception {
        if (env == null) {
            open();
        }
        Cursor cursor = null;
        Database crawldbDatabase = env.openDatabase(null, "crawldb", BerkeleyDBUtils.defaultDBConfig);
        cursor = crawldbDatabase.openCursor(null, CursorConfig.DEFAULT);
        DatabaseEntry key = new DatabaseEntry();
        DatabaseEntry value = new DatabaseEntry();

        while (cursor.getNext(key, value, LockMode.DEFAULT) == OperationStatus.SUCCESS) {
            CrawlDatum datum = BerkeleyDBUtils.createCrawlDatum(key, value);
            System.out.println(CrawlDatumFormater.datumToString(datum));
//            try {
//                CrawlDatum datum = BerkeleyDBUtils.createCrawlDatum(key, value);
//                System.out.println(CrawlDatumFormater.datumToString(datum));
//            } catch (Exception ex) {
//                LOG.info("Exception when generating", ex);
//                continue;
//            }
        }

    }
 
Example #10
Source Project: BIMserver   Author: opensourceBIM   File: BerkeleyKeyValueStore.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<byte[]> getDuplicates(String tableName, byte[] keyBytes, DatabaseSession databaseSession) throws BimserverDatabaseException {
	DatabaseEntry key = new DatabaseEntry(keyBytes);
	DatabaseEntry value = new DatabaseEntry();
	try {
		TableWrapper tableWrapper = getTableWrapper(tableName);
		Cursor cursor = tableWrapper.getDatabase().openCursor(getTransaction(databaseSession, tableWrapper), getCursorConfig(tableWrapper));
		try {
			OperationStatus operationStatus = cursor.getSearchKey(key, value, LockMode.DEFAULT);
			List<byte[]> result = new ArrayList<byte[]>();
			while (operationStatus == OperationStatus.SUCCESS) {
				result.add(value.getData());
				operationStatus = cursor.getNextDup(key, value, LockMode.DEFAULT);
			}
			return result;
		} finally {
			cursor.close();
		}
	} catch (DatabaseException e) {
		LOGGER.error("", e);
	}
	return null;
}
 
Example #11
Source Project: BIMserver   Author: opensourceBIM   File: BerkeleyKeyValueStore.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public RecordIterator getRecordIterator(String tableName, DatabaseSession databaseSession) throws BimserverDatabaseException {
	Cursor cursor = null;
	try {
		TableWrapper tableWrapper = getTableWrapper(tableName);
		cursor = tableWrapper.getDatabase().openCursor(getTransaction(databaseSession, tableWrapper), getCursorConfig(tableWrapper));
		BerkeleyRecordIterator berkeleyRecordIterator = new BerkeleyRecordIterator(cursor, this, cursorCounter.incrementAndGet());
		if (MONITOR_CURSOR_STACK_TRACES) {
			openCursors.put(berkeleyRecordIterator.getCursorId(), new Exception().getStackTrace());
		}
		return berkeleyRecordIterator;
	} catch (DatabaseException e) {
		LOGGER.error("", e);
	}
	return null;
}
 
Example #12
Source Project: timbuctoo   Author: HuygensING   File: BdbWrapper.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void replace(KeyT key, ValueT initialValue, Function<ValueT, ValueT> replacer) throws DatabaseWriteException {
  synchronized (keyEntry) {
    try (Cursor cursor = database.openCursor(transaction, CursorConfig.DEFAULT)) {
      keyBinder.objectToEntry(key, keyEntry);
      OperationStatus searchResult = cursor.getSearchKey(keyEntry, valueEntry, LockMode.DEFAULT);
      ValueT newValue = initialValue;
      if (searchResult.equals(OperationStatus.SUCCESS)) {
        newValue = replacer.apply(valueBinder.entryToObject(valueEntry));
      }
      valueBinder.objectToEntry(newValue, valueEntry);
      cursor.putCurrent(valueEntry);
    } catch (Exception e) {
      throw new DatabaseWriteException(e);
    }
  }
}
 
Example #13
Source Project: timbuctoo   Author: HuygensING   File: BdbWrapper.java    License: GNU General Public License v3.0 6 votes vote down vote up
public boolean put(KeyT key, ValueT value) throws DatabaseWriteException {
  synchronized (keyEntry) {
    try {
      keyBinder.objectToEntry(key, keyEntry);
      if (databaseConfig.getSortedDuplicates()) {
        valueBinder.objectToEntry(value, valueEntry);
        OperationStatus operationStatus = database.putNoDupData(transaction, keyEntry, valueEntry);
        // operation status is only SUCCESS if the data was not in the database before
        return operationStatus.equals(OperationStatus.SUCCESS);
      } else {
        try (Cursor cursor = database.openCursor(transaction, CursorConfig.DEFAULT)) {
          OperationStatus searchResult = cursor.getSearchKey(keyEntry, valueEntry, LockMode.DEFAULT);
          if (searchResult == SUCCESS && Objects.equals(value, valueBinder.entryToObject(valueEntry))) {
            return false;
          } else {
            valueBinder.objectToEntry(value, valueEntry);
            database.put(transaction, keyEntry, valueEntry); // returns OperationStatus.SUCCESS or throws an exception
            return true;
          }
        }
      }
    } catch (Exception e) {
      throw new DatabaseWriteException(e);
    }
  }
}
 
Example #14
Source Project: timbuctoo   Author: HuygensING   File: BdbWrapper.java    License: GNU General Public License v3.0 6 votes vote down vote up
public boolean delete(KeyT key, ValueT value) throws DatabaseWriteException {
  boolean wasChange = false;
  synchronized (keyEntry) {
    try (Cursor cursor = database.openCursor(transaction, CursorConfig.DEFAULT)) {
      keyBinder.objectToEntry(key, keyEntry);
      valueBinder.objectToEntry(value, valueEntry);
      OperationStatus searchResult = cursor.getSearchBoth(keyEntry, valueEntry, LockMode.DEFAULT);
      if (searchResult.equals(OperationStatus.SUCCESS)) {
        wasChange = cursor.delete() == OperationStatus.SUCCESS;
      }
    } catch (Exception e) {
      throw new DatabaseWriteException(e);
    }
  }
  return wasChange;
}
 
Example #15
Source Project: timbuctoo   Author: HuygensING   File: BdbWrapper.java    License: GNU General Public License v3.0 6 votes vote down vote up
public List<String> dump(String prefix, int start, int count, LockMode lockMode) {
  EntryBinding<String> binder = TupleBinding.getPrimitiveBinding(String.class);
  DatabaseEntry key = new DatabaseEntry();
  binder.objectToEntry(prefix, key);
  DatabaseEntry value = new DatabaseEntry();

  Cursor cursor = database.openCursor(null, null);
  OperationStatus status = cursor.getSearchKeyRange(key, value, LockMode.READ_UNCOMMITTED);
  List<String> result = new ArrayList<>();
  int index = 0;
  while (status == OperationStatus.SUCCESS && index < (start + count)) {
    if (index >= start) {
      result.add(
        binder.entryToObject(key) + " -> " + binder.entryToObject(value)
      );
    }
    index++;
    status = cursor.getNext(key, value, LockMode.READ_UNCOMMITTED);
  }
  cursor.close();
  return result;
}
 
Example #16
Source Project: qpid-broker-j   Author: apache   File: BDBLinkStore.java    License: Apache License 2.0 5 votes vote down vote up
private ModelVersion getStoredVersion() throws RuntimeException
{
    try(Cursor cursor = getLinksVersionDb().openCursor(null, null))
    {
        DatabaseEntry key = new DatabaseEntry();
        DatabaseEntry value = new DatabaseEntry();

        ModelVersion storedVersion = null;
        while (cursor.getNext(key, value, LockMode.READ_UNCOMMITTED) == OperationStatus.SUCCESS)
        {
            String versionString = StringBinding.entryToString(key);
            ModelVersion version = ModelVersion.fromString(versionString);
            if (storedVersion == null || storedVersion.lessThan(version))
            {
                storedVersion = version;
            }
        }
        if (storedVersion == null)
        {
            throw new StoreException("No link version information.");
        }
        return storedVersion;
    }
    catch (RuntimeException e)
    {
        throw getEnvironmentFacade().handleDatabaseException("Cannot visit link version", e);
    }
}
 
Example #17
Source Project: qpid-broker-j   Author: apache   File: AbstractBDBMessageStore.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visitDistributedTransactions(final DistributedTransactionHandler handler) throws StoreException
{
    checkMessageStoreOpen();

    try(Cursor cursor = getXidDb().openCursor(null, null))
    {
        CachingUUIDFactory uuidFactory = new CachingUUIDFactory();
        DatabaseEntry key = new DatabaseEntry();
        XidBinding keyBinding = XidBinding.getInstance();
        DatabaseEntry value = new DatabaseEntry();

        while (cursor.getNext(key, value, LockMode.READ_UNCOMMITTED) == OperationStatus.SUCCESS)
        {
            Xid xid = keyBinding.entryToObject(key);
            PreparedTransaction preparedTransaction = PreparedTransactionBinding.entryToObject(uuidFactory, value);
            if (!handler.handle(new BDBStoredXidRecord(xid.getFormat(), xid.getGlobalId(), xid.getBranchId()),
                                preparedTransaction.getEnqueues(), preparedTransaction.getDequeues()))
            {
                break;
            }
        }
    }
    catch (RuntimeException e)
    {
        throw getEnvironmentFacade().handleDatabaseException("Cannot recover distributed transactions", e);
    }
}
 
Example #18
Source Project: qpid-broker-j   Author: apache   File: Upgrader.java    License: Apache License 2.0 5 votes vote down vote up
int getSourceVersion(Database versionDb)
{
    int version = -1;

    Cursor cursor = null;
    try
    {
        cursor = versionDb.openCursor(null, null);

        DatabaseEntry key = new DatabaseEntry();
        DatabaseEntry value = new DatabaseEntry();

        while(cursor.getNext(key, value, null) == OperationStatus.SUCCESS)
        {
            int ver = IntegerBinding.entryToInt(key);
            if(ver > version)
            {
                version = ver;
            }
        }
    }
    finally
    {
        if(cursor != null)
        {
            cursor.close();
        }
    }


    return version;
}
 
Example #19
Source Project: qpid-broker-j   Author: apache   File: UpgradeFrom7To8.java    License: Apache License 2.0 5 votes vote down vote up
private long getMaximumMessageId(Database messageMetaDataDb)
{
    Cursor cursor = null;
    long maximumMessageId = 0;  // Our hand-rolled sequences value always began at zero
    try
    {
        cursor = messageMetaDataDb.openCursor(null, null);
        DatabaseEntry key = new DatabaseEntry();
        DatabaseEntry value = new DatabaseEntry();
        MessageMetaDataBinding valueBinding = MessageMetaDataBinding.getInstance();

        while (cursor.getNext(key, value, LockMode.RMW) == OperationStatus.SUCCESS)
        {
            long messageId = LongBinding.entryToLong(key);
            maximumMessageId = Math.max(messageId, maximumMessageId);
        }
    }
    finally
    {
        if (cursor != null)
        {
            cursor.close();
        }
    }

    return maximumMessageId;
}
 
Example #20
Source Project: qpid-broker-j   Author: apache   File: AbstractBDBPreferenceStore.java    License: Apache License 2.0 5 votes vote down vote up
ModelVersion getStoredVersion()
{
    try(Cursor cursor = getPreferencesVersionDb().openCursor(null, null))
    {
        DatabaseEntry key = new DatabaseEntry();
        DatabaseEntry value = new DatabaseEntry();

        ModelVersion storedVersion = null;
        while (cursor.getNext(key, value, LockMode.READ_UNCOMMITTED) == OperationStatus.SUCCESS)
        {
            String versionString = StringBinding.entryToString(key);
            ModelVersion version = ModelVersion.fromString(versionString);
            if (storedVersion == null || storedVersion.lessThan(version))
            {
                storedVersion = version;
            }
        }
        if (storedVersion == null)
        {
            throw new StoreException("No preference version information.");
        }
        return storedVersion;
    }
    catch (RuntimeException e)
    {
        throw getEnvironmentFacade().handleDatabaseException("Cannot visit preference version", e);
    }
}
 
Example #21
Source Project: qpid-broker-j   Author: apache   File: BDBConfigurationStore.java    License: Apache License 2.0 5 votes vote down vote up
private Collection<? extends ConfiguredObjectRecord> doVisitAllConfiguredObjectRecords()
{
    Map<UUID, BDBConfiguredObjectRecord> configuredObjects = new HashMap<>();
    try(Cursor objectsCursor = getConfiguredObjectsDb().openCursor(null, null))
    {
        DatabaseEntry key = new DatabaseEntry();
        DatabaseEntry value = new DatabaseEntry();


        while (objectsCursor.getNext(key, value, LockMode.READ_UNCOMMITTED) == OperationStatus.SUCCESS)
        {
            UUID id = UUIDTupleBinding.getInstance().entryToObject(key);

            BDBConfiguredObjectRecord configuredObject =
                    (BDBConfiguredObjectRecord) new ConfiguredObjectBinding(id).entryToObject(value);
            configuredObjects.put(configuredObject.getId(), configuredObject);
        }

        // set parents
        try(Cursor hierarchyCursor = getConfiguredObjectHierarchyDb().openCursor(null, null))
        {
            while (hierarchyCursor.getNext(key, value, LockMode.READ_UNCOMMITTED) == OperationStatus.SUCCESS)
            {
                HierarchyKey hk = HierarchyKeyBinding.getInstance().entryToObject(key);
                UUID parentId = UUIDTupleBinding.getInstance().entryToObject(value);
                BDBConfiguredObjectRecord child = configuredObjects.get(hk.getChildId());
                if(child != null)
                {
                    ConfiguredObjectRecord parent = configuredObjects.get(parentId);
                    if(parent != null)
                    {
                        child.addParent(hk.getParentType(), parent);
                    }
                }
            }
        }
    }
    return configuredObjects.values();

}
 
Example #22
Source Project: titan1withtp3.1   Author: graben1437   File: BerkeleyJETx.java    License: Apache License 2.0 5 votes vote down vote up
void registerCursor(Cursor cursor) {
    Preconditions.checkArgument(cursor != null);
    synchronized (openCursors) {
        //TODO: attempt to remove closed cursors if there are too many
        openCursors.add(cursor);
    }
}
 
Example #23
Source Project: hypergraphdb   Author: hypergraphdb   File: DefaultIndexImpl.java    License: Apache License 2.0 5 votes vote down vote up
public void removeEntry(KeyType key, ValueType value)
{
	checkOpen();
	DatabaseEntry keyEntry = new DatabaseEntry(keyConverter.toByteArray(key));
	DatabaseEntry valueEntry = new DatabaseEntry(valueConverter.toByteArray(value));
	Cursor cursor = null;

	try
	{
		cursor = db.openCursor(txn().getBJETransaction(), cursorConfig);
		if (cursor.getSearchBoth(keyEntry, valueEntry, LockMode.DEFAULT) == OperationStatus.SUCCESS)
			cursor.delete();
	}
	catch (Exception ex)
	{
		throw new HGException("Failed to lookup index '" + name + "': " + ex.toString(), ex);
	}
	finally
	{
		if (cursor != null)
		{
			try
			{
				cursor.close();
			}
			catch (Throwable t)
			{
			}
		}
	}
}
 
Example #24
Source Project: hypergraphdb   Author: hypergraphdb   File: DefaultIndexImpl.java    License: Apache License 2.0 5 votes vote down vote up
public ValueType findFirst(KeyType key)
{
	checkOpen();
	DatabaseEntry keyEntry = new DatabaseEntry(keyConverter.toByteArray(key));
	DatabaseEntry value = new DatabaseEntry();
	ValueType result = null;
	Cursor cursor = null;

	try
	{
		cursor = db.openCursor(txn().getBJETransaction(), cursorConfig);
		OperationStatus status = cursor.getSearchKey(keyEntry, value, LockMode.DEFAULT);
		if (status == OperationStatus.SUCCESS)
			result = valueConverter.fromByteArray(value.getData(), value.getOffset(), value.getSize());
	}
	catch (Exception ex)
	{
		throw new HGException("Failed to lookup index '" + name + "': " + ex.toString(), ex);
	}
	finally
	{
		if (cursor != null)
		{
			try
			{
				cursor.close();
			}
			catch (Throwable t)
			{
			}
		}
	}
	return result;
}
 
Example #25
Source Project: hypergraphdb   Author: hypergraphdb   File: DefaultIndexImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Find the last entry, assuming ordered duplicates, corresponding to the
 * given key.
 * </p>
 * 
 * @param key
 *            The key whose last entry is sought.
 * @return The last (i.e. greatest, i.e. maximum) data value for that key or
 *         null if the set of entries for the key is empty.
 */
public ValueType findLast(KeyType key)
{
	checkOpen();
	DatabaseEntry keyEntry = new DatabaseEntry(keyConverter.toByteArray(key));
	DatabaseEntry value = new DatabaseEntry();
	ValueType result = null;
	Cursor cursor = null;
	try
	{
		cursor = db.openCursor(txn().getBJETransaction(), cursorConfig);
		OperationStatus status = cursor.getLast(keyEntry, value, LockMode.DEFAULT);
		if (status == OperationStatus.SUCCESS)
			result = valueConverter.fromByteArray(value.getData(), value.getOffset(), value.getSize());
	}
	catch (Exception ex)
	{
		throw new HGException("Failed to lookup index '" + name + "': " + ex.toString(), ex);
	}
	finally
	{
		if (cursor != null)
		{
			try
			{
				cursor.close();
			}
			catch (Throwable t)
			{
			}
		}
	}
	return result;
}
 
Example #26
Source Project: hypergraphdb   Author: hypergraphdb   File: DefaultIndexImpl.java    License: Apache License 2.0 5 votes vote down vote up
public long count(KeyType key)
{
	Cursor cursor = null;
	try
	{
		cursor = db.openCursor(txn().getBJETransaction(), cursorConfig);
		DatabaseEntry keyEntry = new DatabaseEntry(keyConverter.toByteArray(key));
		DatabaseEntry value = new DatabaseEntry();
		OperationStatus status = cursor.getSearchKey(keyEntry, value, LockMode.DEFAULT);

		if (status == OperationStatus.SUCCESS)
			return cursor.count();
		else
			return 0;
	}
	catch (DatabaseException ex)
	{
		throw new HGException(ex);
	}
	finally
	{
		if (cursor != null)
		{
			try
			{
				cursor.close();
			}
			catch (Throwable t)
			{
			}
		}
	}
}
 
Example #27
Source Project: hypergraphdb   Author: hypergraphdb   File: BJEIndexStats.java    License: Apache License 2.0 5 votes vote down vote up
public Count valuesOfKey(final Key key, final long cost, final boolean isEstimateOk)
{
	index.checkOpen();
	if (cost == 0)
		return null;
	else
	{
		Ref<Long> counter = new Ref<Long>() {
		public Long get() {
			try (Cursor cursor = index.db.openCursor(index.txn().getBJETransaction(), index.cursorConfig)) 
			{
				DatabaseEntry keyEntry = new DatabaseEntry(index.keyConverter.toByteArray(key));
				DatabaseEntry value = new DatabaseEntry();
				OperationStatus status = cursor.getSearchKey(keyEntry, value, LockMode.DEFAULT);

				if (status == OperationStatus.SUCCESS)
					return (long)cursor.count();
				else
					return 0l;
			}
			catch (DatabaseException ex)
			{
				throw new HGException(ex);
			}
		}};
		return new Count(counter, false);
	}		
}
 
Example #28
Source Project: hypergraphdb   Author: hypergraphdb   File: TransactionBJEImpl.java    License: Apache License 2.0 5 votes vote down vote up
public BJETxCursor attachCursor(Cursor cursor)
	{
//		if (t != null && traceme)
//			System.err.println("Adding cursor to tx " + t.getId());
		if (t == null)
		{
			return new BJETxCursor(cursor, null);
		}
		BJETxCursor c = new BJETxCursor(cursor, this);
		bdbCursors.add(c);
		return c;
	}
 
Example #29
Source Project: hypergraphdb   Author: hypergraphdb   File: BJEStorageImplementation.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public HGRandomAccessResult<HGPersistentHandle> getIncidenceResultSet(HGPersistentHandle handle)
{
	if (handle == null)
		throw new NullPointerException("HGStore.getIncidenceSet called with a null handle.");

	Cursor cursor = null;
	try
	{
		DatabaseEntry key = new DatabaseEntry(handle.toByteArray());
		DatabaseEntry value = new DatabaseEntry();
		TransactionBJEImpl tx = txn();
		cursor = incidence_db.openCursor(tx.getBJETransaction(), cursorConfig);
		OperationStatus status = cursor.getSearchKey(key, value, LockMode.DEFAULT);
		if (status == OperationStatus.NOTFOUND)
		{
			cursor.close();
			return (HGRandomAccessResult<HGPersistentHandle>) HGSearchResult.EMPTY;
		}
		else
			return new SingleKeyResultSet<HGPersistentHandle>(tx.attachCursor(cursor), key,
					BAtoHandle.getInstance(handleFactory));
	}
	catch (Throwable ex)
	{
		if (cursor != null)
			try
			{
				cursor.close();
			}
			catch (Throwable t)
			{
			}
		throw new HGException("Failed to retrieve incidence set for handle " + handle + ": " + ex.toString(), ex);
	}
}
 
Example #30
Source Project: hypergraphdb   Author: hypergraphdb   File: BJEStorageImplementation.java    License: Apache License 2.0 5 votes vote down vote up
public long getIncidenceSetCardinality(HGPersistentHandle handle)
{
	if (handle == null)
		throw new NullPointerException("HGStore.getIncidenceSetCardinality called with a null handle.");

	Cursor cursor = null;
	try
	{
		DatabaseEntry key = new DatabaseEntry(handle.toByteArray());
		DatabaseEntry value = new DatabaseEntry();
		cursor = incidence_db.openCursor(txn().getBJETransaction(), cursorConfig);
		OperationStatus status = cursor.getSearchKey(key, value, LockMode.DEFAULT);
		if (status == OperationStatus.NOTFOUND)
			return 0;
		else
			return cursor.count();
	}
	catch (Exception ex)
	{
		throw new HGException("Failed to retrieve incidence set for handle " + handle + ": " + ex.toString(), ex);
	}
	finally
	{
		try
		{
			cursor.close();
		}
		catch (Throwable t)
		{
		}
	}
}