Ejemplo n.º 1
0
  public void testCreateAndLoadLaptop() throws Exception {
    Database database = _category.getDatabase();

    database.begin();
    ProductDetail detail = new ProductDetail();
    detail.setId(10);
    detail.setCategory("category 10");
    detail.setLocation("location 10");
    database.create(detail);
    database.commit();

    database.begin();
    Laptop laptop = new Laptop();
    laptop.setId(10);
    laptop.setName("laptop 10");
    laptop.setCpu("centrino");
    laptop.setResolution("1600");
    laptop.setWeight(2750);
    laptop.setDetail((ProductDetail) database.load(ProductDetail.class, new Integer(10)));
    database.create(laptop);

    Owner owner = new Owner();
    owner.setId(new Integer(10));
    owner.setName("owner 10");
    owner.setProduct(laptop);
    database.commit();

    database.begin();
    laptop = (Laptop) database.load(Laptop.class, new Integer(10));
    database.commit();

    assertNotNull(laptop);
    assertEquals("ctf.jdo.tc9x.Laptop", laptop.getClass().getName());
    assertEquals(10, laptop.getId());
    assertEquals("laptop 10", laptop.getName());

    database.begin();
    database.remove(database.load(Laptop.class, new Integer(10)));
    database.remove(database.load(ProductDetail.class, new Integer(10)));
    database.commit();

    database.begin();
    try {
      laptop = (Laptop) database.load(Laptop.class, new Integer(10));
      fail("Laptop with id 10 still exists.");
    } catch (ObjectNotFoundException e) {
      assertEquals(
          "The object of type ctf.jdo.tc9x.Laptop with identity <10(10)> "
              + "was not found in persistent storage",
          e.getMessage());
    }
    database.commit();

    database.close();
  }
Ejemplo n.º 2
0
  public void testCreateAndLoadCar() throws Exception {
    Database database = _category.getDatabase();

    database.begin();
    Order order = new Order();
    order.setId(11);
    order.setName("order 11");
    database.create(order);
    database.commit();

    database.begin();
    ProductDetail detail = new ProductDetail();
    detail.setId(11);
    detail.setCategory("category 11");
    detail.setLocation("location 11");
    database.create(detail);
    database.commit();

    database.begin();
    Truck truck = new Truck();
    truck.setId(11);
    truck.setName("truck 11");
    truck.setKw(112);
    truck.setMake("Fiat");
    truck.setMaxWeight(3750);
    truck.setDetail((ProductDetail) database.load(ProductDetail.class, new Integer(11)));
    database.create(truck);
    Collection orders = new LinkedList();
    orders.add(database.load(Order.class, new Integer(11)));
    truck.setOrders(orders);
    database.commit();

    database.begin();
    Object object = database.load(Car.class, new Integer(11));
    assertNotNull(object);
    assertEquals("ctf.jdo.tc9x.Truck", object.getClass().getName());
    Truck loadedTruck = (Truck) object;
    database.commit();

    assertNotNull(loadedTruck);
    assertEquals(11, loadedTruck.getId());

    database.begin();
    database.remove(database.load(Car.class, new Integer(11)));
    database.remove(database.load(ProductDetail.class, new Integer(11)));
    database.remove(database.load(Order.class, new Integer(11)));
    database.commit();

    database.close();
  }
Ejemplo n.º 3
0
  public void testCreateAndLoadComputer() throws Exception {
    Database database = _category.getDatabase();

    database.begin();
    Order order = new Order();
    order.setId(12);
    order.setName("order 12");
    database.create(order);
    database.commit();

    database.begin();
    ProductDetail detail = new ProductDetail();
    detail.setId(12);
    detail.setCategory("category 12");
    detail.setLocation("location 12");
    database.create(detail);
    database.commit();

    database.begin();
    Laptop laptop = new Laptop();
    laptop.setId(12);
    laptop.setName("laptop 12");
    laptop.setCpu("centrino");
    laptop.setResolution("1600");
    laptop.setWeight(2450);
    laptop.setDetail((ProductDetail) database.load(ProductDetail.class, new Integer(12)));
    database.create(laptop);
    Collection orders = new LinkedList();
    orders.add(database.load(Order.class, new Integer(12)));
    laptop.setOrders(orders);
    database.commit();

    database.begin();
    Computer computer = (Computer) database.load(Computer.class, new Integer(12));
    database.commit();

    assertNotNull(computer);
    assertEquals("ctf.jdo.tc9x.Laptop", computer.getClass().getName());
    assertEquals(12, computer.getId());
    assertEquals("laptop 12", computer.getName());

    database.begin();
    computer = (Computer) database.load(Computer.class, new Integer(12));
    database.remove(computer);
    database.remove(database.load(ProductDetail.class, new Integer(12)));
    database.remove(database.load(Order.class, new Integer(12)));
    database.commit();

    database.close();
  }
Ejemplo n.º 4
0
  public void testQuery() throws Exception {
    Database database;

    // create some products
    database = _category.getDatabase();
    database.begin();

    database.create(new Product(1, "LCD", KindEnum.MONITOR));
    database.create(new Product(2, "Laser", KindEnum.PRINTER));
    database.create(new Product(3, "Desktop", KindEnum.COMPUTER));
    database.create(new Product(4, "Notebook", KindEnum.COMPUTER));

    database.commit();
    database.close();

    // query and delete all product
    database = _category.getDatabase();
    database.begin();

    Product pq;
    OQLQuery query =
        database.getOQLQuery(
            "select p from " + jdo.tc167.Product.class.getName() + " p order by p.id");
    QueryResults results = query.execute();

    pq = (Product) results.next();
    assertEquals(pq, new Product(1, "LCD", KindEnum.MONITOR));
    database.remove(pq);

    pq = (Product) results.next();
    assertEquals(pq, new Product(2, "Laser", KindEnum.PRINTER));
    database.remove(pq);

    pq = (Product) results.next();
    assertEquals(pq, new Product(3, "Desktop", KindEnum.COMPUTER));
    database.remove(pq);

    pq = (Product) results.next();
    assertEquals(pq, new Product(4, "Notebook", KindEnum.COMPUTER));
    database.remove(pq);

    assertFalse(results.hasMore());
    results.close();
    query.close();

    database.commit();
    database.close();
  }
