示例#1
0
文件: Store.java 项目: nologic/nabs
  public synchronized void closeClass(Class entityClass) throws DatabaseException {

    checkOpen();
    String clsName = entityClass.getName();
    EntityMetadata entityMeta = checkEntityClass(clsName);

    PrimaryIndex priIndex = priIndexMap.get(clsName);
    if (priIndex != null) {
      /* Close the secondaries first. */
      DatabaseException firstException = null;
      for (SecondaryKeyMetadata keyMeta : entityMeta.getSecondaryKeys().values()) {

        String secName = makeSecName(clsName, keyMeta.getKeyName());
        SecondaryIndex secIndex = secIndexMap.get(secName);
        if (secIndex != null) {
          Database db = secIndex.getDatabase();
          firstException = closeDb(db, firstException);
          firstException = closeDb(secIndex.getKeysDatabase(), firstException);
          secIndexMap.remove(secName);
          deferredWriteDatabases.remove(db);
        }
      }
      /* Close the primary last. */
      Database db = priIndex.getDatabase();
      firstException = closeDb(db, firstException);
      priIndexMap.remove(clsName);
      deferredWriteDatabases.remove(db);

      /* Throw the first exception encountered. */
      if (firstException != null) {
        throw firstException;
      }
    }
  }
示例#2
0
  /**
   * Checks that we get an appropriate exception when storing an entity subclass instance, which
   * contains a secondary key, without registering the subclass up front. [#16399]
   */
  public void testPutEntitySubclassWithoutRegisterClass() throws DatabaseException {

    open();

    final PrimaryIndex<Long, Statement> pri = store.getPrimaryIndex(Long.class, Statement.class);

    final Transaction txn = txnBegin();
    pri.put(txn, new Statement(1));
    try {
      pri.put(txn, new ExtendedStatement(2, null));
      fail();
    } catch (IllegalArgumentException expected) {
      assertTrue(
          expected.toString(),
          expected
              .getMessage()
              .contains(
                  "Entity subclasses defining a secondary key must be "
                      + "registered by calling EntityModel.registerClass or "
                      + "EntityStore.getSubclassIndex before storing an instance "
                      + "of the subclass: "
                      + ExtendedStatement.class.getName()));
    }
    txnAbort(txn);

    close();
  }
示例#3
0
  public void testCursorCount() throws DatabaseException {

    open();

    PrimaryIndex<Integer, MyEntity> priIndex = store.getPrimaryIndex(Integer.class, MyEntity.class);

    SecondaryIndex<Integer, Integer, MyEntity> secIndex =
        store.getSecondaryIndex(priIndex, Integer.class, "secKey");

    Transaction txn = txnBeginCursor();

    MyEntity e = new MyEntity();
    e.priKey = 1;
    e.secKey = 1;
    priIndex.put(txn, e);

    EntityCursor<MyEntity> cursor = secIndex.entities(txn, null);
    cursor.next();
    assertEquals(1, cursor.count());
    cursor.close();

    e.priKey = 2;
    priIndex.put(txn, e);
    cursor = secIndex.entities(txn, null);
    cursor.next();
    assertEquals(2, cursor.count());
    cursor.close();

    txnCommit(txn);
    close();
  }
示例#4
0
  /**
   * Same as testPutEntitySubclassWithGetSubclassIndex2 but store the first instance of the subclass
   * after closing and reopening the store, *without* calling getSubclassIndex. This ensures that a
   * single call to getSubclassIndex is sufficient and subsequent use of the store does not require
   * it. [#16399]
   */
  public void testPutEntitySubclassWithGetSubclassIndex2() throws DatabaseException {

    open();

    PrimaryIndex<Long, Statement> pri = store.getPrimaryIndex(Long.class, Statement.class);

    SecondaryIndex<String, Long, ExtendedStatement> sec =
        store.getSubclassIndex(pri, ExtendedStatement.class, String.class, "name");

    Transaction txn = txnBegin();
    pri.put(txn, new Statement(1));
    txnCommit(txn);

    close();
    open();

    pri = store.getPrimaryIndex(Long.class, Statement.class);

    txn = txnBegin();
    pri.put(txn, new ExtendedStatement(2, "abc"));
    txnCommit(txn);

    sec = store.getSubclassIndex(pri, ExtendedStatement.class, String.class, "name");

    ExtendedStatement o = sec.get("abc");
    assertNotNull(o);
    assertEquals(2, o.id);

    close();
  }
