/**
   * unlocks this instance for the given instance and state
   *
   * @param state state that have to be locked
   * @param user the locking user
   */
  public void unlock(ProcessInstance instance, State state, User user) throws WorkflowException {
    Database db = null;

    try {
      // Get database connection
      db = WorkflowJDOManager.getDatabase();

      // begin transaction
      db.begin();

      // Re-load process instance
      UpdatableProcessInstance copyInstance =
          (UpdatableProcessInstance) db.load(ProcessInstanceImpl.class, instance.getInstanceId());

      // Do workflow stuff
      try {
        // unlock instance for user
        copyInstance.unLock(state, user);
      } catch (WorkflowException we) {
        db.rollback();
        throw new WorkflowException(
            "ProcessInstanceManagerImpl.unlock", "workflowEngine.EX_ERR_UNLOCK", we);
      }

      // commit
      db.commit();
    } catch (PersistenceException pe) {
      throw new WorkflowException(
          "ProcessInstanceManagerImpl.unlock", "workflowEngine.EX_ERR_CASTOR_UNLOCK", pe);
    } finally {
      WorkflowJDOManager.closeDatabase(db);
    }
  }
Example #2
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");
    }
  }
Example #3
0
 public void run() {
     boolean succeed;
     int trials = 0;
     TestRace tr;
     try {
         for ( int i=0; i < trial && !other.isDone(); i++ ) {
             try {
                 // load it and modify it
                 db.begin();
                 succeed = false;
                 trials = 0;
                 while ( !succeed && trials < NUM_OF_RETRIAL && !other.isDone() ) {
                     trials++;
                     try {
                         tr = (TestRace) db.load( _classType, id, Database.Shared );
                                             // may throw ObjectNotFoundException
                                             // LockNotGrantedException
                         db.commit();
                         succeed = true;
                     } catch ( LockNotGrantedException e ) {
                         succeed = false;
                         // ethernet way of retry
                         Thread.currentThread().sleep( (long) ((SLEEP_BASE_TIME^trials) * ran.nextDouble()) );
                     } catch ( ObjectNotFoundException e ) {
                         succeed = false;
                         // ethernet way of retry
                         Thread.currentThread().sleep( (long) ((SLEEP_BASE_TIME^trials) * ran.nextDouble()) );
                     } catch ( TransactionAbortedException e ) {
                         succeed = false;
                         // ethernet way of retry
                         Thread.currentThread().sleep( (long) ((SLEEP_BASE_TIME^trials) * ran.nextDouble()) );
                     }
                     Thread.currentThread().sleep( 0 );
                 }
                 if ( db.isActive() ) 
                     db.rollback();
             
             } catch ( Exception e ) {
             }
         }
     } finally {
         isDone = true;
     }
 }
Example #4
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);
  }
Example #5
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();
  }
Example #6
0
  public void tearDown() throws PersistenceException {
    if (_db.isActive()) {
      _db.rollback();
    }

    OQLQuery oql;
    QueryResults qres;

    LOG.debug("Delete everything");
    _db.begin();
    oql =
        _db.getOQLQuery("SELECT p FROM " + TimeStampableObject.class.getName() + " p WHERE id=$1");
    oql.bind(TimeStampableObject.DEFAULT_ID);
    qres = oql.execute();
    while (qres.hasMore()) {
      _db.remove(qres.next());
    }
    oql.close();
    _db.commit();

    _db.close();

    _jdo.setCallbackInterceptor(null);
  }
Example #7
0
 public void tearDown() throws Exception {
   if (_db.isActive()) {
     _db.rollback();
   }
   _db.close();
 }
Example #8
0
 /** Close the database and JDBC connection */
 public void tearDown() throws PersistenceException, SQLException {
   if (_db.isActive()) {
     _db.rollback();
   }
   _db.close();
 }
Example #9
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");
      }
    }
  }
Example #10
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;
            }
        }