Ejemplo n.º 5
0
 public LanguageVO create(Database db, LanguageVO languageVO)
     throws ConstraintException, SystemException, Exception {
   Language ent = new LanguageImpl();
   ent.setValueObject(languageVO);
   db.create(ent);
   return ent.getValueObject();
 }
Ejemplo n.º 6
0
  /**
   * This method is called by the tests and preform the actual concurrent modification test.
   *
   * @param accessMode the access mode that is used in the concurrent modification tests
   */
  private void testDirtyIgnored(final AccessMode accessMode)
      throws PersistenceException, SQLException {
    OQLQuery oql;
    Sample object;
    QueryResults enumeration;

    // Open transaction in order to perform JDO operations
    _db.begin();

    // Determine if test object exists, if not create it.
    // If it exists, set the name to some predefined value
    // that this test will later override.
    oql = _db.getOQLQuery("SELECT object FROM " + Sample.class.getName() + " object WHERE id = $1");
    oql.bind(Sample.DEFAULT_ID);

    enumeration = oql.execute();
    if (enumeration.hasMore()) {
      object = (Sample) enumeration.next();
      LOG.debug("Retrieved object: " + object);
      object.setValue1(Sample.DEFAULT_VALUE_1);
      object.setValue2(Sample.DEFAULT_VALUE_2);
    } else {
      object = new Sample();
      LOG.debug("Creating new object: " + object);
      _db.create(object);
    }

    _db.commit();

    // Open a new transaction in order to conduct test
    _db.begin();

    oql.bind(new Integer(Sample.DEFAULT_ID));
    object = (Sample) oql.execute(accessMode).nextElement();
    object.setValue2(JDO_VALUE);

    // Perform direct JDBC access and override the value of that table
    if (accessMode != Database.DbLocked) {
      _conn
          .createStatement()
          .execute(
              "UPDATE tc0x_sample SET value2='" + JDBC_VALUE + "' WHERE id=" + Sample.DEFAULT_ID);
      LOG.debug("Updated test object from JDBC");
    }

    // Commit JDO transaction, this should report object modified exception
    LOG.debug("Commit update: no dirty checking field not modified");
    try {
      _db.commit();
      LOG.debug("OK: ObjectModifiedException not thrown");
    } catch (ObjectModifiedException ex) {
      if (_db.isActive()) {
        _db.rollback();
      }
      LOG.error("Error: ObjectModifiedException thrown", ex);
      fail("ObjectModifiedException thrown");
    }
  }
Ejemplo n.º 7
0
  public void testDepends() throws Exception {
    Database db = null;
    MasterObjectNoKeyGen master = new MasterObjectNoKeyGen();
    master.setId(100);
    master.setDescrip("This is the descrip.");
    db = _category.getDatabase();
    db.begin();
    db.create(master);
    db.commit();

    assertTrue(master.getId() != 0);
    assertEquals(100, master.getId());

    // THIS Part Works!
    db.begin();
    DependentObjectNoKeyGen depends = new DependentObjectNoKeyGen();
    depends.setId(101);
    depends.setDescrip("Description");
    master.setDepends(depends);
    db.update(master);
    db.commit();

    assertTrue(master.getId() != 0);
    assertEquals(100, master.getId());
    int masterId = master.getId();

    db.begin();
    master = (MasterObjectNoKeyGen) db.load(MasterObjectNoKeyGen.class, new Integer(masterId));
    assertNotNull(master.getDepends());
    master.setDepends(null);
    db.commit();

    db.begin();
    master = (MasterObjectNoKeyGen) db.load(MasterObjectNoKeyGen.class, new Integer(masterId));
    assertNull(master.getDepends());
    db.commit();

    // THIS part doesn't!
    db.begin();
    master = (MasterObjectNoKeyGen) db.load(MasterObjectNoKeyGen.class, new Integer(masterId));
    depends = new DependentObjectNoKeyGen();
    depends.setId(102);
    depends.setDescrip("Description");
    master.setDepends(depends);
    db.commit();

    db.begin();
    master = (MasterObjectNoKeyGen) db.load(MasterObjectNoKeyGen.class, new Integer(masterId));
    assertNotNull(master.getDepends());
    db.commit();

    db.begin();
    master = (MasterObjectNoKeyGen) db.load(MasterObjectNoKeyGen.class, new Integer(masterId));
    assertNotNull(master);
    db.remove(master);
    db.commit();
  }
Ejemplo n.º 8
0
  public void testCreateLoadUpdateDelete() throws Exception {
    Database database;

    // create product
    database = _category.getDatabase();
    database.begin();

    Product pc = new Product(1, "LCD", KindEnum.MONITOR);
    database.create(pc);

    database.commit();
    database.close();

    // load created product
    database = _category.getDatabase();
    database.begin();

    Product pl1 = new Product(1, "LCD", KindEnum.MONITOR);
    Product pl2 = (Product) database.load(Product.class, new Integer(1));
    assertEquals(pl1, pl2);

    database.commit();
    database.close();

    // update product
    database = _category.getDatabase();
    database.begin();

    Product pu = (Product) database.load(Product.class, new Integer(1));
    pu.setName("Laser");
    pu.setKind(KindEnum.PRINTER);

    database.commit();
    database.close();

    // load updated product
    database = _category.getDatabase();
    database.begin();

    Product pl3 = new Product(1, "Laser", KindEnum.PRINTER);
    Product pl4 = (Product) database.load(Product.class, new Integer(1));
    assertEquals(pl3, pl4);

    database.commit();
    database.close();

    // delete product
    database = _category.getDatabase();
    database.begin();

    Product pd = (Product) database.load(Product.class, new Integer(1));
    database.remove(pd);

    database.commit();
    database.close();
  }
  public PropertiesCategory createWithDatabase(PropertiesCategoryVO c, Database db)
      throws SystemException, PersistenceException {
    // Need this crappy hack to forge the relationship (castor completely sucks like this)
    // TODO: When hibernate comes, just save the VOs and if it has a child VO with an id set
    // TODO: it is used to make the relationship...ask me for clarification -frank
    Category category = (Category) getObjectWithId(CategoryImpl.class, c.getCategory().getId(), db);

    PropertiesCategory propertiesCategory = new PropertiesCategoryImpl();
    propertiesCategory.setValueObject(c);
    propertiesCategory.setCategory((CategoryImpl) category);
    db.create(propertiesCategory);
    return propertiesCategory;
  }