示例#5
0
文件: Store.java 项目: nologic/nabs
  /**
   * Opens any secondary indexes defined in the given entity metadata that are not already open.
   * This method is called when a new entity subclass is encountered when an instance of that class
   * is stored, and the EntityStore.getSubclassIndex has not been previously called for that class.
   * [#15247]
   */
  synchronized void openSecondaryIndexes(
      Transaction txn, EntityMetadata entityMeta, PrimaryOpenState priOpenState)
      throws DatabaseException {

    String entityClassName = entityMeta.getClassName();
    PrimaryIndex<Object, Object> priIndex = priIndexMap.get(entityClassName);
    assert priIndex != null;
    Class<Object> entityClass = priIndex.getEntityClass();

    for (SecondaryKeyMetadata secKeyMeta : entityMeta.getSecondaryKeys().values()) {
      String keyName = secKeyMeta.getKeyName();
      String secName = makeSecName(entityClassName, keyName);
      SecondaryIndex<Object, Object, Object> secIndex = secIndexMap.get(secName);
      if (secIndex == null) {
        String keyClassName = getSecKeyClass(secKeyMeta);
        /* RawMode: should not require class. */
        Class keyClass = SimpleCatalog.keyClassForName(keyClassName);
        openSecondaryIndex(
            txn,
            priIndex,
            entityClass,
            entityMeta,
            keyClass,
            keyClassName,
            secKeyMeta,
            makeSecName(entityClassName, secKeyMeta.getKeyName()),
            storeConfig.getSecondaryBulkLoad() /*doNotCreate*/,
            priOpenState);
      }
    }
  }
  /** Primary keys: {0, 1, 2, 3, 4} */
  @Test
  public void testPrimary() throws DatabaseException {

    SortedMap<Integer, SortedSet<Integer>> expected = new TreeMap<Integer, SortedSet<Integer>>();

    for (int priKey = 0; priKey < N_RECORDS; priKey += 1) {
      SortedSet<Integer> values = new TreeSet<Integer>();
      values.add(priKey);
      expected.put(priKey, values);
    }

    open();
    addEntities(primary);
    checkIndex(primary, expected, keyGetter, entityGetter);
    checkIndex(primaryRaw, expected, rawKeyGetter, rawEntityGetter);

    /* Close and reopen, then recheck indices. */
    close();
    open();
    checkIndex(primary, expected, keyGetter, entityGetter);
    checkIndex(primaryRaw, expected, rawKeyGetter, rawEntityGetter);

    /* Check primary delete, last key first for variety. */
    for (int priKey = N_RECORDS - 1; priKey >= 0; priKey -= 1) {
      boolean useRaw = ((priKey & 1) != 0);
      Transaction txn = txnBegin();
      if (useRaw) {
        primaryRaw.delete(txn, priKey);
      } else {
        primary.delete(txn, priKey);
      }
      txnCommit(txn);
      expected.remove(priKey);
      checkIndex(primary, expected, keyGetter, entityGetter);
    }
    checkAllEmpty();

    /* Check PrimaryIndex put operations. */
    MyEntity e;
    Transaction txn = txnBegin();
    /* put() */
    e = primary.put(txn, new MyEntity(1));
    assertNull(e);
    e = primary.get(txn, 1, null);
    assertEquals(1, e.key);
    /* putNoReturn() */
    primary.putNoReturn(txn, new MyEntity(2));
    e = primary.get(txn, 2, null);
    assertEquals(2, e.key);
    /* putNoOverwrite */
    assertTrue(!primary.putNoOverwrite(txn, new MyEntity(1)));
    assertTrue(!primary.putNoOverwrite(txn, new MyEntity(2)));
    assertTrue(primary.putNoOverwrite(txn, new MyEntity(3)));
    e = primary.get(txn, 3, null);
    assertEquals(3, e.key);
    txnCommit(txn);
    close();
  }