Example #11
0
  public void testIterWithDelete() throws PersistenceException, SQLException {

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

    // Tests iterating over a lazy-loaded Collection that has
    // had data deleted
    Complex fullname = new Complex("First", "Person");

    // First add a record, then commit
    _db.begin();
    TestLazyEmployee loadPerson = (TestLazyEmployee) _db.load(TestLazyEmployee.class, fullname);
    Collection addresses = loadPerson.getAddress();
    TestLazyAddress la = new TestLazyAddress();
    la.setId(999);
    la.setStreet("Rogue Street");
    la.setCity("Rogue City");
    la.setState("RS");
    la.setZip("10666");
    la.setPerson(loadPerson);
    addresses.add(la);
    _db.commit();

    // New transaction
    _db.begin();

    ArrayList masterData = new ArrayList();

    // test java.util.Collection.clear() for lazy loading (bug 801)
    loadPerson = (TestLazyEmployee) _db.load(TestLazyEmployee.class, fullname);

    addresses = loadPerson.getAddress();
    // Store the list in the database at the start of the transaction,
    // for comparison purposes.  Select a victim for deletion.
    Iterator it = addresses.iterator();
    // victim is last element to test bug 1022
    int victim = addresses.size() - 1;
    int recNo = 0;
    TestLazyAddress victimAddr = null;
    while (it.hasNext()) {
      TestLazyAddress addr = (TestLazyAddress) it.next();
      if (recNo++ == victim) {
        victimAddr = addr;
      } else {
        masterData.add(addr);
      }
    }

    // The expected number of items to iterate over
    int collSize = addresses.size();

    _db.rollback();

    // Now start over, and add something to the collection.  Then try
    // iterating and clearing the collection
    _db.begin();
    loadPerson = (TestLazyEmployee) _db.load(TestLazyEmployee.class, fullname);
    addresses = loadPerson.getAddress();
    addresses.remove(victimAddr);

    Iterator it2 = addresses.iterator();

    while (it2.hasNext()) {

      TestLazyAddress addr = (TestLazyAddress) it2.next();
      if (addr.equals(victimAddr)) {
        stream.println("Error: Deleted record should not show up in iteration");
        fail("Error: Deleted record should not show up in iteration");
      } else {

        if (!masterData.remove(addr)) {
          stream.println("Error: unrecognized element from list in testIterWithDelete");
          fail("Error: unrecognized element from list in testIterWithDelete");
        }
      }
    }

    _db.rollback();

    if (!masterData.isEmpty()) {
      stream.println("Error: iteration/deletion failed in testIterWithDelete");
      fail("Error: iteration/deletion failed in testIterWithDelete");
    }
  }
Example #12
0
  public void testIterWithAdd() throws PersistenceException, SQLException {

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

    // Tests iterating over a lazy-loaded Collection that has
    // had data added

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

    // test java.util.Collection.clear() for lazy loading (bug 801)
    _db.begin();
    TestLazyPerson loadPerson = (TestLazyEmployee) _db.load(TestLazyEmployee.class, fullname);

    Collection addresses = loadPerson.getAddress();
    // Store the list in the database at the start of the transaction,
    // for comparison purposes
    Iterator it = addresses.iterator();
    while (it.hasNext()) {
      masterData.add(it.next());
    }

    _db.rollback();

    // Now start over, and add something to the collection.  Then try
    // iterating and clearing the collection
    _db.begin();
    loadPerson = (TestLazyEmployee) _db.load(TestLazyEmployee.class, fullname);
    addresses = loadPerson.getAddress();
    int collSize = addresses.size();
    TestLazyAddress la = new TestLazyAddress();
    la.setId(999);
    la.setStreet("Rogue Street");
    la.setCity("Rogue City");
    la.setState("RS");
    la.setZip("10666");
    la.setPerson(loadPerson);
    addresses.add(la);

    // bruce
    stream.println("masterData size: " + masterData.size());
    stream.println(" addresses size: " + addresses.size());

    if (addresses.size() != masterData.size() + 1)
      fail("Lazy collection size is different from what is expected");

    boolean matchNewElement = false;
    int matchCount = 0;

    it = addresses.iterator();

    /*
     * The problem with the following block is that the second loop is
     * entered but never exited.
     *
     */

    bigloop:
    while (it.hasNext()) {
      TestLazyAddress addr = (TestLazyAddress) it.next();

      Iterator it2 = masterData.iterator();
      while (it2.hasNext()) {
        TestLazyAddress addr2 = (TestLazyAddress) it2.next();

        stream.println(" addr: " + addr);
        stream.println("addr2: " + addr2);

        if (addr2.equals(addr)) {
          stream.println("matched");
          matchCount++;
          continue bigloop;
        } else if (addr == la) {
          stream.println("matched lazy");
          matchNewElement = true;
          matchCount++;
          continue bigloop;
        } else {
          stream.println("no match");
        }
      }
      stream.println("newly added:" + la + "@" + System.identityHashCode(la));
      stream.println("matchNewElement " + matchNewElement);
      stream.println("matchCount " + matchCount);

      fail(
          "found unexpected address in the new lazy collection:"
              + addr
              + "@"
              + System.identityHashCode(la));
    }

    if (!matchNewElement) fail("Newly added element is missing");

    if (matchCount != (masterData.size() + 1))
      fail(
          "Lazy collection contains unexpected number of elements. expected: "
              + (masterData.size() + 1)
              + " found: "
              + matchCount);

    addresses.clear();
    if (!addresses.isEmpty()) {
      stream.println("Error: clear failed in testIterWithAdd");
      fail("Error: clear failed in testIterWithAdd");
    }

    _db.rollback();
  }