Ejemplo n.º 10
0
  public void runTest() throws PersistenceException, SQLException {
    OQLQuery oql;
    TestObject object;
    QueryResults enumeration;

    _db.begin();

    // Determine if test object exists, if not create it.
    // If it exists, set the name to some predefined value
    // that this test will later override.
    oql = _db.getOQLQuery("SELECT object FROM jdo.TestObject object WHERE id = $1");
    oql.bind(50);
    enumeration = oql.execute();
    if (enumeration.hasMore()) {
      object = (TestObject) enumeration.next();
      stream.println("Retrieved object: " + object);
      object.setValue1(TestObject.DefaultValue1);
      object.setValue2(TestObject.DefaultValue2);
    } else {
      object = new TestObject();
      object.setId(50);
      stream.println("Creating new object: " + object);
      _db.create(object);
    }
    oql.close();
    _db.commit();

    try {
      stream.println("CALL SQL query");
      _db.begin();
      oql =
          _db.getOQLQuery(
              "CALL SQL SELECT ID,VALUE1,VALUE2 FROM TEST_TABLE WHERE (ID = $1) AS jdo.TestObject");
      oql.bind(50);
      enumeration = oql.execute();
      if (enumeration.hasMore()) {
        object = (TestObject) enumeration.next();
        stream.println("Retrieved object: " + object);
      } else {
        fail("test object not found");
      }
      oql.close();
      _db.commit();
    } catch (Exception e) {
      fail("Exception thrown " + e);
    }
  }
Ejemplo n.º 11
0
  public void testRollback() throws Exception {
    Database db = getJDOManager(DBNAME, MAPPING).getDatabase();
    db.begin();
    LOG.info("Preparing for rollback bug");

    // Prepare the database: add a NewProduct, which references the same
    // ProductGroup as most Product objects do
    ProductGroup group = (ProductGroup) db.load(ProductGroup.class, new Integer(3));
    NewProduct newProduct = null;
    try {
      newProduct = (NewProduct) db.load(NewProduct.class, new Integer(1));
    } catch (ObjectNotFoundException e) {
      newProduct = new NewProduct();
      newProduct.setId(1);
      newProduct.setName("NewProduct1");
      newProduct.setPrice(1.0f);
      newProduct.setGroup(group);
      db.create(newProduct);
      LOG.info("NewProduct1 created.");
    }

    db.commit();

    // Now the data are prepared:
    // We have Product7 and NewProduct1, both are pointing to Group3
    // Below we will load both objects in on transaction and then call rollback
    db.begin();
    LOG.info("Trying to reproduce rollback bug");

    // loading both product entities
    newProduct = (NewProduct) db.load(NewProduct.class, new Integer(1));
    Product product = (Product) db.load(Product.class, new Integer(7));
    LOG.debug("Product loaded: " + product);
    LOG.debug("NewProduct loaded: " + newProduct);

    // we only loaded both objects in one tx. Now we are doing a rollback.
    LOG.info("Calling Rollback");
    db.rollback();

    LOG.info("End transaction: Trying to reproduce rollback bug");
    db.close();
  }
Ejemplo n.º 12
0
  public void testLazyCollectionRollback() throws PersistenceException, SQLException {

    stream.println("Running testLazyCollectionRollback...");

    Complex fullname = new Complex("First", "Person");

    // set up the data object
    _db.begin();
    TestLazyEmployee loadPerson = (TestLazyEmployee) _db.load(TestLazyEmployee.class, fullname);
    Collection projects = loadPerson.getProjects();
    TestLazyProject project = new TestLazyProject();

    project = new TestLazyProject();
    project.setId(1002);
    project.setName("Project Two");
    project.setOwner(loadPerson);
    projects.add(project);
    _db.create(project);

    _db.commit();

    _db.begin();
    loadPerson = (TestLazyEmployee) _db.load(TestLazyEmployee.class, fullname);
    projects = loadPerson.getProjects();

    // is the collection populated?
    assertTrue("The projects collection is not valid!.", projects != null && projects.size() > 0);

    // is the collection instanceof Lazy?
    assertTrue(
        "Collection has to be lazy! It is " + loadPerson.getProjects().getClass(),
        loadPerson.getProjects() instanceof org.exolab.castor.persist.Lazy);

    // OK, the collection of projects is there, let's test a rollback for bug #1046
    stream.println("Rolling back transaction");
    _db.rollback();

    // test it again since the rollback - is the collection instanceof Lazy?
    assertTrue(
        "Collection has to be lazy! It is " + loadPerson.getProjects().getClass(),
        loadPerson.getProjects() instanceof org.exolab.castor.persist.Lazy);
  }
Ejemplo n.º 13
0
  public void testQueryFinalize() throws Exception {
    LOG.info("Create many master objects");
    _db.begin();
    for (int i = 0; i < 100; i++) {
      Master master = new Master();
      _db.create(master);
    }
    _db.commit();

    LOG.info("query master objects");
    try {
      _db.begin();
      QueryResults results = getResults(_db);
      LOG.info("query can be garbage collected");
      while (results.hasMore()) {
        Master master = (Master) results.next();
        LOG.info(master.getId());
      }
      _db.commit();
    } catch (Exception e) {
      fail("Exception thrown iterating over results : " + e);
    }
  }