示例#7
0
  public void testCustomCompare() throws DatabaseException {

    open();

    PrimaryIndex<ReverseIntKey, CustomCompareEntity> priIndex =
        store.getPrimaryIndex(ReverseIntKey.class, CustomCompareEntity.class);

    SecondaryIndex<ReverseIntKey, ReverseIntKey, CustomCompareEntity> secIndex1 =
        store.getSecondaryIndex(priIndex, ReverseIntKey.class, "secKey1");

    SecondaryIndex<ReverseIntKey, ReverseIntKey, CustomCompareEntity> secIndex2 =
        store.getSecondaryIndex(priIndex, ReverseIntKey.class, "secKey2");

    Transaction txn = txnBegin();
    for (int i = 1; i <= 5; i += 1) {
      assertTrue(priIndex.putNoOverwrite(txn, new CustomCompareEntity(i)));
    }
    txnCommit(txn);

    txn = txnBeginCursor();
    EntityCursor<CustomCompareEntity> c = priIndex.entities(txn, null);
    for (int i = 5; i >= 1; i -= 1) {
      CustomCompareEntity e = c.next();
      assertNotNull(e);
      assertEquals(new ReverseIntKey(i), e.key);
    }
    c.close();
    txnCommit(txn);

    txn = txnBeginCursor();
    c = secIndex1.entities(txn, null);
    for (int i = -1; i >= -5; i -= 1) {
      CustomCompareEntity e = c.next();
      assertNotNull(e);
      assertEquals(new ReverseIntKey(-i), e.key);
      assertEquals(new ReverseIntKey(i), e.secKey1);
    }
    c.close();
    txnCommit(txn);

    txn = txnBeginCursor();
    c = secIndex2.entities(txn, null);
    for (int i = -1; i >= -5; i -= 1) {
      CustomCompareEntity e = c.next();
      assertNotNull(e);
      assertEquals(new ReverseIntKey(-i), e.key);
      assertTrue(e.secKey2.contains(new ReverseIntKey(i)));
    }
    c.close();
    txnCommit(txn);

    close();
  }
示例#8
0
  /**
   * When opening an X_TO_MANY secondary that has a persistent key class, the key class was not
   * recognized as being persistent if it was never before referenced when getSecondaryIndex was
   * called. This was a bug in JE 3.0.12, reported on OTN. [#15103]
   */
  public void testToManyKeyClass() throws DatabaseException {

    open();

    PrimaryIndex<Integer, ToManyKeyEntity> priIndex =
        store.getPrimaryIndex(Integer.class, ToManyKeyEntity.class);
    SecondaryIndex<ToManyKey, Integer, ToManyKeyEntity> secIndex =
        store.getSecondaryIndex(priIndex, ToManyKey.class, "key2");

    priIndex.put(new ToManyKeyEntity());
    secIndex.get(new ToManyKey());

    close();
  }
示例#9
0
  /**
   * Returns a read-only keys index that maps secondary key to primary key. When accessing the keys
   * index, the primary key is returned rather than the entity. When only the primary key is needed
   * and not the entire entity, using the keys index is less expensive than using the secondary
   * index because the primary index does not have to be accessed.
   *
   * <p>Note the following in the unusual case that you are <em>not</em> using an <code>EntityStore
   * </code>: This method will open the keys database, a second database handle for the secondary
   * database, if it is not already open. In this case, if you are <em>not</em> using an <code>
   * EntityStore</code>, then you are responsible for closing the database returned by {@link
   * #getKeysDatabase} before closing the environment. If you <em>are</em> using an <code>
   * EntityStore</code>, the keys database will be closed automatically by {@link
   * EntityStore#close}.
   *
   * @return the keys index.
   */
  public synchronized EntityIndex<SK, PK> keysIndex() throws DatabaseException {

    if (keysIndex == null) {
      if (keysDb == null) {
        DatabaseConfig config = secDb.getConfig();
        config.setReadOnly(true);
        keysDb = db.getEnvironment().openDatabase(null, secDb.getDatabaseName(), config);
      }
      keysIndex =
          new KeysIndex<SK, PK>(
              keysDb, keyClass, keyBinding, priIndex.getKeyClass(), priIndex.getKeyBinding());
    }
    return keysIndex;
  }
