@SuppressWarnings("unchecked")
 @Test
 public void testIteratorCollectionNotFound() throws Exception {
   set.add(one);
   Iterator<Object> iter = set.iterator();
   dataService.setBinding("iter", new ManagedSerializable(iter));
   newTransaction();
   DoneRemoving.init();
   dataService.removeObject(set);
   endTransaction();
   DoneRemoving.await(1);
   startTransaction();
   iter = (Iterator<Object>) dataService.getBinding("iter", ManagedSerializable.class).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);
   }
 }
    /** Processes (at least) the first event in the queue. */
    void serviceEvent() {
      checkState();

      ClientSessionServiceImpl sessionService = ClientSessionServiceImpl.getInstance();
      ManagedQueue<SessionEvent> eventQueue = getQueue();
      DataService dataService = ClientSessionServiceImpl.getDataService();

      for (int i = 0; i < sessionService.eventsPerTxn; i++) {
        SessionEvent event = eventQueue.poll();
        if (event == null) {
          // no more events
          break;
        }

        logger.log(Level.FINEST, "processing event:{0}", event);

        int cost = event.getCost();
        if (cost > 0) {
          dataService.markForUpdate(this);
          writeBufferAvailable += cost;
          if (logger.isLoggable(Level.FINEST)) {
            logger.log(
                Level.FINEST,
                "{0} cleared reservation of " + "{1,number,#} bytes, leaving {2,number,#}",
                this,
                cost,
                writeBufferAvailable);
          }
        }

        event.serviceEvent(this);
      }
    }
 /** Per-test setup */
 @Before
 public void setUpTest() throws Exception {
   txn = createTransaction();
   set = new ScalableHashSet<Object>();
   dataService.setBinding("set", set);
   one = new Int(1);
   dataService.setBinding("one", one);
 }
 /**
  * Returns the event queue for the client session with the specified {@code sessionId}, or null if
  * the event queue is not bound in the data service.
  */
 private static EventQueue getEventQueue(byte[] sessionId) {
   DataService dataService = ClientSessionServiceImpl.getDataService();
   String eventQueueKey = getEventQueueKey(sessionId);
   try {
     return (EventQueue) dataService.getServiceBinding(eventQueueKey);
   } catch (NameNotBoundException e) {
     return null;
   }
 }
 /** {@inheritDoc} */
 public void run() {
   DataService dataService = ClientSessionServiceImpl.getDataService();
   String key = dataService.nextServiceBoundName(lastKey);
   if (key != null && key.startsWith(nodePrefix)) {
     TaskService taskService = ClientSessionServiceImpl.getTaskService();
     taskService.scheduleTask(new CleanupDisconnectedSessionTask(key));
     lastKey = key;
     taskService.scheduleTask(this);
   }
 }
 @Test
 public void testAddObjectNotFound() throws Exception {
   newTransaction();
   dataService.removeObject(one);
   one = new Int(1);
   assertTrue(set.add(one));
   dataService.removeObject(one);
   newTransaction();
   assertTrue(set.add(new Int(1)));
 }
 public void testConcurrency() throws Throwable {
   DummyComponentRegistry componentRegistry = new DummyComponentRegistry();
   service = getDataService(props, componentRegistry);
   if (service instanceof ProfileProducer) {
     DummyProfileCoordinator.startProfiling(((ProfileProducer) service));
   }
   DummyTransaction txn = new DummyTransaction();
   txnProxy.setCurrentTransaction(txn);
   service.configure(componentRegistry, txnProxy);
   componentRegistry.setComponent(DataManager.class, service);
   componentRegistry.registerAppContext();
   txn.commit();
   int perThread = objects + objectsBuffer;
   /* Create objects */
   for (int t = 0; t < maxThreads; t++) {
     long startTime = System.currentTimeMillis();
     txn = new DummyTransaction();
     txnProxy.setCurrentTransaction(txn);
     int start = t * perThread;
     BigInteger block = null;
     for (int i = 0; i < perThread; i++) {
       if (startTime + 100 < System.currentTimeMillis()) {
         txn.commit();
         txn = new DummyTransaction();
         txnProxy.setCurrentTransaction(txn);
         if (i > 0) {
           service.getBinding(getObjectName(start), ModifiableObject.class);
         }
       }
       ModifiableObject object = new ModifiableObject();
       if (i == 0) {
         service.manageInNewArea(object);
       }
       service.setBinding(getObjectName(start + i), object);
       BigInteger oidBlock = service.createReference(object).getId().shiftRight(32);
       if (block == null || !block.equals(oidBlock)) {
         block = oidBlock;
         System.err.println("Thread " + t + ": init block " + block);
       }
     }
     txn.commit();
   }
   /* Warm up */
   if (repeat != 1) {
     System.err.println("Warmup:");
     runOperations(1);
   }
   /* Test */
   for (int t = threads; t <= maxThreads; t++) {
     System.err.println("Threads: " + t);
     for (int r = 0; r < repeat; r++) {
       runOperations(t);
     }
   }
 }
 /**
  * Returns the protocol descriptors map, keyed by node ID. Creates and stores the map if it
  * doesn't already exist. This method must be run within a transaction.
  */
 private static Map<Long, Set<ProtocolDescriptor>> getProtocolDescriptorsMap() {
   DataService dataService = getDataService();
   Map<Long, Set<ProtocolDescriptor>> protocolDescriptorsMap;
   try {
     protocolDescriptorsMap =
         Objects.uncheckedCast(dataService.getServiceBinding(PROTOCOL_DESCRIPTORS_MAP_KEY));
   } catch (NameNotBoundException e) {
     protocolDescriptorsMap = new ScalableHashMap<Long, Set<ProtocolDescriptor>>();
     dataService.setServiceBinding(PROTOCOL_DESCRIPTORS_MAP_KEY, protocolDescriptorsMap);
   }
   return protocolDescriptorsMap;
 }
 /** Removes the channel server proxy and binding for the node specified during construction. */
 public void run() {
   String channelServerKey = getChannelServerKey(nodeId);
   DataService dataService = getDataService();
   try {
     dataService.removeObject(dataService.getServiceBinding(channelServerKey));
   } catch (NameNotBoundException e) {
     // already removed
     return;
   } catch (ObjectNotFoundException e) {
   }
   dataService.removeServiceBinding(channelServerKey);
 }
 /** Updates fields from bindings, setting the fields to null if the objects are not found. */
 @SuppressWarnings("unchecked")
 private void startTransaction() throws Exception {
   try {
     set = (ScalableHashSet) dataService.getBinding("set");
   } catch (ObjectNotFoundException e) {
     set = null;
   }
   try {
     one = (Int) dataService.getBinding("one");
   } catch (ObjectNotFoundException e) {
     one = null;
   }
 }
 /**
  * Removes the client session server proxy and binding and also removes the protocol descriptors
  * for the node specified during construction.
  */
 public void run() {
   String sessionServerKey = getClientSessionServerKey(nodeId);
   DataService dataService = getDataService();
   try {
     dataService.removeObject(dataService.getServiceBinding(sessionServerKey));
     getProtocolDescriptorsMap().remove(nodeId);
   } catch (NameNotBoundException e) {
     // already removed
     return;
   } catch (ObjectNotFoundException e) {
   }
   dataService.removeServiceBinding(sessionServerKey);
 }
 /** Prints the current objects above the specified value, for debugging. */
 private void printObjects(BigInteger id) {
   while (true) {
     id = dataService.nextObjectId(id);
     if (id == null) {
       break;
     }
     try {
       Object obj = dataService.createReferenceForId(id).get();
       System.err.println(id + ": (" + obj.getClass().getName() + ") " + obj);
     } catch (Exception e) {
       System.err.println(id + ": " + e);
     }
   }
 }
 /** Stores fields, if they are not null, into bindings. */
 private void endTransaction() throws Exception {
   if (set != null) {
     try {
       dataService.setBinding("set", set);
     } catch (ObjectNotFoundException e) {
     }
   }
   if (one != null) {
     try {
       dataService.setBinding("one", one);
     } catch (ObjectNotFoundException e) {
     }
   }
 }
 /**
  * Starts a new transaction and updates fields from bindings, setting the fields to null if the
  * objects are not found.
  */
 @SuppressWarnings("unchecked")
 private void startTransaction() throws Exception {
   txn = createTransaction();
   try {
     set = dataService.getBinding("set", ScalableHashSet.class);
   } catch (ObjectNotFoundException e) {
     set = null;
   }
   try {
     one = dataService.getBinding("one", Int.class);
   } catch (ObjectNotFoundException e) {
     one = null;
   }
 }
 private void op(int i) throws Exception {
   if (random.nextInt(5) == 0) {
     DummyTransaction t = txn;
     txn = null;
     t.commit();
     long time = System.currentTimeMillis() - txnStart;
     if (time > maxTxnTime) {
       maxTxnTime = time;
       maxTxnTimeOps = txnOps;
     }
     txnStart = System.currentTimeMillis();
     txnOps = 0;
     createTxn();
   }
   txnOps++;
   int start = id * (objects + objectsBuffer);
   String name = getObjectName(start + random.nextInt(objects));
   switch (random.nextInt(whichOperations.value)) {
     case 0:
       /* Get binding */
       service.getBinding(name, Object.class);
       break;
     case 1:
       /* Set bindings */
       ModifiableObject obj = service.getBinding(name, ModifiableObject.class);
       String name2 = getObjectName(start + random.nextInt(objects));
       ModifiableObject obj2 = service.getBinding(name2, ModifiableObject.class);
       service.setBinding(name, obj2);
       service.setBinding(name2, obj);
       break;
     case 2:
       /* Modify object */
       service.getBinding(name, ModifiableObject.class).incrementNumber(service);
       break;
     case 3:
       /* Create object */
       /*
        * Get the binding first, so the new object is created with
        * proper locality.
        */
       ModifiableObject object = service.getBinding(name, ModifiableObject.class);
       service.removeObject(object);
       object = new ModifiableObject();
       service.setBinding(name, object);
       BigInteger oidBlock = service.createReference(object).getId().shiftRight(32);
       if (block == null || !block.equals(oidBlock)) {
         block = oidBlock;
         System.err.println("Thread " + id + ": create block " + block);
       }
       break;
     default:
       throw new AssertionError();
   }
 }
 /**
  * Returns the client session listener, obtained from the specified {@code dataService}, for this
  * session. This method should only be called within a transaction.
  *
  * @param dataService a data service
  * @return the client session listener for this session
  * @throws TransactionException if there is a problem with the current transaction
  */
 ClientSessionListener getClientSessionListener(DataService dataService) {
   String listenerKey = getListenerKey();
   ManagedObject obj = dataService.getServiceBinding(listenerKey);
   return (obj instanceof ListenerWrapper)
       ? ((ListenerWrapper) obj).get()
       : (ClientSessionListener) obj;
 }
 /**
  * Stores the specified client session listener in the specified {@code dataService} with
  * following binding:
  *
  * <pre>
  * com.sun.sgs.impl.service.session.listener.&lt;idBytes&gt;
  * </pre>
  *
  * This method should only be called within a transaction.
  *
  * @param dataService a data service
  * @param listener a client session listener
  * @throws TransactionException if there is a problem with the current transaction
  */
 void putClientSessionListener(DataService dataService, ClientSessionListener listener) {
   ManagedObject managedObject =
       (listener instanceof ManagedObject)
           ? (ManagedObject) listener
           : new ListenerWrapper(listener);
   String listenerKey = getListenerKey();
   dataService.setServiceBinding(listenerKey, managedObject);
 }
 @SuppressWarnings("unchecked")
 @Test
 public void testIterator() throws Exception {
   set.add(null);
   set.add(1);
   set.add(2);
   Iterator iter = set.iterator();
   dataService.setBinding("iter", new ManagedSerializable(iter));
   newTransaction();
   iter = (Iterator) dataService.getBinding("iter", ManagedSerializable.class).get();
   int count = 0;
   while (iter.hasNext()) {
     iter.next();
     count++;
   }
   assertEquals(3, count);
 }
 @Test
 public void testContainsObjectNotFound() throws Exception {
   set.add(one);
   newTransaction();
   dataService.removeObject(one);
   assertFalse(set.contains(one));
   newTransaction();
   assertFalse(set.contains(one));
 }
 @Test
 public void testSizeObjectNotFound() throws Exception {
   set.add(one);
   newTransaction();
   dataService.removeObject(one);
   assertEquals(1, set.size());
   newTransaction();
   assertEquals(1, set.size());
 }
 /**
  * Returns the {@code ClientSession} instance for the given {@code id}, retrieved from the
  * specified {@code dataService}, or {@code null} if the client session isn't bound in the data
  * service. This method should only be called within a transaction.
  *
  * @param dataService a data service
  * @param id a session ID
  * @return the session for the given session {@code id}, or {@code null}
  * @throws TransactionException if there is a problem with the current transaction
  */
 static ClientSessionImpl getSession(DataService dataService, BigInteger id) {
   ClientSessionImpl sessionImpl = null;
   try {
     ManagedReference<?> sessionRef = dataService.createReferenceForId(id);
     sessionImpl = (ClientSessionImpl) sessionRef.get();
   } catch (ObjectNotFoundException e) {
   }
   return sessionImpl;
 }
 @Test
 public void testIsEmptyObjectNotFound() throws Exception {
   set.add(one);
   newTransaction();
   dataService.removeObject(one);
   assertFalse(set.isEmpty());
   newTransaction();
   assertFalse(set.isEmpty());
 }
 @Test
 public void testRemoveObjectNotFound() throws Exception {
   set.add(one);
   newTransaction();
   dataService.removeObject(one);
   one = new Int(1);
   assertFalse(set.remove(one));
   newTransaction();
   assertFalse(set.remove(one));
 }
 @Test
 public void testClearObjectNotFound() throws Exception {
   set.add(one);
   newTransaction();
   dataService.removeObject(one);
   DoneRemoving.init();
   set.clear();
   assertTrue(set.isEmpty());
   one = new Int(1);
   set.add(one);
   endTransaction();
   DoneRemoving.await(1);
   startTransaction();
   dataService.removeObject(one);
   newTransaction();
   set.clear();
   assertTrue(set.isEmpty());
   endTransaction();
   DoneRemoving.await(1);
 }
 @SuppressWarnings("unchecked")
 @Test
 public void testIteratorObjectNotFound() throws Exception {
   set.add(one);
   set.add(new Int(2));
   Iterator<Object> iter = set.iterator();
   dataService.setBinding("iter", new ManagedSerializable(iter));
   newTransaction();
   dataService.removeObject(one);
   newTransaction();
   iter = (Iterator<Object>) dataService.getBinding("iter", ManagedSerializable.class).get();
   int count = 0;
   while (iter.hasNext()) {
     try {
       assertEquals(new Int(2), iter.next());
       count++;
     } catch (ObjectNotFoundException e) {
     }
   }
   assertEquals(1, count);
 }
 @SuppressWarnings("unchecked")
 @Test
 public void testIteratorRemove() throws Exception {
   Iterator iter = set.iterator();
   try {
     iter.remove();
     fail("Expected IllegalStateException");
   } catch (IllegalStateException e) {
   }
   set.add(one);
   set.add(new Int(2));
   set.add(new Int(3));
   try {
     iter.remove();
     fail("Expected IllegalStateException");
   } catch (IllegalStateException e) {
   }
   dataService.setBinding("iter", new ManagedSerializable(iter));
   newTransaction();
   iter = (Iterator) dataService.getBinding("iter", ManagedSerializable.class).get();
   while (iter.hasNext()) {
     Object next = iter.next();
     if (one.equals(next)) {
       iter.remove();
       try {
         iter.remove();
         fail("Expected IllegalStateException");
       } catch (IllegalStateException e) {
       }
     }
   }
   newTransaction();
   iter = set.iterator();
   int count = 0;
   while (iter.hasNext()) {
     assertFalse(one.equals(iter.next()));
     count++;
   }
   assertEquals(2, count);
 }
 @Test
 public void testRemoveObjectSet() throws Exception {
   DoneRemoving.init();
   dataService.removeObject(set);
   set = null;
   endTransaction();
   DoneRemoving.await(1);
   startTransaction();
   int count = getObjectCount();
   set = new ScalableHashSet<Object>();
   newTransaction();
   for (int i = 0; i < 50; i++) {
     set.add(random.nextInt());
   }
   newTransaction();
   dataService.removeObject(set);
   set = null;
   endTransaction();
   DoneRemoving.await(1);
   startTransaction();
   assertEquals(count, getObjectCount());
 }
 /** Returns the current number of objects. */
 private int getObjectCount() {
   int count = 0;
   BigInteger last = null;
   while (true) {
     BigInteger next = dataService.nextObjectId(last);
     if (next == null) {
       break;
     }
     last = next;
     count++;
   }
   return count;
 }
 @Test
 public void testEqualsObjectNotFound() throws Exception {
   Set<Object> empty = new HashSet<Object>();
   Set<Object> containsOne = new HashSet<Object>();
   containsOne.add(one);
   set.add(one);
   newTransaction();
   dataService.removeObject(one);
   assertFalse(set.equals(empty));
   assertFalse(set.equals(containsOne));
   newTransaction();
   assertFalse(set.equals(empty));
   assertFalse(set.equals(containsOne));
 }
 @Test
 public void testCopyConstructorObjectNotFound() throws Exception {
   set.add(one);
   newTransaction();
   dataService.removeObject(one);
   try {
     new ScalableHashSet<Object>(set);
     fail("Expected ObjectNotFoundException");
   } catch (ObjectNotFoundException e) {
   }
   newTransaction();
   try {
     new ScalableHashSet<Object>(set);
     fail("Expected ObjectNotFoundException");
   } catch (ObjectNotFoundException e) {
   }
 }