Ejemplo n.º 14
0
  public void testLongTransaction() throws Exception {
    Product product = null;
    ProductGroup group;
    QueryResults results;

    Database db = getJDOManager(DBNAME, MAPPING).getDatabase();

    db.begin();
    LOG.info("Begin transaction to remove Product objects");

    // Look up the products and if found delete them from the database
    OQLQuery productOql =
        db.getOQLQuery("SELECT p FROM " + Product.class.getName() + " p WHERE p.id = $1");

    for (int i = 4; i < 10; ++i) {
      productOql.bind(i);
      results = productOql.execute();
      while (results.hasMore()) {
        product = (Product) results.next();
        LOG.debug("Deleting existing product: " + product);
        db.remove(product);
      }
    }

    LOG.info("End transaction to remove Product objects");
    db.commit();

    db.begin();
    LOG.info("Begin transaction: one-to-one, one-to-many, and dependent relations");

    // If no such group exists in the database, create a new object and persist it
    OQLQuery groupOql =
        db.getOQLQuery("SELECT g FROM " + ProductGroup.class.getName() + " g WHERE id = $1");
    groupOql.bind(3);
    results = groupOql.execute();
    if (!results.hasMore()) {
      group = new ProductGroup();
      group.setId(3);
      group.setName("a group");
      db.create(group);
      LOG.debug("Creating new group: " + group);
    } else {
      group = (ProductGroup) results.next();
      LOG.debug("Query result: " + group);
    }

    // If no such product exists in the database, create a new object and persist it
    // Note: product uses group, so group object has to be created first, but can
    //       be persisted later
    productOql.bind(4);
    results = productOql.execute();
    if (!results.hasMore()) {
      product = new Product();
      product.setId(4);
      product.setName("product4");
      product.setPrice(200);
      product.setGroup(group);
      LOG.debug("Creating new product: " + product);
      db.create(product);
    } else {
      LOG.debug("Query result: " + results.next());
    }

    LOG.info("End transaction: one-to-one, one-to-many and dependent relations");
    db.commit();

    db.begin();
    LOG.info("Begin transaction: one-to-one and dependent relations");

    group = (ProductGroup) db.load(ProductGroup.class, new Integer(3));

    // If no such products with ids 5-8 exist, create new objects and persist them
    for (int i = 5; i < 10; ++i) {
      int j = i + 1;
      productOql.bind(j);
      results = productOql.execute();
      if (!results.hasMore()) {
        product = new Product();
        product.setId(i);
        product.setName("product" + product.getId());
        product.setPrice(300);
        product.setGroup(group);
        LOG.debug("Creating new product: " + product);
        db.create(product);
      } else {
        LOG.debug("Query result: " + results.next());
      }
    }

    LOG.info("End transaction: one-to-one and dependent relations");
    db.commit();

    product.setPrice(333);
    LOG.info("Updated Product price: " + product);

    db.begin();
    LOG.info("Begin transaction: long transaction");
    // Don't forget to implement TimeStampable for the long transaction!!!
    db.update(product);
    LOG.info("End transaction: long transaction");
    db.commit();

    db.close();
    LOG.info("Test complete");
  }
Ejemplo n.º 15
0
  /**
   * This method is called by the tests and preform the actual concurrent modification test.
   *
   * @param accessMode the access mode that is used in the concurrent modification tests
   */
  private void testDirtyChecked(final AccessMode accessMode)
      throws PersistenceException, SQLException {
    OQLQuery oql;
    Sample object;
    QueryResults enumeration;

    // Open transaction in order to perform JDO operations
    _db.begin();

    // Determine if test object exists, if not create it.
    // If it exists, set the name to some predefined value
    // that this test will later override.
    oql = _db.getOQLQuery("SELECT object FROM " + Sample.class.getName() + " object WHERE id = $1");
    oql.bind(Sample.DEFAULT_ID);

    enumeration = oql.execute();
    if (enumeration.hasMore()) {
      object = (Sample) enumeration.next();
      LOG.debug("Retrieved object: " + object);
      object.setValue1(Sample.DEFAULT_VALUE_1);
      object.setValue2(Sample.DEFAULT_VALUE_2);
    } else {
      object = new Sample();
      LOG.debug("Creating new object: " + object);
      _db.create(object);
    }

    _db.commit();

    // Open a new transaction in order to conduct test
    _db.begin();

    oql.bind(new Integer(Sample.DEFAULT_ID));
    object = (Sample) oql.execute(accessMode).nextElement();
    object.setValue1(JDO_VALUE);

    // Perform direct JDBC access and override the value of that table
    if (accessMode != Database.DbLocked) {
      _conn
          .createStatement()
          .execute(
              "UPDATE tc0x_sample SET value1='" + JDBC_VALUE + "' WHERE id=" + Sample.DEFAULT_ID);
      LOG.debug("OK: Updated object from JDBC");
    } else {
      Thread th =
          new Thread() {
            public void run() {
              Connection conn = null;
              try {
                conn = _category.getJDBCConnection();
                conn.createStatement()
                    .execute(
                        "UPDATE tc0x_sample SET value1='"
                            + JDBC_VALUE
                            + "' WHERE id="
                            + Sample.DEFAULT_ID);
                conn.close();
              } catch (Exception ex) {
              } finally {
                try {
                  if (conn != null) {
                    conn.close();
                  }
                } catch (Exception ex) {
                }
              }
            }
          };
      th.start();
      synchronized (this) {
        try {
          wait(5000);
          if (th.isAlive()) {
            th.interrupt();
            LOG.debug("OK: Cannot update object from JDBC");
          } else {
            LOG.error("Error: Updated object from JDBC");
            fail("Updated test object from JDBC");
          }
        } catch (InterruptedException ex) {
        }
      }
    }

    // Commit JDO transaction, this should report object modified exception
    LOG.debug("Committing JDO update: dirty checking field modified");
    if (accessMode != Database.DbLocked) {
      try {
        _db.commit();
        LOG.error("Error: ObjectModifiedException not thrown");
        fail("ObjectModifiedException not thrown");
      } catch (ObjectModifiedException ex) {
        LOG.debug("OK: ObjectModifiedException thrown");
      }
    } else {
      try {
        _db.commit();
        LOG.debug("OK: ObjectModifiedException not thrown");
        // After _db.commit the concurrent update will be performed.
        // and we need to undo it.
        _conn
            .createStatement()
            .execute(
                "UPDATE tc0x_sample SET value1='" + JDO_VALUE + "' WHERE id=" + Sample.DEFAULT_ID);
      } catch (ObjectModifiedException ex) {
        _db.rollback();
        LOG.error("Error: ObjectModifiedException thrown");
        fail("ObjectModifiedException not thrown");
      }
    }
  }