示例#10
0
  public void testUninitializedCursor() throws DatabaseException {

    open();

    PrimaryIndex<Integer, MyEntity> priIndex = store.getPrimaryIndex(Integer.class, MyEntity.class);

    Transaction txn = txnBeginCursor();

    MyEntity e = new MyEntity();
    e.priKey = 1;
    e.secKey = 1;
    priIndex.put(txn, e);

    EntityCursor<MyEntity> entities = priIndex.entities(txn, null);
    try {
      entities.nextDup();
      fail();
    } catch (IllegalStateException expected) {
    }
    try {
      entities.prevDup();
      fail();
    } catch (IllegalStateException expected) {
    }
    try {
      entities.current();
      fail();
    } catch (IllegalStateException expected) {
    }
    try {
      entities.delete();
      fail();
    } catch (IllegalStateException expected) {
    }
    try {
      entities.update(e);
      fail();
    } catch (IllegalStateException expected) {
    }
    try {
      entities.count();
      fail();
    } catch (IllegalStateException expected) {
    }

    entities.close();
    txnCommit(txn);
    close();
  }
    public void putWithTry(int numOps) {
      try {
        setup(true);
        for (int i = 0; i < numOps; i++) {
          TestObject object = new TestObject();
          String s = new Integer(i).toString();
          object.setSid(s);
          object.setName("hero" + s);
          object.setCountry("China");

          objectList.add(object);

          if (objectList.size() >= CACHE_LIMIT) {
            close();

            boolean success = false;
            while (!success) {
              success = setup(false);
            }

            for (int j = 0; j < objectList.size(); j++) {
              objectBySid.putNoReturn(objectList.get(j));
            }

            close();
            setup(true);
            objectList = new ArrayList<TestObject>();
          }
        }
      } catch (DatabaseException e) {
        e.printStackTrace();
      }
    }
 public synchronized <K, E> boolean putNoOverwrite(PrimaryIndex<K, E> index, E entity) {
   try {
     return index.putNoOverwrite(getDbTransaction(), entity);
   } catch (DatabaseException e) {
     throw getPersistenceManager().convertDatabaseException(e);
   }
 }
 public synchronized <K, E> void putNoReturn(PrimaryIndex<K, E> index, E entity) {
   try {
     index.putNoReturn(getDbTransaction(), entity);
   } catch (DatabaseException e) {
     throw getPersistenceManager().convertDatabaseException(e);
   }
 }
示例#14
0
  /** A proxied object may not current contain a field that references the parent proxy. [#15815] */
  public void testProxyNestedRef() throws DatabaseException {

    open();
    PrimaryIndex<Integer, ProxyNestedRef> index =
        store.getPrimaryIndex(Integer.class, ProxyNestedRef.class);
    ProxyNestedRef entity = new ProxyNestedRef();
    entity.list.add(entity.list);
    try {
      index.put(entity);
      fail();
    } catch (IllegalArgumentException expected) {
      assertTrue(
          expected.getMessage().indexOf("Cannot embed a reference to a proxied object") >= 0);
    }
    close();
  }
示例#15
0
  @Override
  public String saveDocument(
      DsSessionDto aSessionDto,
      DsDocumentDto aDocumentDto,
      String aKey,
      boolean aKeyIsNumeric,
      String aValue,
      String aSecurityPolicyName,
      String aContentFileKey) {

    if ("bug".equals(aSessionDto.getUsername())) {
      throw new IllegalStateException("this is a bug");
    }

    Transaction tx = entityStore.getEnvironment().beginTransaction(null, null);

    Document doc = new Document();
    doc.setFileKey(aContentFileKey);

    doc.setFileName(getFileName(aDocumentDto));
    documentPrimaryIndex.put(doc);
    tx.commit();

    return String.valueOf(doc.getId());
  }
示例#16
0
  public void testPersistentFields() throws DatabaseException {

    open();
    PrimaryIndex<Integer, PersistentFields> pri =
        store.getPrimaryIndex(Integer.class, PersistentFields.class);
    PersistentFields o1 = new PersistentFields(-1, 1, 2, 3, 4, 5, 6);
    assertNull(pri.put(o1));
    PersistentFields o2 = pri.get(-1);
    assertNotNull(o2);
    assertEquals(0, o2.transient1);
    assertEquals(0, o2.transient2);
    assertEquals(0, o2.transient3);
    assertEquals(4, o2.persistent1);
    assertEquals(5, o2.persistent2);
    assertEquals(6, o2.persistent3);
    close();
  }
示例#17
0
  /** Disallow primary keys on entity subclasses. [#15757] */
  public void testEntitySubclassWithPrimaryKey() throws DatabaseException {

    open();
    PrimaryIndex<Integer, EntitySuperClass> index =
        store.getPrimaryIndex(Integer.class, EntitySuperClass.class);
    EntitySuperClass e1 = new EntitySuperClass(1, "one");
    index.put(e1);
    assertEquals(e1, index.get(1));
    EntitySubClass e2 = new EntitySubClass(2, "two", "foo", 9);
    try {
      index.put(e2);
    } catch (IllegalArgumentException e) {
      assertTrue(e.getMessage().contains("PrimaryKey may not appear on an Entity subclass"));
    }
    assertEquals(e1, index.get(1));
    close();
  }
 private void executeShutdown() {
   if (resolutionIndex != null) {
     for (String link : urlsToResolve) {
       toResolveStore store = new toResolveStore();
       store.setPKey(link);
       resolutionIndex.put(store);
     }
   }
 }
