@Test
 public void testAdd() throws Exception {
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               assertTrue(set.add(1));
               assertFalse(set.add(1));
               set.remove(1);
               assertTrue(set.add(1));
               assertTrue(set.add(null));
               assertFalse(set.add(null));
             }
           }),
       taskOwner);
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               assertTrue(set.contains(1));
               assertTrue(set.contains(null));
               assertEquals(2, set.size());
             }
           }),
       taskOwner);
 }
 @Test
 public void testCopyConstructor() throws Exception {
   final Set<Integer> anotherSet = new HashSet<Integer>();
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               try {
                 new ScalableHashSet<Object>(null);
                 fail("Expected NullPointerException");
               } catch (NullPointerException e) {
               }
               anotherSet.add(null);
               anotherSet.add(1);
               anotherSet.add(2);
               set = new ScalableHashSet<Object>(anotherSet);
               assertEquals(anotherSet, set);
             }
           }),
       taskOwner);
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               assertEquals(anotherSet, set);
             }
           }),
       taskOwner);
 }
 @SuppressWarnings("unchecked")
 @Test
 public void testIterator() throws Exception {
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               set.add(null);
               set.add(1);
               set.add(2);
               Iterator<Object> iter = set.iterator();
               dataService.setBinding("iter", new ManagedSerializable(iter));
             }
           }),
       taskOwner);
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               ManagedSerializable<Iterator<Object>> msIter =
                   uncheckedCast(dataService.getBinding("iter"));
               dataService.markForUpdate(msIter);
               Iterator<Object> iter = msIter.get();
               int count = 0;
               while (iter.hasNext()) {
                 iter.next();
                 count++;
               }
               assertEquals(3, count);
             }
           }),
       taskOwner);
 }
 @Test
 public void testClear() throws Exception {
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               set.add(1);
               set.add(null);
               DoneRemoving.init();
               set.clear();
               assertTrue(set.isEmpty());
             }
           }),
       taskOwner);
   DoneRemoving.await(1);
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               set.clear();
               assertTrue(set.isEmpty());
             }
           }),
       taskOwner);
   DoneRemoving.await(1);
 }
 @Test
 public void testRemoveObjectNotFound() throws Exception {
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               set.add(one);
             }
           }),
       taskOwner);
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               dataService.removeObject(one);
               one = new Int(1);
               assertFalse(set.remove(one));
             }
           }),
       taskOwner);
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               assertFalse(set.remove(one));
             }
           }),
       taskOwner);
 }
 private void doTestRead(boolean detectMods) throws Exception {
   Properties props = getNodeProps();
   props.setProperty(DataServiceImplClass + ".detect.modifications", String.valueOf(detectMods));
   props.setProperty("com.sun.sgs.txn.timeout", "10000");
   serverNode = new SgsTestNode("TestDataServicePerformance", null, props);
   final DataService service = serverNode.getDataService();
   TransactionScheduler txnScheduler =
       serverNode.getSystemRegistry().getComponent(TransactionScheduler.class);
   Identity taskOwner = serverNode.getProxy().getCurrentOwner();
   txnScheduler.runTask(
       new AbstractKernelRunnable() {
         public void run() {
           service.setBinding("counters", new Counters(items));
         }
       },
       taskOwner);
   for (int r = 0; r < repeat; r++) {
     long start = System.currentTimeMillis();
     for (int c = 0; c < count; c++) {
       txnScheduler.runTask(
           new AbstractKernelRunnable() {
             public void run() throws Exception {
               Counters counters = (Counters) service.getBinding("counters");
               for (int i = 0; i < items; i++) {
                 counters.get(i);
               }
             }
           },
           taskOwner);
     }
     long stop = System.currentTimeMillis();
     System.err.println("Time: " + (stop - start) / (float) count + " ms per transaction");
   }
 }
 @Test
 public void testSizeObjectNotFound() throws Exception {
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               set.add(one);
             }
           }),
       taskOwner);
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               dataService.removeObject(one);
               assertEquals(1, set.size());
             }
           }),
       taskOwner);
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               assertEquals(1, set.size());
             }
           }),
       taskOwner);
 }
 @Test
 public void testEqualsObjectNotFound() throws Exception {
   final Set<Object> empty = new HashSet<Object>();
   final Set<Object> containsOne = new HashSet<Object>();
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               containsOne.add(one);
               set.add(one);
             }
           }),
       taskOwner);
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               dataService.removeObject(one);
               assertFalse(set.equals(empty));
               assertFalse(set.equals(containsOne));
             }
           }),
       taskOwner);
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               assertFalse(set.equals(empty));
               assertFalse(set.equals(containsOne));
             }
           }),
       taskOwner);
 }
  @Test
  public void testSampleLevel() throws Exception {
    final String name = "MySamples";
    ProfileCollector collector = getCollector(serverNode);
    ProfileConsumer cons1 = collector.getConsumer("cons1");
    final ProfileSample sample = cons1.registerSampleSource(name, true, -1, ProfileLevel.MAX);

    // Because the listener is running in a different thread, JUnit
    // is not able to report the assertions and failures.
    // Use an exchanger to synchronize between the threads and communicate
    // any problems.
    final Exchanger<AssertionError> errorExchanger = new Exchanger<AssertionError>();

    final List<Long> testValues = new ArrayList<Long>();
    testValues.add(101L);
    testValues.add(-22L);
    // The owner for our positive test.  The listener uses this owner
    // to find the ProfileReport for the task in this test.
    final Identity positiveOwner = new DummyIdentity("samplelevel");
    TestListener test =
        new TestListener(
            new TestSampleReport(
                name, positiveOwner,
                errorExchanger, testValues));
    profileCollector.addListener(test, true);
    txnScheduler.runTask(
        new TestAbstractKernelRunnable() {
          public void run() {
            // The default profile level is MIN so we don't expect
            // to see the samples.
            for (Long v : testValues) {
              sample.addSample(v);
            }
          }
        },
        taskOwner);

    AssertionError error = errorExchanger.exchange(null, 100, TimeUnit.MILLISECONDS);
    if (error != null) {
      throw new AssertionError(error);
    }

    cons1.setProfileLevel(ProfileLevel.MAX);
    txnScheduler.runTask(
        new TestAbstractKernelRunnable() {
          public void run() {
            // Because we bumped the consumer's profile level,
            // we expect the samples to appear
            for (Long v : testValues) {
              sample.addSample(v);
            }
          }
        },
        positiveOwner);

    error = errorExchanger.exchange(null, 100, TimeUnit.MILLISECONDS);
    if (error != null) {
      throw new AssertionError(error);
    }
  }
 @SuppressWarnings("unchecked")
 @Test
 public void testIteratorCollectionNotFound() throws Exception {
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               set.add(one);
               Iterator<Object> iter = set.iterator();
               dataService.setBinding("iter", new ManagedSerializable(iter));
             }
           }),
       taskOwner);
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               DoneRemoving.init();
               dataService.removeObject(set);
             }
           }),
       taskOwner);
   DoneRemoving.await(1);
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               ManagedSerializable<Iterator<Object>> msIter =
                   uncheckedCast(dataService.getBinding("iter"));
               dataService.markForUpdate(msIter);
               Iterator<Object> iter = msIter.get();
               try {
                 iter.next();
                 fail("Expected ObjectNotFoundException");
               } catch (ObjectNotFoundException e) {
                 System.err.println(e);
               }
               try {
                 iter.hasNext();
                 fail("Expected ObjectNotFoundException");
               } catch (ObjectNotFoundException e) {
                 System.err.println(e);
               }
               try {
                 iter.remove();
                 fail("Expected an exception");
               } catch (ObjectNotFoundException e) {
                 System.err.println(e);
               } catch (IllegalStateException e) {
                 System.err.println(e);
               }
             }
           }),
       taskOwner);
 }
  @Test
  public void testCounterLevel() throws Exception {
    final String name = "MyCounter";
    ProfileCollector collector = getCollector(serverNode);
    ProfileConsumer cons1 = collector.getConsumer("c1");
    // Register a counter to be updated only at the max level
    final ProfileCounter counter = cons1.registerCounter(name, true, ProfileLevel.MAX);

    // Because the listener is running in a different thread, JUnit
    // is not able to report the assertions and failures.
    // Use an exchanger to synchronize between the threads and communicate
    // any problems.
    final Exchanger<AssertionError> errorExchanger = new Exchanger<AssertionError>();

    // The owner for our positive test.  The listener uses this owner
    // to find the ProfileReport for the task in this test.
    final Identity positiveOwner = new DummyIdentity("counterlevel");
    TestListener test =
        new TestListener(new TestCounterReport(name, positiveOwner, errorExchanger, 1));
    profileCollector.addListener(test, true);

    txnScheduler.runTask(
        new TestAbstractKernelRunnable() {
          public void run() {
            // The default profile level is MIN so we don't expect
            // to see the counter incremented.
            counter.incrementCount();
          }
        },
        taskOwner);

    AssertionError error = errorExchanger.exchange(null, 100, TimeUnit.MILLISECONDS);
    if (error != null) {
      throw new AssertionError(error);
    }

    cons1.setProfileLevel(ProfileLevel.MAX);
    txnScheduler.runTask(
        new TestAbstractKernelRunnable() {
          public void run() {
            // Because we bumped the consumer's profile level,
            // we expect the counter
            counter.incrementCount();
          }
        },
        positiveOwner);

    error = errorExchanger.exchange(null, 100, TimeUnit.MILLISECONDS);
    if (error != null) {
      throw new AssertionError(error);
    }
  }
  @Test
  public void testCounter() throws Exception {
    final String name = "counter";
    ProfileCollector collector = getCollector(serverNode);
    ProfileConsumer cons1 = collector.getConsumer("c1");
    // Register a counter to be noted at all profiling levels
    final ProfileCounter counter = cons1.registerCounter(name, true, ProfileLevel.MIN);

    // Because the listener is running in a different thread, JUnit
    // is not able to report the assertions and failures.
    // Use an exchanger to synchronize between the threads and communicate
    // any problems.
    final Exchanger<AssertionError> errorExchanger = new Exchanger<AssertionError>();

    // The owner for our positive test.  The listener uses this owner
    // to find the ProfileReport for the task in this test.
    final Identity positiveOwner = new DummyIdentity("owner");
    TestListener test =
        new TestListener(new TestCounterReport(name, positiveOwner, errorExchanger, 1));
    profileCollector.addListener(test, true);

    // We run with the myOwner because we expect to see the
    // value in the test report.
    txnScheduler.runTask(
        new TestAbstractKernelRunnable() {
          public void run() {
            counter.incrementCount();
          }
        },
        positiveOwner);

    AssertionError error = errorExchanger.exchange(null, 100, TimeUnit.MILLISECONDS);
    if (error != null) {
      // Rethrow with the original error as the cause so we see
      // both stack traces.
      throw new AssertionError(error);
    }

    txnScheduler.runTask(
        new TestAbstractKernelRunnable() {
          public void run() {}
        },
        taskOwner);

    error = errorExchanger.exchange(null, 100, TimeUnit.MILLISECONDS);
    if (error != null) {
      throw new AssertionError(error);
    }
  }
  @Test
  public void testAddListenerCalled() throws Exception {
    final Semaphore flag = new Semaphore(1);

    SimpleTestListener test =
        new SimpleTestListener(
            new Runnable() {
              public void run() {
                flag.release();
              }
            });
    profileCollector.addListener(test, true);

    flag.acquire();
    // Run a task, to be sure our listener gets called at least once
    txnScheduler.runTask(
        new TestAbstractKernelRunnable() {
          // empty task
          public void run() {}
        },
        taskOwner);

    // Calling reports is asynchronous
    flag.tryAcquire(100, TimeUnit.MILLISECONDS);
    assertTrue(test.reportCalls > 0);
  }
 @Test
 public void testContainsAll() throws Exception {
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               try {
                 set.containsAll(null);
                 fail("Expected NullPointerException");
               } catch (NullPointerException e) {
               }
               Set<Object> other = new HashSet<Object>();
               assertTrue(set.containsAll(other));
               other.add(1);
               assertFalse(set.containsAll(other));
               set.add(null);
               set.add(1);
               assertTrue(set.containsAll(other));
               DoneRemoving.init();
               set.clear();
               assertFalse(set.containsAll(other));
             }
           }),
       taskOwner);
   DoneRemoving.await(1);
 }
 /** Returns the current number of objects, using its own transactions. */
 private int getObjectCount() throws Exception {
   final AtomicInteger countRef = new AtomicInteger(0);
   final AtomicReference<BigInteger> lastRef = new AtomicReference<BigInteger>();
   final AtomicBoolean done = new AtomicBoolean(false);
   while (!done.get()) {
     txnScheduler.runTask(
         new TestTask(
             new AbstractKernelRunnable() {
               public void run() {
                 BigInteger last = lastRef.get();
                 int count;
                 for (count = 0; count < 50; count++) {
                   BigInteger next = dataService.nextObjectId(last);
                   if (next == null) {
                     done.set(true);
                   }
                   last = next;
                 }
                 countRef.addAndGet(count);
                 lastRef.set(last);
               }
             }),
         taskOwner);
   }
   return countRef.get();
 }
 @Test
 public void testAddAll() throws Exception {
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               try {
                 set.addAll(null);
                 fail("Expected NullPointerException");
               } catch (NullPointerException e) {
               }
               set.add(1);
               set.add(2);
               set.add(3);
               Set<Object> other = new HashSet<Object>();
               other.add(null);
               other.add(3);
               other.add(4);
               other.add(5);
               set.addAll(other);
               assertEquals(6, set.size());
               set.contains(4);
               set.contains(5);
             }
           }),
       taskOwner);
 }
  @Test
  public void testOperationMediumToMaxLevel() throws Exception {
    ProfileCollector collector = getCollector(serverNode);
    ProfileConsumer cons1 = collector.getConsumer("c1");
    final ProfileOperation op = cons1.registerOperation("something", ProfileLevel.MEDIUM);

    // Because the listener is running in a different thread, JUnit
    // is not able to report the assertions and failures.
    // Use an exchanger to synchronize between the threads and communicate
    // any problems.
    final Exchanger<AssertionError> errorExchanger = new Exchanger<AssertionError>();

    // The owner for our positive test.  The listener uses this owner
    // to find the ProfileReport for the task in this test.
    final Identity positiveOwner = new DummyIdentity("opmedtomax");
    TestListener test =
        new TestListener(new TestOperationReport(op, positiveOwner, errorExchanger));
    profileCollector.addListener(test, true);

    txnScheduler.runTask(
        new TestAbstractKernelRunnable() {
          public void run() {
            // We do not expect to see this reported.
            op.report();
          }
        },
        taskOwner);

    AssertionError error = errorExchanger.exchange(null, 100, TimeUnit.MILLISECONDS);
    if (error != null) {
      throw new AssertionError(error);
    }

    cons1.setProfileLevel(ProfileLevel.MAX);
    txnScheduler.runTask(
        new TestAbstractKernelRunnable() {
          public void run() {
            op.report();
          }
        },
        positiveOwner);

    error = errorExchanger.exchange(null, 100, TimeUnit.MILLISECONDS);
    if (error != null) {
      throw new AssertionError(error);
    }
  }
 @Test
 public void testClearObjectNotFound() throws Exception {
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               set.add(one);
             }
           }),
       taskOwner);
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               dataService.removeObject(one);
               DoneRemoving.init();
               set.clear();
               assertTrue(set.isEmpty());
               one = new Int(1);
               set.add(one);
             }
           }),
       taskOwner);
   DoneRemoving.await(1);
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               dataService.removeObject(one);
             }
           }),
       taskOwner);
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               set.clear();
               assertTrue(set.isEmpty());
             }
           }),
       taskOwner);
   DoneRemoving.await(1);
 }
 @Test(expected = NullPointerException.class)
 public void testGetConflictWithNull() throws Exception {
   txnScheduler.runTask(
       new TestAbstractKernelRunnable() {
         public void run() throws Exception {
           accessCoordinator.getConflictingTransaction(null);
         }
       },
       taskOwner);
 }
  @Test(expected = NullPointerException.class)
  public void testAccessSourceNullType() throws Exception {
    txnScheduler.runTask(
        new TestAbstractKernelRunnable() {
          public void run() throws Exception {

            accessCoordinator.registerAccessSource("source", null);
          }
        },
        taskOwner);
  }
 @Test
 public void testRegisterAccessSource() throws Exception {
   txnScheduler.runTask(
       new TestAbstractKernelRunnable() {
         public void run() throws Exception {
           AccessReporter<Integer> reporter =
               accessCoordinator.registerAccessSource("test", Integer.class);
         }
       },
       taskOwner);
 }
 @Test
 public void testConstructorNoArg() throws Exception {
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               assertTrue(set.isEmpty());
             }
           }),
       taskOwner);
 }
 /** Per-test setup */
 @Before
 public void setUp() throws Exception {
   txnScheduler.runTask(
       new AbstractKernelRunnable() {
         public void run() throws Exception {
           set = new ScalableHashSet<Object>();
           one = new Int(1);
           endTransaction();
         }
       },
       taskOwner);
 }
 @Test(expected = NullPointerException.class)
 public void testAccessReporterNullTransaction2() throws Exception {
   txnScheduler.runTask(
       new TestAbstractKernelRunnable() {
         public void run() throws Exception {
           AccessReporter<Integer> reporter =
               accessCoordinator.registerAccessSource("test", Integer.class);
           reporter.reportObjectAccess(null, 1, AccessType.READ, "description");
         }
       },
       taskOwner);
 }
  @Test
  public void testRemoveAfterSerialization() throws Exception {

    final String SET_NAME = "test.remove.after.serialization";

    // store the set in the db

    txnScheduler.runTask(
        new TestTask(
            new AbstractKernelRunnable() {
              public void run() {
                assertFalse(set.remove(1));
                assertFalse(set.remove(null));
                set.add(1);
                set.add(null);
                dataService.setBinding(SET_NAME, set);
              }
            }),
        taskOwner);

    // next reload the set from the db to test for the correct
    // handling of the Marker flag.

    txnScheduler.runTask(
        new TestTask(
            new AbstractKernelRunnable() {
              public void run() {

                ScalableHashSet deserialized = (ScalableHashSet) (dataService.getBinding(SET_NAME));

                assertTrue(deserialized.remove(1));
                assertFalse(deserialized.contains(1));
                assertFalse(deserialized.remove(1));
                assertTrue(deserialized.remove(null));
                assertFalse(deserialized.contains(null));
                assertFalse(deserialized.remove(null));
              }
            }),
        taskOwner);
  }
 @SuppressWarnings("unchecked")
 @Test
 public void testIteratorRetainAcrossTransactions() throws Exception {
   final AtomicReference<Iterator<Object>> iterRef = new AtomicReference();
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               set.add(one);
               Iterator<Object> iter = set.iterator();
               iterRef.set(iter);
               dataService.setBinding("iter", new ManagedSerializable(iter));
             }
           }),
       taskOwner);
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               Iterator<Object> iter = iterRef.get();
               try {
                 iter.hasNext();
                 fail("Expected TransactionNotActiveException");
               } catch (TransactionNotActiveException e) {
               }
               try {
                 iter.next();
                 fail("Expected TransactionNotActiveException");
               } catch (TransactionNotActiveException e) {
               }
               try {
                 iter.remove();
                 fail("Expected IllegalStateException");
               } catch (IllegalStateException e) {
               }
             }
           }),
       taskOwner);
 }
  @Test(expected = NullPointerException.class)
  public void testAccessReporterNullValue() throws Exception {
    final AccessReporter<Integer> reporter =
        accessCoordinator.registerAccessSource("test", Integer.class);

    txnScheduler.runTask(
        new TestAbstractKernelRunnable() {
          public void run() throws Exception {
            reporter.setObjectDescription(null, "description");
          }
        },
        taskOwner);
  }
  @Test
  public void testAccessReporterAccessWithDescription() throws Exception {

    txnScheduler.runTask(
        new TestAbstractKernelRunnable() {
          public void run() throws Exception {
            AccessReporter<Integer> reporter =
                accessCoordinator.registerAccessSource("test", Integer.class);
            reporter.reportObjectAccess(1, AccessType.READ, "desc");
          }
        },
        taskOwner);
  }
 @Test
 public void testToString() throws Exception {
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               assertEquals("[]", set.toString());
               set.add(1);
               assertEquals("[1]", set.toString());
             }
           }),
       taskOwner);
 }
 @Test
 public void testRemoveObjectSet() throws Exception {
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               DoneRemoving.init();
               dataService.removeObject(set);
               set = null;
             }
           }),
       taskOwner);
   DoneRemoving.await(1);
   int count = getObjectCount();
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               set = new ScalableHashSet<Object>();
               for (int i = 0; i < 50; i++) {
                 set.add(random.nextInt());
               }
             }
           }),
       taskOwner);
   txnScheduler.runTask(
       new TestTask(
           new AbstractKernelRunnable() {
             public void run() {
               dataService.removeObject(set);
               set = null;
             }
           }),
       taskOwner);
   DoneRemoving.await(1);
   assertEquals(count, getObjectCount());
 }