Ejemplo n.º 16
0
        public void run() {
            try {
                int num = 0;
                stream.writeVerbose("start testing");
                TestRace tr;
                TestRace testrace;
                OQLQuery oql;
                QueryResults qr;
                boolean succeed;
                int trials;
                Integer id = new Integer(5);

                out:
                for ( int i=0; i<trial; i++ ) {
                    // create, modified, delete object
                    try {
                        switch ( cachetype ) {
                        case 0:
                            testrace = new TestRaceCount();
                            testrace.setId(5);
                            break;
                        case 1:
                            testrace = new TestRaceTime();
                            testrace.setId(5);
                            break;
                        case 2:
                            testrace = new TestRaceNone();
                            testrace.setId(5);
                            break;
                        case 3:
                            testrace = new TestRaceUnlimited();
                            testrace.setId(5);
                            break;
                        default:
                            testrace = null;
                        }
     
                        // create object
                        //try {
                            db.begin();
                            db.create( testrace );  // may throw duplicateIdentityException
                            db.commit();
                        //} catch ( Exception e ) {
                        //    e.printStackTrace();
                        //}

                        // load it and modify it
                        succeed = false;
                        trials = 0;
                        while ( !succeed && trials < NUM_OF_RETRIAL ) {
                            Thread.currentThread().sleep( 0 );
                            trials++;
                            try {
                                db.begin();
                                tr = (TestRace) db.load( _classType, id );
                                                    // may throw ObjectNotFoundException
                                                    // LockNotGrantedException
                                tr.incValue1();
                                db.commit();
                                succeed = true;
                            } catch ( LockNotGrantedException e ) {
                                succeed = false;
                                // ethernet way of retry
                                if ( db.isActive() ) db.rollback();
                                Thread.currentThread().sleep( (long) ((SLEEP_BASE_TIME^trials) * ran.nextDouble()) );
                            } catch ( TransactionAbortedException e ) {
                                succeed = false;
                                // ethernet way of retry
                                if ( db.isActive() ) db.rollback();
                                Thread.currentThread().sleep( (long) ((SLEEP_BASE_TIME^trials) * ran.nextDouble()) );
                            } 
                        }
                        if ( db.isActive() ) 
                            db.rollback();

                        // load it and release it
                        succeed = false;
                        trials = 0;
                        while ( !succeed && trials < NUM_OF_RETRIAL ) {
                            Thread.currentThread().sleep( 0 );
                            trials++;
                            try {
                                db.begin();
                                tr = (TestRace) db.load( _classType, id );
                                                    // may throw ObjectNotFoundException
                                                    // LockNotGrantedException
                                db.commit();
                                succeed = true;
                            } catch ( LockNotGrantedException e ) {
                                succeed = false;
                                // ethernet way of retry
                                if ( db.isActive() ) db.rollback();
                                Thread.currentThread().sleep( (long) ((SLEEP_BASE_TIME^trials) * ran.nextDouble()) );
                            } 
                        }
                        if ( db.isActive() ) 
                            db.rollback();

                        // load it and delete it
                        succeed = false;
                        trials = 0;
                        while ( !succeed && trials < NUM_OF_RETRIAL ) {
                            Thread.currentThread().sleep( 0 );
                            trials++;    
                            try {
                                db.begin();
                                tr = (TestRace) db.load( _classType, id );
                                                // may throw ObjectNotFoundException
                                                // LockNotGrantedException
                                db.remove( tr );
                                db.commit();
                                succeed = true;
                            } catch ( LockNotGrantedException e ) {
                                succeed = false;
                                if ( db.isActive() ) db.rollback();
                                Thread.currentThread().sleep( (long) ((SLEEP_BASE_TIME^trials) * ran.nextDouble()) );
                            } catch ( TransactionAbortedException e ) {
                                succeed = false;
                                // ethernet way of retry
                                if ( db.isActive() ) db.rollback();
                                Thread.currentThread().sleep( (long) ((SLEEP_BASE_TIME^trials) * ran.nextDouble()) );
                            }
                        }
                        if ( db.isActive() ) 
                            db.rollback();
                        if ( !succeed )
                            throw new Exception("Transaction can't not lock the object within "+trials+" trials");

                    } catch ( TransactionNotInProgressException e ) {
                        stream.writeVerbose( "Thread <CreateDelete> will be killed. Unexcepted exception: "+e.getException() );
                        e.printStackTrace();
                        if ( db.isActive() ) try { db.rollback(); } catch ( TransactionNotInProgressException ee ) {}
                        _errLeak = true;
                        break out;
                    } catch ( PersistenceException e ) {
                        stream.writeVerbose( "Thread <CreateDelete> will be killed. Unexcepted exception: " );
                        e.printStackTrace();
                        if ( db.isActive() ) try { db.rollback(); } catch ( TransactionNotInProgressException ee ) {}
                        _errLeak = true;
                        break out;
                    } catch ( Exception e ) {
                        stream.writeVerbose( "Thread <CreateDelete> will be killed. Element not found: other exception: "+e );
                        e.printStackTrace();
                        if ( db.isActive() ) try { db.rollback(); } catch ( TransactionNotInProgressException ee ) {}
                        _errLeak = true;
                        break out;
                    }
                }

            } finally {
                isDone = true;
            }
        }