示例#19
0
  @Override
  public String getDocumentContent(DsSessionDto aSessionDto, String aDocumentId) {
    if ("bug".equals(aSessionDto.getUsername())) {
      throw new IllegalStateException("this is a bug");
    }

    Document doc = documentPrimaryIndex.get(Long.valueOf(aDocumentId));
    return doc.getFileKey();
  }
示例#20
0
  private void addEntities(PrimaryIndex<Integer, MyEntity> primary) throws DatabaseException {

    Transaction txn = txnBegin();
    for (int priKey = 0; priKey < N_RECORDS; priKey += 1) {
      MyEntity prev = primary.put(txn, new MyEntity(priKey));
      assertNull(prev);
    }
    txnCommit(txn);
  }
示例#21
0
  /**
   * Creates a secondary index without using an <code>EntityStore</code>. When using an {@link
   * EntityStore}, call {@link EntityStore#getSecondaryIndex getSecondaryIndex} instead.
   *
   * <p>This constructor is not normally needed and is provided for applications that wish to use
   * custom bindings along with the Direct Persistence Layer. Normally, {@link
   * EntityStore#getSecondaryIndex getSecondaryIndex} is used instead.
   *
   * @param database the secondary database used for all access other than via a {@link #keysIndex}.
   * @param keysDatabase another handle on the secondary database, opened without association to the
   *     primary, and used only for access via a {@link #keysIndex}. If this argument is null and
   *     the {@link #keysIndex} method is called, then the keys database will be opened
   *     automatically; however, the user is then responsible for closing the keys database. To get
   *     the keys database in order to close it, call {@link #getKeysDatabase}.
   * @param primaryIndex the primary index associated with this secondary index.
   * @param secondaryKeyClass the class of the secondary key.
   * @param secondaryKeyBinding the binding to be used for secondary keys.
   */
  public SecondaryIndex(
      SecondaryDatabase database,
      Database keysDatabase,
      PrimaryIndex<PK, E> primaryIndex,
      Class<SK> secondaryKeyClass,
      EntryBinding secondaryKeyBinding)
      throws DatabaseException {

    super(
        database,
        secondaryKeyClass,
        secondaryKeyBinding,
        new EntityValueAdapter(
            primaryIndex.getEntityClass(), primaryIndex.getEntityBinding(), true));
    secDb = database;
    keysDb = keysDatabase;
    priIndex = primaryIndex;
    entityBinding = primaryIndex.getEntityBinding();
  }
示例#22
0
  @Override
  public void deleteDocument(DsSessionDto aSessionDto, String aDocumentId) {

    if ("bug".equals(aSessionDto.getUsername())) {
      throw new IllegalStateException("this is a bug");
    }

    Transaction tx = entityStore.getEnvironment().beginTransaction(null, null);
    documentPrimaryIndex.delete(Long.valueOf(aDocumentId));
    tx.commit();
  }
示例#23
0
  public void testSeparateSequence() throws DatabaseException {

    open();

    PrimaryIndex<Integer, SeparateSequenceEntity1> priIndex1 =
        store.getPrimaryIndex(Integer.class, SeparateSequenceEntity1.class);

    PrimaryIndex<Integer, SeparateSequenceEntity2> priIndex2 =
        store.getPrimaryIndex(Integer.class, SeparateSequenceEntity2.class);

    Transaction txn = txnBegin();
    SeparateSequenceEntity1 e1 = new SeparateSequenceEntity1();
    SeparateSequenceEntity2 e2 = new SeparateSequenceEntity2();
    priIndex1.put(txn, e1);
    assertEquals(1, e1.key);
    priIndex2.putNoOverwrite(txn, e2);
    assertEquals(Integer.valueOf(1), e2.key);
    e1.key = 0;
    priIndex1.putNoOverwrite(txn, e1);
    assertEquals(2, e1.key);
    e2.key = null;
    priIndex2.put(txn, e2);
    assertEquals(Integer.valueOf(2), e2.key);
    txnCommit(txn);

    close();
  }