Example #13
0
  public void testGeneral() throws PersistenceException, SQLException {

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

    _db.begin();
    Complex fullname = new Complex("First", "Person");

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

    if (loadPerson.getBirthday().equals(new Date(1922, 2, 2))
        && loadPerson.getFirstName().equals("First")
        && loadPerson.getLastName().equals("Person")) {
      stream.println("OK: Employee is valid");

      Collection address = loadPerson.getAddress();
      Iterator itor = address.iterator();
      TestLazyAddress[] addresses = {null, null, null};
      TestLazyAddress addr;
      while (itor.hasNext()) {
        addr = (TestLazyAddress) itor.next();
        if (addr.getId() < 1 || addr.getId() > 3) {
          _db.rollback();
          stream.println("Error: Address id is incorrect");
          fail("address id is incorrect");
        }
        addresses[addr.getId() - 1] = addr;
      }

      if (addresses[0] == null
          || !addresses[0].getStreet().equals("#1 Address Street")
          || !addresses[0].getCity().equals("First City")
          || !addresses[0].getState().equals("AB")
          || !addresses[0].getZip().equals("10000")
          || addresses[0].getPerson() != loadPerson) {
        stream.println("Error: Address 1 is incorrect: " + addresses[0]);
        _db.rollback();
        fail("address 1 is incorrect");
      }
      stream.println("OK: Address 1 are valid");

      if (addresses[1] == null
          || !addresses[1].getStreet().equals("2nd Ave")
          || !addresses[1].getCity().equals("Second City")
          || !addresses[1].getState().equals("BC")
          || !addresses[1].getZip().equals("22222")
          || addresses[1].getPerson() != loadPerson) {
        stream.println("Error: Address 2 is incorrect");
        _db.rollback();
        fail("address 2 is incorrect");
      }
      stream.println("OK: Address 2 are valid");

      TestLazyPayRoll payroll = loadPerson.getPayRoll();
      if (payroll == null
          || payroll.getId() != 1
          || payroll.getHoliday() != 15
          || payroll.getEmployee() != loadPerson
          || payroll.getHourlyRate() != 25) {
        stream.println("Error: PayRoll loaded incorrect");
        _db.rollback();
        fail("payroll is incorrect");
      }
      stream.println("OK: PayRoll is valid");

      TestLazyContract cont = loadPerson.getContract();
      if (cont == null
          || cont.getPolicyNo() != 1001
          || cont.getEmployee() != loadPerson
          || cont.getContractNo() != 78) {
        stream.println("Error: Contract is not what expected!");
        stream.println(
            "employe==null? "
                + cont.getEmployee()
                + "/"
                + cont.getEmployee().getFirstName()
                + "/"
                + cont.getEmployee().getLastName());
        stream.println(
            "loadPerson? "
                + loadPerson
                + "/"
                + loadPerson.getFirstName()
                + "/"
                + loadPerson.getLastName());
        _db.rollback();
        fail("contract is incorrect");
      }
      stream.println("OK: Contract is valid");

      Collection catelist = cont.getCategory();
      itor = catelist.iterator();
      TestLazyContractCategory cate;
      while (itor.hasNext()) {
        cate = (TestLazyContractCategory) itor.next();
        if (cate.getId() == 101 && cate.getName().equals("Full-time slave")) {
        } else if (cate.getId() == 102 && cate.getName().equals("Full-time employee")) {
        } else {
          stream.println("Error: Category is incorrect");
          _db.rollback();
          fail("category is incorrect");
        }
      }
      stream.println("OK: Categories are valid");

      // now modified the object and store it
      address.remove(addresses[0]);
      addresses[1].setStreet("New Second Street");

    } else {
      _db.rollback();
      stream.println("Error: FirstName, LastName or Birthday is incorrect!");
      fail("FirstName, LastName or Birthday is incorrect!");
    }
    _db.commit();

    // test and see if changes made succeed
    _db.begin();
    loadPerson = (TestLazyEmployee) _db.load(TestLazyEmployee.class, fullname);

    if (loadPerson.getBirthday().equals(new Date(1922, 2, 2))
        && loadPerson.getFirstName().equals("First")
        && loadPerson.getLastName().equals("Person")) {
      stream.println("OK: Employee is valid");

      Collection address = loadPerson.getAddress();
      Iterator itor = address.iterator();
      TestLazyAddress[] addresses = {null, null, null};
      TestLazyAddress addr;
      while (itor.hasNext()) {
        addr = (TestLazyAddress) itor.next();
        if (addr.getId() < 1 || addr.getId() > 3) {
          _db.rollback();
          stream.println("Error: Address id is incorrect");
          fail("address id is incorrect");
        }
        addresses[addr.getId() - 1] = addr;
      }

      if (addresses[0] != null) {
        stream.println("Error: Address 1 is not deleted: " + addresses[0]);
        fail("address 1 is not deleted");
      }
      stream.println("OK: Address 1 is deleted");

      if (addresses[1] == null
          || !addresses[1].getStreet().equals("New Second Street")
          || !addresses[1].getCity().equals("Second City")
          || !addresses[1].getState().equals("BC")
          || !addresses[1].getZip().equals("22222")
          || addresses[1].getPerson() != loadPerson) {
        stream.println("Error: Address 2 is incorrect");
        _db.rollback();
        fail("address 2 is incorrect");
      }
      stream.println("OK: Address 2 are valid: " + addresses[1]);

      TestLazyPayRoll payroll = loadPerson.getPayRoll();
      if (payroll == null
          || payroll.getId() != 1
          || payroll.getHoliday() != 15
          || payroll.getEmployee() != loadPerson
          || payroll.getHourlyRate() != 25) {
        stream.println("Error: PayRoll loaded incorrect");
        _db.rollback();
        fail("payroll is incorrect");
      }
      stream.println("OK: PayRoll is valid");

      TestLazyContract cont = loadPerson.getContract();
      if (cont == null
          || cont.getPolicyNo() != 1001
          || cont.getEmployee() != loadPerson
          || cont.getContractNo() != 78) {
        stream.println("Error: Contract is not what expected!");
        stream.println(
            "employe==null? "
                + cont.getEmployee()
                + "/"
                + cont.getEmployee().getFirstName()
                + "/"
                + cont.getEmployee().getLastName());
        stream.println(
            "loadPerson? "
                + loadPerson
                + "/"
                + loadPerson.getFirstName()
                + "/"
                + loadPerson.getLastName());
        _db.rollback();
        fail("contract is incorrect");
      }
      stream.println("OK: Contract is valid");

      Collection catelist = cont.getCategory();
      itor = catelist.iterator();
      TestLazyContractCategory cate;
      while (itor.hasNext()) {
        cate = (TestLazyContractCategory) itor.next();
        if (cate.getId() == 101 && cate.getName().equals("Full-time slave")) {
        } else if (cate.getId() == 102 && cate.getName().equals("Full-time employee")) {
        } else {
          stream.println("Error: Category is incorrect");
          _db.rollback();
          fail("category is incorrect");
        }
      }
      stream.println("OK: Categories are valid");

    } else {
      _db.rollback();
      stream.println("Error: FirstName, LastName or Birthday is incorrect!");
      fail("FirstName, LastName or Birthday is incorrect!");
    }
    _db.commit();
  }
Example #14
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
  }