Ejemplo n.º 17
0
  public void testComplex() throws PersistenceException, SQLException {

    stream.println("Running testComplex...");

    Complex fullname = new Complex("First", "Person");

    // set up the data object
    _db.begin();
    TestLazyEmployee loadPerson = (TestLazyEmployee) _db.load(TestLazyEmployee.class, fullname);
    Collection projects = loadPerson.getProjects();

    TestLazyProject project = new TestLazyProject();
    project.setId(1001);
    project.setName("Project One");
    project.setOwner(loadPerson);
    projects.add(project);
    _db.create(project);

    project = new TestLazyProject();
    project.setId(1002);
    project.setName("Project Two");
    project.setOwner(loadPerson);
    projects.add(project);
    _db.create(project);

    project = new TestLazyProject();
    project.setId(1003);
    project.setName("Project Three");
    project.setOwner(loadPerson);
    projects.add(project);
    _db.create(project);

    _db.commit();

    // reload and test bug 823
    _db.begin();
    project = (TestLazyProject) _db.load(TestLazyProject.class, new Integer(1002));
    _db.remove(project);

    loadPerson = (TestLazyEmployee) _db.load(TestLazyEmployee.class, fullname);
    projects = loadPerson.getProjects();

    Iterator itor = projects.iterator();
    while (itor.hasNext()) {
      project = (TestLazyProject) itor.next();
      if (project.getId() == 1002) {
        itor.remove();
        break;
      }
    }

    itor = projects.iterator();
    while (itor.hasNext()) {
      project = (TestLazyProject) itor.next();
      if (project.getId() == 1002) {
        itor.remove();
        break;
      }
    }
    _db.commit();

    // reload and make sure the cache is consistent
    _db.begin();
    loadPerson = (TestLazyEmployee) _db.load(TestLazyEmployee.class, fullname);
    projects = loadPerson.getProjects();
    itor = projects.iterator();
    int id1 = 0;
    if (itor.hasNext()) {
      project = (TestLazyProject) itor.next();
      id1 = project.getId();
      if (project.getId() != 1001 && project.getId() != 1003) {
        stream.println("Error: found project1 with unexpected id " + project.getId());
        fail("Error: found project1 with unexpected id " + project.getId());
      }
    } else {
      stream.println("Error: expected project is not found");
      fail("Error: expected project is not found");
    }

    if (itor.hasNext()) {
      project = (TestLazyProject) itor.next();
      if (project.getId() == id1 || (project.getId() != 1001 && project.getId() != 1003)) {
        stream.println("Error: found project2 with unexpected id " + project.getId());
        fail("Error: found project2 with unexpected id " + project.getId());
      }
    } else {
      stream.println("Error: expected project is not found");
      fail("Error: expected project is not found");
    }

    if (itor.hasNext()) {
      project = (TestLazyProject) itor.next();
      stream.println("Error: unexpected project is found: " + project.getId());
      fail("Error: unexpected project is found: " + project.getId());
    }
    _db.commit();
  }
Ejemplo n.º 18
0
  public void createDataObjects() throws PersistenceException, SQLException {

    _db.begin();
    // create person 1
    TestLazyEmployee person = new TestLazyEmployee();
    person.setFirstName("First");
    person.setLastName("Person");
    person.setBirthday(new Date(1922, 2, 2));
    person.setStartDate(new Date(2000, 2, 2));

    TestLazyAddress address1 = new TestLazyAddress();
    address1.setId(1);
    address1.setStreet("#1 Address Street");
    address1.setCity("First City");
    address1.setState("AB");
    address1.setZip("10000");
    address1.setPerson(person);

    TestLazyAddress address2 = new TestLazyAddress();
    address2.setId(2);
    address2.setStreet("2nd Ave");
    address2.setCity("Second City");
    address2.setState("BC");
    address2.setZip("22222");
    address2.setPerson(person);

    TestLazyAddress address3 = new TestLazyAddress();
    address3.setId(3);
    address3.setStreet("3rd Court");
    address3.setCity("Third Ave");
    address3.setState("AB");
    address3.setZip("30003");
    address3.setPerson(person);

    ArrayList addresslist = new ArrayList();
    addresslist.add(address1);
    addresslist.add(address2);
    addresslist.add(address3);

    person.setAddress(addresslist);

    TestLazyPayRoll pr1 = new TestLazyPayRoll();
    pr1.setId(1);
    pr1.setHoliday(15);
    pr1.setHourlyRate(25);
    pr1.setEmployee(person);
    person.setPayRoll(pr1);

    TestLazyContractCategory cc = new TestLazyContractCategory();
    cc.setId(101);
    cc.setName("Full-time slave");
    _db.create(cc);

    TestLazyContractCategory cc2 = new TestLazyContractCategory();
    cc2.setId(102);
    cc2.setName("Full-time employee");
    _db.create(cc2);
    ArrayList category = new ArrayList();
    category.add(cc);
    category.add(cc2);

    TestLazyContract con = new TestLazyContract();
    con.setPolicyNo(1001);
    con.setComment(
        "80 hours a week, no pay hoilday, no sick leave, arrive office at 7:30am everyday");
    con.setContractNo(78);
    con.setEmployee(person);
    con.setCategory(category);
    person.setContract(con);
    _db.create(person);
    _db.commit();
  }