示例#24
0
  public void testReadOnly() throws DatabaseException {

    open();
    PrimaryIndex<Integer, SharedSequenceEntity1> priIndex =
        store.getPrimaryIndex(Integer.class, SharedSequenceEntity1.class);
    Transaction txn = txnBegin();
    SharedSequenceEntity1 e = new SharedSequenceEntity1();
    priIndex.put(txn, e);
    assertEquals(1, e.key);
    txnCommit(txn);
    close();

    /*
     * Check that we can open the store read-only and read the records
     * written above.
     */
    openReadOnly();
    priIndex = store.getPrimaryIndex(Integer.class, SharedSequenceEntity1.class);
    e = priIndex.get(1);
    assertNotNull(e);
    close();
  }
示例#25
0
文件: Store.java 项目: nologic/nabs
  public synchronized void close() throws DatabaseException {

    checkOpen();
    DatabaseException firstException = null;
    try {
      if (rawAccess) {
        boolean allClosed = catalog.close();
        assert allClosed;
      } else {
        synchronized (catalogPool) {
          Map<String, PersistCatalog> catalogMap = catalogPool.get(env);
          assert catalogMap != null;
          if (catalog.close()) {
            /* Remove when the reference count goes to zero. */
            catalogMap.remove(storeName);
          }
        }
      }
      catalog = null;
    } catch (DatabaseException e) {
      if (firstException == null) {
        firstException = e;
      }
    }
    firstException = closeDb(sequenceDb, firstException);
    for (SecondaryIndex index : secIndexMap.values()) {
      firstException = closeDb(index.getDatabase(), firstException);
      firstException = closeDb(index.getKeysDatabase(), firstException);
    }
    for (PrimaryIndex index : priIndexMap.values()) {
      firstException = closeDb(index.getDatabase(), firstException);
    }
    if (firstException != null) {
      throw firstException;
    }
  }
 public void putNoTry(int numOps) {
   setup(false);
   try {
     for (int i = 0; i < numOps; i++) {
       TestObject object = new TestObject();
       String sId = new Integer(i).toString();
       object.setSid(sId);
       object.setName("hero" + sId);
       object.setCountry("China");
       objectBySid.putNoReturn(object);
     }
   } catch (DatabaseException e) {
     e.printStackTrace();
   }
 }
示例#27
0
  public void testCompositeSequence() throws DatabaseException {

    open();

    PrimaryIndex<CompositeSequenceEntity1.Key, CompositeSequenceEntity1> priIndex1 =
        store.getPrimaryIndex(CompositeSequenceEntity1.Key.class, CompositeSequenceEntity1.class);

    PrimaryIndex<CompositeSequenceEntity2.Key, CompositeSequenceEntity2> priIndex2 =
        store.getPrimaryIndex(CompositeSequenceEntity2.Key.class, CompositeSequenceEntity2.class);

    Transaction txn = txnBegin();
    CompositeSequenceEntity1 e1 = new CompositeSequenceEntity1();
    CompositeSequenceEntity2 e2 = new CompositeSequenceEntity2();
    priIndex1.put(txn, e1);
    assertEquals(1, e1.key.key);
    priIndex2.putNoOverwrite(txn, e2);
    assertEquals(Integer.valueOf(1), e2.key.key);
    e1.key = null;
    priIndex1.putNoOverwrite(txn, e1);
    assertEquals(2, e1.key.key);
    e2.key = null;
    priIndex2.put(txn, e2);
    assertEquals(Integer.valueOf(2), e2.key.key);
    txnCommit(txn);

    EntityCursor<CompositeSequenceEntity1> c1 = priIndex1.entities();
    e1 = c1.next();
    assertEquals(2, e1.key.key);
    e1 = c1.next();
    assertEquals(1, e1.key.key);
    e1 = c1.next();
    assertNull(e1);
    c1.close();

    EntityCursor<CompositeSequenceEntity2> c2 = priIndex2.entities();
    e2 = c2.next();
    assertEquals(Integer.valueOf(2), e2.key.key);
    e2 = c2.next();
    assertEquals(Integer.valueOf(1), e2.key.key);
    e2 = c2.next();
    assertNull(e2);
    c2.close();

    close();
  }