Ejemplo n.º 19
0
  public void runOnce(Class masterClass) throws PersistenceException, SQLException, Exception {

    String masterName = masterClass.getName();

    stream.println("Running...");
    stream.println("");

    // delete everything
    _conn.createStatement().executeUpdate("DELETE FROM test_col");
    _conn.createStatement().executeUpdate("DELETE FROM test_item");
    _conn.commit();

    // create new TestCol object with elements
    _db.begin();
    TestCol testCol = (TestCol) masterClass.newInstance();
    testCol.setId(1);
    _db.create(testCol);
    for (int i = 0; i < 5; i++) {
      TestItem newItem = new TestItem(100 + i);
      testCol.addItem(newItem);
      _db.create(newItem);
    }
    _db.commit();

    // test if object created properly
    _db.begin();
    testCol = (TestCol) _db.load(masterClass, new Integer(1));
    if (testCol == null) fail("Object creation failed!");

    if (testCol.itemSize() != 5
        || !testCol.containsItem(new TestItem(100))
        || !testCol.containsItem(new TestItem(101))
        || !testCol.containsItem(new TestItem(102))
        || !testCol.containsItem(new TestItem(103))
        || !testCol.containsItem(new TestItem(104))) fail("Related objects creation failed!");

    testCol.removeItem(new TestItem(100));
    testCol.removeItem(new TestItem(103));
    TestItem newItem = new TestItem(106);
    testCol.addItem(newItem);
    _db.create(newItem);
    newItem = new TestItem(107);
    testCol.addItem(newItem);
    _db.create(newItem);
    _db.commit();

    // test if add and remove work properly.
    _db.begin();
    testCol = (TestCol) _db.load(masterClass, new Integer(1));
    if (testCol == null) fail("Object add/remove failed! " + testCol);

    if (testCol.itemSize() != 5
        || !testCol.containsItem(new TestItem(106))
        || !testCol.containsItem(new TestItem(101))
        || !testCol.containsItem(new TestItem(102))
        || !testCol.containsItem(new TestItem(107))
        || !testCol.containsItem(new TestItem(104))) fail("Related add/remove failed!" + testCol);

    // test if add and remove rollback properly.
    testCol.removeItem(new TestItem(102));
    testCol.removeItem(new TestItem(104));
    newItem = new TestItem(108);
    testCol.addItem(newItem);
    newItem = new TestItem(109);
    testCol.addItem(newItem);
    _db.create(newItem);
    _db.rollback();

    if (testCol.itemSize() != 5
        || !testCol.containsItem(new TestItem(106))
        || !testCol.containsItem(new TestItem(101))
        || !testCol.containsItem(new TestItem(102))
        || !testCol.containsItem(new TestItem(107))
        || !testCol.containsItem(new TestItem(104)))
      fail("Related add/remove rollback failed!" + testCol);

    // shoud test for update too
  }
Ejemplo n.º 20
0
  public void runTest() throws PersistenceException, SQLException {

    stream.println("Running...");
    stream.println("");

    // delete everything
    _conn.createStatement().executeUpdate("DELETE test_serial");
    _conn.commit();

    // create new object with an serializable dependent object
    _db.begin();
    TestSerial master = new TestSerial();
    master.setId(1);
    master.setSerializableObject(new TestSerializableObject());
    master.getSerializableObject().aCoolString = "Very cool!";
    master.getSerializableObject().ints = new int[] {1, 3, 5, 7, 9};
    _db.create(master);
    _db.commit();

    // test if object created properly
    _db.begin();
    TestSerial testSerial = (TestSerial) _db.load(TestSerial.class, new Integer(1));
    if (testSerial == null) fail("Object creation failed!");

    if (testSerial.getSerializableObject() == null
        || !testSerial.getSerializableObject().aCoolString.equals("Very cool!")
        || testSerial.getSerializableObject().ints == null
        || testSerial.getSerializableObject().ints.length != 5
        || testSerial.getSerializableObject().ints[0] != 1
        || testSerial.getSerializableObject().ints[1] != 3
        || testSerial.getSerializableObject().ints[2] != 5
        || testSerial.getSerializableObject().ints[3] != 7
        || testSerial.getSerializableObject().ints[4] != 9)
      fail("dependent objects creation failed!" + testSerial);

    // modify the object
    testSerial.getSerializableObject().ints[1] = 103;
    testSerial.getSerializableObject().ints[3] = 107;
    testSerial.getSerializableObject().aCoolString = "Very very cool!";
    _db.commit();

    _db.begin();
    testSerial = (TestSerial) _db.load(TestSerial.class, new Integer(1));
    if (testSerial == null) fail("dependent modfiication failed!" + testSerial);

    if (testSerial.getSerializableObject() == null
        || !testSerial.getSerializableObject().aCoolString.equals("Very very cool!")
        || testSerial.getSerializableObject().ints == null
        || testSerial.getSerializableObject().ints.length != 5
        || testSerial.getSerializableObject().ints[0] != 1
        || testSerial.getSerializableObject().ints[1] != 103
        || testSerial.getSerializableObject().ints[2] != 5
        || testSerial.getSerializableObject().ints[3] != 107
        || testSerial.getSerializableObject().ints[4] != 9)
      fail("dependent modification failed!" + testSerial);

    // set the field to null;
    testSerial.getSerializableObject().ints = null;
    testSerial.getSerializableObject().aCoolString = null;
    _db.commit();

    _db.begin();
    testSerial = (TestSerial) _db.load(TestSerial.class, new Integer(1));
    if (testSerial == null) fail("dependent modfiication failed!" + testSerial);

    if (testSerial.getSerializableObject() == null
        || testSerial.getSerializableObject().aCoolString != null
        || testSerial.getSerializableObject().ints != null)
      fail("dependent modification failed!" + testSerial);

    // setSerializableObject( null );
    testSerial.setSerializableObject(null);
    _db.commit();

    _db.begin();
    testSerial = (TestSerial) _db.load(TestSerial.class, new Integer(1));
    if (testSerial == null) fail("dependent modfiication failed!" + testSerial);

    if (testSerial.getSerializableObject() != null)
      fail("dependent modification failed!" + testSerial);
    _db.commit();
  }
Ejemplo n.º 21
0
  public void runTest() throws PersistenceException {
    TimeStampableObject object;
    CallbacksInvoked cbi = new CallbacksInvoked();

    cbi.allow(CallbacksInvoked.CREATING);
    cbi.allow(CallbacksInvoked.USING);
    cbi.allow(CallbacksInvoked.CREATED);
    cbi.allow(CallbacksInvoked.STORING);
    cbi.allow(CallbacksInvoked.RELEASING);

    _i._callbacksInvoked.init();
    _db.begin();

    object = new TimeStampableObject();
    LOG.debug("Creating new object: " + object);
    _db.create(object);

    _db.commit();

    if (!cbi.equals(_i._callbacksInvoked)) {
      LOG.error("Callbacks were not properly invoked: " + cbi + " != " + _i._callbacksInvoked);
      fail("Callbacks were not properly invoked: " + cbi + " != " + _i._callbacksInvoked);
    }

    cbi.init();
    cbi.allow(CallbacksInvoked.USING);
    cbi.allow(CallbacksInvoked.LOADED);
    cbi.allow(CallbacksInvoked.STORING);
    cbi.allow(CallbacksInvoked.RELEASING);
    cbi.allow(CallbacksInvoked.INSTANTIATE);

    _i._callbacksInvoked.init();
    _db.begin();

    object =
        (TimeStampableObject)
            _db.load(TimeStampableObject.class, new Integer(TimeStampableObject.DEFAULT_ID));
    object.setValue1("Alan");

    _db.commit();

    if (!cbi.equals(_i._callbacksInvoked)) {
      LOG.error("Callbacks were not properly invoked: " + cbi + " != " + _i._callbacksInvoked);
      fail("Callbacks were not properly invoked: " + cbi + " != " + _i._callbacksInvoked);
    }

    cbi.init();
    cbi.allow(CallbacksInvoked.USING);
    cbi.allow(CallbacksInvoked.UPDATED);
    cbi.allow(CallbacksInvoked.STORING);
    cbi.allow(CallbacksInvoked.RELEASING);

    _i._callbacksInvoked.init();

    object.setValue2("long transaction new value");
    _db.begin();
    _db.update(object);
    _db.commit();

    if (!cbi.equals(_i._callbacksInvoked)) {
      LOG.error("Callbacks were not properly invoked: " + cbi + " != " + _i._callbacksInvoked);
      fail("Callbacks were not properly invoked: " + cbi + " != " + _i._callbacksInvoked);
    }

    cbi.init();
    cbi.allow(CallbacksInvoked.USING);
    cbi.allow(CallbacksInvoked.LOADED);
    cbi.allow(CallbacksInvoked.REMOVING);
    cbi.allow(CallbacksInvoked.REMOVED);
    cbi.allow(CallbacksInvoked.RELEASING);
    cbi.allow(CallbacksInvoked.INSTANTIATE);

    _i._callbacksInvoked.init();
    _db.begin();

    object =
        (TimeStampableObject)
            _db.load(TimeStampableObject.class, new Integer(TimeStampableObject.DEFAULT_ID));
    _db.remove(object);

    _db.commit();

    if (!cbi.equals(_i._callbacksInvoked)) {
      LOG.error("Callbacks were not properly invoked: " + cbi + " != " + _i._callbacksInvoked);
      fail("Callbacks were not properly invoked: " + cbi + " != " + _i._callbacksInvoked);
    }
  }
Ejemplo n.º 22
0
  public boolean run(CWVerboseStream stream) {
    try {

      _db = _category.getDatabase(stream.verbose());
      _conn = _category.getJDBCConnection();

      stream.writeVerbose("Running...");
      stream.writeVerbose("");

      // delete everything
      _conn.createStatement().executeUpdate("DELETE test_serial");
      _conn.commit();

      // create new object with an serializable dependent object
      _db.begin();
      TestSerial master = new TestSerial();
      master.setId(1);
      master.setSerializableObject(new TestSerializableObject());
      master.getSerializableObject().aCoolString = "Very cool!";
      master.getSerializableObject().ints = new int[] {1, 3, 5, 7, 9};
      _db.create(master);
      _db.commit();

      // test if object created properly
      _db.begin();
      TestSerial testSerial = (TestSerial) _db.load(TestSerial.class, new Integer(1));
      if (testSerial == null) throw new Exception("Object creation failed!");

      if (testSerial.getSerializableObject() == null
          || !testSerial.getSerializableObject().aCoolString.equals("Very cool!")
          || testSerial.getSerializableObject().ints == null
          || testSerial.getSerializableObject().ints.length != 5
          || testSerial.getSerializableObject().ints[0] != 1
          || testSerial.getSerializableObject().ints[1] != 3
          || testSerial.getSerializableObject().ints[2] != 5
          || testSerial.getSerializableObject().ints[3] != 7
          || testSerial.getSerializableObject().ints[4] != 9)
        throw new Exception("dependent objects creation failed!" + testSerial);

      // modify the object
      testSerial.getSerializableObject().ints[1] = 103;
      testSerial.getSerializableObject().ints[3] = 107;
      testSerial.getSerializableObject().aCoolString = "Very very cool!";
      _db.commit();

      _db.begin();
      testSerial = (TestSerial) _db.load(TestSerial.class, new Integer(1));
      if (testSerial == null) throw new Exception("dependent modfiication failed!" + testSerial);

      if (testSerial.getSerializableObject() == null
          || !testSerial.getSerializableObject().aCoolString.equals("Very very cool!")
          || testSerial.getSerializableObject().ints == null
          || testSerial.getSerializableObject().ints.length != 5
          || testSerial.getSerializableObject().ints[0] != 1
          || testSerial.getSerializableObject().ints[1] != 103
          || testSerial.getSerializableObject().ints[2] != 5
          || testSerial.getSerializableObject().ints[3] != 107
          || testSerial.getSerializableObject().ints[4] != 9)
        throw new Exception("dependent modification failed!" + testSerial);

      // set the field to null;
      testSerial.getSerializableObject().ints = null;
      testSerial.getSerializableObject().aCoolString = null;
      _db.commit();

      _db.begin();
      testSerial = (TestSerial) _db.load(TestSerial.class, new Integer(1));
      if (testSerial == null) throw new Exception("dependent modfiication failed!" + testSerial);

      if (testSerial.getSerializableObject() == null
          || testSerial.getSerializableObject().aCoolString != null
          || testSerial.getSerializableObject().ints != null)
        throw new Exception("dependent modification failed!" + testSerial);

      // setSerializableObject( null );
      testSerial.setSerializableObject(null);
      _db.commit();

      _db.begin();
      testSerial = (TestSerial) _db.load(TestSerial.class, new Integer(1));
      if (testSerial == null) throw new Exception("dependent modfiication failed!" + testSerial);

      if (testSerial.getSerializableObject() != null)
        throw new Exception("dependent modification failed!" + testSerial);
      _db.commit();

    } catch (Exception e) {
      e.printStackTrace();

      stream.writeVerbose("Exception: " + e);
      try {
        if (_db.isActive()) _db.close();
        return false;
      } catch (Exception ex) {
        return false;
      }
    }
    return true;
  }