示例#28
0
  /**
   * When Y is opened and X has a key with relatedEntity=Y.class, X should be opened automatically.
   * If X is not opened, foreign key constraints will not be enforced. [#15358]
   */
  public void testAutoOpenRelatedEntity() throws DatabaseException {

    PrimaryIndex<Integer, RelatedY> priY;
    PrimaryIndex<Integer, RelatedX> priX;

    /* Opening X should create (and open) Y and enforce constraints. */
    open();
    priX = store.getPrimaryIndex(Integer.class, RelatedX.class);
    PersistTestUtils.assertDbExists(true, env, STORE_NAME, RelatedY.class.getName(), null);
    if (isTransactional) {
      /* Constraint enforcement requires transactions. */
      try {
        priX.put(new RelatedX());
        fail();
      } catch (DatabaseException e) {
        assertTrue(
            "" + e.getMessage(),
            (e.getMessage().indexOf("foreign key not allowed: it is not present") >= 0)
                || (e.getMessage().indexOf("DB_FOREIGN_CONFLICT") >= 0));
      }
    }
    priY = store.getPrimaryIndex(Integer.class, RelatedY.class);
    priY.put(new RelatedY());
    priX.put(new RelatedX());
    close();

    /* Delete should cascade even when X is not opened explicitly. */
    open();
    priY = store.getPrimaryIndex(Integer.class, RelatedY.class);
    assertEquals(1, priY.count());
    priY.delete(88);
    assertEquals(0, priY.count());
    priX = store.getPrimaryIndex(Integer.class, RelatedX.class);
    assertEquals(0, priX.count()); /* Failed prior to [#15358] fix. */
    close();
  }
示例#29
0
  private void run() throws DatabaseException {

    Random rand = new Random();

    /*
     * Create a set of events. Each insertion is a separate, auto-commit
     * transaction.
     */
    System.out.println("-> Inserting 4 events");
    eventByTime.put(new Event(makeDate(1), 100, "Company_A"));
    eventByTime.put(new Event(makeDate(2), 2, "Company_B"));
    eventByTime.put(new Event(makeDate(3), 20, "Company_C"));
    eventByTime.put(new Event(makeDate(4), 40, "CompanyD"));

    /* Load a whole set of events transactionally. */
    Transaction txn = env.beginTransaction(null, null);
    int maxPrice = 50;
    System.out.println("-> Inserting some randomly generated events");
    for (int i = 0; i < 25; i++) {
      Event e = new Event(makeDate(rand.nextInt(365)), rand.nextInt(maxPrice), "Company_X");
      if ((i % 2) == 0) {
        e.addRep("Bob");
        e.addRep("Nikunj");
      } else {
        e.addRep("Yongmin");
      }
      eventByTime.put(e);
    }
    txn.commitWriteNoSync();

    /*
     * Windows of events - display the events between June 1 and Aug 31
     */
    System.out.println("\n-> Display the events between June 1 and Aug 31");
    Date startDate = makeDate(Calendar.JUNE, 1);
    Date endDate = makeDate(Calendar.AUGUST, 31);

    EntityCursor<Event> eventWindow = eventByTime.entities(startDate, true, endDate, true);
    printEvents(eventWindow);

    /*
     * Display all events, ordered by a secondary index on price.
     */
    System.out.println("\n-> Display all events, ordered by price");
    EntityCursor<Event> byPriceEvents = eventByPrice.entities();
    printEvents(byPriceEvents);
  }
 /** Default constructor for the DNS resolver thread */
 public DnsResolver() {
   dnsCache = new ConcurrentHashMap<String, InetAddress>();
   urlsToResolve = new LinkedBlockingQueue<String>();
   CrawlerDrone.addLog("DNS Resolver starting......");
   resolutionIndex =
       CrawlerDrone.bdb.getPrimaryIndex(
           storage.BDBWrapper.DB_TO_RESOLVE_STORE, String.class, toResolveStore.class);
   if (resolutionIndex != null) {
     EntityCursor<toResolveStore> previousUnresolved = resolutionIndex.entities();
     for (toResolveStore item : previousUnresolved) {
       urlsToResolve.add(item.getPKey());
     }
     previousUnresolved.close();
     try {
       CrawlerDrone.bdb
           .getEnvironment()
           .truncateDatabase(null, storage.BDBWrapper.DB_TO_RESOLVE_STORE, false);
     } catch (DatabaseNotFoundException e) {
       // Nothing to restore
     }
   }
   CrawlerDrone.addLog("DNS Resolver started.");
 }