@Test(invocationCount = 5, successPercentage = 19)
  public void topicConduit() throws Exception {
    String topicName =
        "JmsByteArrayTransportTest-topicConduit-"
            + System.getProperty("user.name")
            + "-"
            + System.currentTimeMillis();
    ConnectionFactory cf = ActiveMQTestUtils.createTestConnectionFactory();
    JmsTemplate jmsTemplate = new JmsTemplate();
    jmsTemplate.setConnectionFactory(cf);
    jmsTemplate.setPubSubDomain(true);

    JmsByteArrayMessageSender messageSender = new JmsByteArrayMessageSender(topicName, jmsTemplate);
    CollectingByteArrayMessageReceiver collectingReceiver =
        new CollectingByteArrayMessageReceiver();
    JmsByteArrayMessageDispatcher messageDispatcher =
        new JmsByteArrayMessageDispatcher(collectingReceiver);

    DefaultMessageListenerContainer container = new DefaultMessageListenerContainer();
    container.setConnectionFactory(cf);
    container.setMessageListener(messageDispatcher);
    container.setDestinationName(topicName);
    container.setPubSubDomain(true);
    container.afterPropertiesSet();
    container.start();

    Random random = new Random();
    byte[] randomBytes = new byte[1024];
    random.nextBytes(randomBytes);

    while (!container.isRunning()) {
      Thread.sleep(10l);
    }
    // TODO: this is a hack.  The context doesn't seem to have always set up the consumer completely
    // yet
    Thread.sleep(500l);

    messageSender.send(randomBytes);
    long startTime = System.currentTimeMillis();
    while (collectingReceiver.getMessages().isEmpty()) {
      Thread.sleep(10l);
      if ((System.currentTimeMillis() - startTime) > TIMEOUT) {
        fail("Did not receive a message in " + (TIMEOUT / 1000) + " seconds.");
      }
    }
    s_logger.debug(
        "topicConduit message received {}ms before timeout limit",
        TIMEOUT - (System.currentTimeMillis() - startTime));
    assertEquals(1, collectingReceiver.getMessages().size());
    byte[] receivedBytes = collectingReceiver.getMessages().get(0);
    assertEquals(randomBytes.length, receivedBytes.length);
    for (int i = 0; i < randomBytes.length; i++) {
      assertEquals(randomBytes[i], receivedBytes[i]);
    }

    container.stop();
    container.destroy();
  }
Example #2
0
  @Test
  public void testDBName() throws Exception {

    Mongo m = new Mongo();

    try {
      new DBImpl(null, null, null);
      fail();
    } catch (Exception e) {
      // ok
    }

    try {
      new DBImpl(m, null, "");
      fail();
    } catch (Exception e) {
      // ok
    }

    try {
      new DBImpl(m, null, "a.b");
      fail();
    } catch (Exception e) {
      // ok
    }

    DBImpl db = new DBImpl(m, m.getConnection(), "test_me");

    assert (db.getName().equals("test_me"));

    db.close();
  }
  public void testDeleteWithExpectedResultSizeOnCobarSqlMapClientTemplate() {
    Follower f = new Follower("fname");
    getSqlMapClientTemplate().insert("com.alibaba.cobar.client.entities.Follower.create", f);

    String confirmSQL = "select name from followers where name='fname'";
    verifyEntityNonExistenceOnSpecificDataSource(confirmSQL, jt1m);
    verifyEntityNonExistenceOnSpecificDataSource(confirmSQL, jt1s);
    verifyEntityExistenceOnSpecificDataSource(confirmSQL, jt2m);
    verifyEntityNonExistenceOnSpecificDataSource(confirmSQL, jt2s);

    try {
      getSqlMapClientTemplate()
          .delete("com.alibaba.cobar.client.entities.Follower.deleteByName", f, 2);
      fail("only one row will be affected in fact.");
    } catch (DataAccessException e) {
      assertTrue(e instanceof JdbcUpdateAffectedIncorrectNumberOfRowsException);
      JdbcUpdateAffectedIncorrectNumberOfRowsException ex =
          (JdbcUpdateAffectedIncorrectNumberOfRowsException) e;
      assertEquals(1, ex.getActualRowsAffected());
    }
    // although JdbcUpdateAffectedIncorrectNumberOfRowsException is raised, but the delete does
    // performed successfully.
    verifyEntityNonExistenceOnSpecificDataSource(confirmSQL, jt1m);
    verifyEntityNonExistenceOnSpecificDataSource(confirmSQL, jt1s);
    verifyEntityNonExistenceOnSpecificDataSource(confirmSQL, jt2m);
    verifyEntityNonExistenceOnSpecificDataSource(confirmSQL, jt2s);

    try {
      getSqlMapClientTemplate()
          .delete("com.alibaba.cobar.client.entities.Follower.deleteByName", f, 0);
    } catch (DataAccessException e) {
      fail();
    }
  }
 private void testOn(Directory dir, int writeSize, int readSize, Cache cache) throws IOException {
   if (cache != null)
     cache
         .clear(); // needed to make sure no chunks are left over in case of Infinispan
                   // implementation
   final String filename = "chunkTest";
   IndexOutput indexOutput = dir.createOutput(filename);
   byte[] toWrite = fillBytes(writeSize);
   indexOutput.writeBytes(toWrite, writeSize);
   indexOutput.close();
   if (cache != null) {
     AssertJUnit.assertEquals(
         writeSize,
         DirectoryIntegrityCheck.deepCountFileSize(new FileCacheKey(INDEXNAME, filename), cache));
   }
   AssertJUnit.assertEquals(writeSize, indexOutput.length());
   byte[] results = new byte[readSize];
   IndexInput openInput = dir.openInput(filename);
   try {
     openInput.readBytes(results, 0, readSize);
     for (int i = 0; i < writeSize && i < readSize; i++) {
       AssertJUnit.assertEquals(results[i], toWrite[i]);
     }
     if (readSize > writeSize)
       AssertJUnit.fail("should have thrown an IOException for reading past EOF");
   } catch (IOException ioe) {
     if (readSize <= writeSize)
       AssertJUnit.fail("should not have thrown an IOException" + ioe.getMessage());
   }
 }
 public void verifyCommentRowContent(
     String commentRowIdSuffix, String commentText, String giverName) {
   WebDriverWait wait = new WebDriverWait(browser.driver, 30);
   WebElement commentRow;
   try {
     commentRow =
         wait.until(
             ExpectedConditions.presenceOfElementLocated(
                 By.id("responseCommentRow" + commentRowIdSuffix)));
   } catch (TimeoutException e) {
     fail("Timeout!");
     commentRow = null;
   }
   try {
     wait.until(
         ExpectedConditions.textToBePresentInElement(
             commentRow.findElement(By.id("plainCommentText" + commentRowIdSuffix)), commentText));
   } catch (TimeoutException e) {
     fail("Not expected message");
   }
   try {
     assertTrue(commentRow.findElement(By.className("text-muted")).getText().contains(giverName));
   } catch (AssertionError e) {
     assertTrue(commentRow.findElement(By.className("text-muted")).getText().contains("you"));
   }
 }
Example #6
0
 /**
  * Asserts that within a set of records, there is no record such that record[fieldName] == val.
  * Note that if multiple such asserts are to be made, it may be necessary to synchronize on the
  * list to ensure it is consistent throughout multiple asserts.
  */
 protected void assertNoSuchRecord(
     List<GenericData.Record> records, String fieldName, Object val) {
   for (GenericData.Record record : records) {
     if (null == val) {
       if (record.get(fieldName) == null) {
         fail("Assertion failed: Found record with null in field " + fieldName);
       }
     } else if (val.equals(record.get(fieldName))) {
       fail("Assertion failed: Found record with field " + fieldName + " equals " + val);
     }
   }
 }
Example #7
0
 private void checkField(GenericData.Record record, String testField, Object testValue) {
   if (null == testValue) {
     if (record.get(testField) != null) {
       fail("Assertion failed: candidate record had non-null value for " + testField);
     }
   } else if (!testValue.equals(record.get(testField))) {
     fail(
         "Assertion failed: test field had value "
             + record.get(testField)
             + ", but expected "
             + testValue);
   }
 }
  @TestFor(issues = "TW-18853")
  public void should_throw_special_exception_when_stderr_mentions_broken_index()
      throws VcsException {
    AskPassGenerator fakeGen =
        new AskPassGenerator() {
          @NotNull
          public File generate(@NotNull AuthSettings authSettings) throws IOException {
            return new File(".");
          }
        };

    File tmpDir = new File(FileUtil.getTempDirectory());
    GitCommandLine failedCmd =
        new GitCommandLine(null, fakeGen, tmpDir, false, GitProgressLogger.NO_OP) {
          @Override
          public ExecResult run(@NotNull GitCommandSettings settings) throws VcsException {
            throw new VcsException("fatal: index file smaller than expected");
          }
        };

    FetchCommand fetch =
        new FetchCommandImpl(failedCmd)
            .setRefspec("+refs/heads/*:refs/remotes/origin/*")
            .setTimeout(3600)
            .setAuthSettings(new AuthSettings(new HashMap<String, String>()));

    try {
      fetch.call();
    } catch (GitIndexCorruptedException e) {
      // expected
    } catch (VcsException e) {
      fail("GitIndexCorruptedException should be thrown");
    }
  }
Example #9
0
  /** Asserts that there exists a record in records such that testField = testValue. */
  protected void assertRecordExists(
      List<GenericData.Record> records, String testField, Object testValue) {
    for (GenericData.Record record : records) {
      Object result = record.get(testField);

      if (result != null && testValue != null) {
        LOG.debug(
            "Checking result: "
                + result
                + " (class="
                + result.getClass().getName()
                + ")"
                + " against testValue: "
                + testValue
                + " (class="
                + testValue.getClass().getName()
                + ") for field "
                + testField);
      }

      if (null == testValue && null == result) {
        return;
      } else if (null != testValue && testValue.equals(result)) {
        return;
      }
    }

    fail("Could not find record such that " + testField + " equals " + testValue);
  }
Example #10
0
  public void testClear() throws Exception {
    _tool.createTestSchema();
    createTestTable();
    _tool.executeSql(
        _tool.getTestCatalog(),
        _tool.getTestSchema(),
        "INSERT INTO " + TEST_TABLE + " (test_column) VALUES ('test')");

    _tool.clearTestTables();

    Connection connection = getConnection();
    Statement statement = connection.createStatement();
    ResultSet rs = statement.executeQuery("SELECT COUNT(*) FROM " + TEST_TABLE);
    if (rs.next()) {
      int count = rs.getInt(1);
      assertEquals(0, count);
    } else {
      fail();
    }

    rs.close();
    statement.close();
    connection.close();

    _tool.dropTestSchema();
  }
Example #11
0
  @Test
  public void testStrictCollectionCreation() throws Exception {

    Mongo m = new Mongo();

    DB db = new DBImpl(m, m.getConnection(), "org_mongo_driver_DBTest");
    db.setDBOptions(new DBOptions().setStrictCollectionMode(true));

    for (String n : db.getCollectionNames()) {
      db.dropCollection(n);
    }

    assert (db.getCollectionNames().size() == 0);

    try {
      db.getCollection("woogie");
      fail();
    } catch (Exception e) {
      // expect an exception as we're in strict mode
    }

    assert (db.getCollectionNames().size() == 0);

    db.setDBOptions(null);

    assert (db.getCollection("woogie") != null);
    assert (db.getCollectionNames().size() == 1);
  }
  @Test
  public static void depositeDetailTest() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
      HttpPost post = new HttpPost("http://192.168.2.111:8578/service?channel=QueryNoticePage");
      List<NameValuePair> list = new ArrayList<NameValuePair>();
      list.add(new BasicNameValuePair("platformId", "82044"));
      list.add(new BasicNameValuePair("appKey", "1"));

      post.setEntity(new UrlEncodedFormEntity(list));
      CloseableHttpResponse response = httpclient.execute(post);

      try {
        System.out.println(response.getStatusLine());
        HttpEntity entity2 = response.getEntity();
        String entity = EntityUtils.toString(entity2);
        if (entity.contains("code\":\"0")) {
          System.out.println("Success!");
          System.out.println("response content:" + entity);
        } else {
          System.out.println("Failure!");
          System.out.println("response content:" + entity);
          AssertJUnit.fail(entity);
        }
      } finally {
        response.close();
      }
    } finally {
      httpclient.close();
    }
  }
  @Test
  public void test100GetAccountMurray() throws Exception {
    TestUtil.displayTestTile(this, "test100GetAccountMurray");

    // GIVEN
    Task task =
        taskManager.createTaskInstance(
            TestModelServiceContract.class.getName() + ".test100GetAccountMurray");
    OperationResult result = task.getResult();

    try {

      // WHEN
      PrismObject<ShadowType> account =
          modelService.getObject(
              ShadowType.class, ACCOUNT_SHADOW_MURRAY_CSVFILE_OID, null, task, result);

      AssertJUnit.fail("Expected SystemException but the operation was successful");
    } catch (SystemException e) {
      // This is expected
      display("Expected exception", e);
      result.computeStatus();
      display("getObject result", result);
      TestUtil.assertFailure("getObject result", result);
    }
  }
  public void testBasicTargetRemoteDistributedCallable() throws Exception {
    long taskTimeout = TimeUnit.SECONDS.toMillis(15);
    EmbeddedCacheManager cacheManager1 = manager(0);
    final EmbeddedCacheManager cacheManager2 = manager(1);

    Cache<Object, Object> cache1 = cacheManager1.getCache();
    Cache<Object, Object> cache2 = cacheManager2.getCache();
    DistributedExecutorService des = null;

    try {
      des = new DefaultExecutorService(cache1);
      Address target = cache2.getAdvancedCache().getRpcManager().getAddress();

      DistributedTaskBuilder<Integer> builder =
          des.createDistributedTaskBuilder(new SimpleCallable())
              .failoverPolicy(DefaultExecutorService.RANDOM_NODE_FAILOVER)
              .timeout(taskTimeout, TimeUnit.MILLISECONDS);

      Future<Integer> future = des.submit(target, builder.build());
      AssertJUnit.assertEquals((Integer) 1, future.get());
    } catch (Exception ex) {
      AssertJUnit.fail("Task did not failover properly " + ex);
    } finally {
      des.shutdown();
    }
  }
Example #15
0
  /**
   * Tries to create payment against review invoice. Here, instead of using the billing process to
   * generate a review invoice we are creating a review invoice with the help of saveLegacyInvoice
   * call.
   */
  @Test
  public void testPayReviewInvoice() {
    // creating new user
    UserWS user = buildUser(PRANCING_PONY_ACCOUNT_TYPE);
    user.setId(api.createUser(user));

    ItemTypeWS itemType = buildItemType();
    itemType.setId(api.createItemCategory(itemType));

    ItemDTOEx item = buildItem(itemType.getId(), api.getCallerCompanyId());
    item.setId(api.createItem(item));

    InvoiceWS invoice = buildInvoice(user.getId(), item.getId());
    invoice.setIsReview(Integer.valueOf(1));
    invoice.setId(api.saveLegacyInvoice(invoice));

    // check if invoice is a review invoice
    System.out.println("Invoice is review : " + invoice.getIsReview());
    assertEquals("Invoice is a review invoice", Integer.valueOf(1), invoice.getIsReview());

    try {
      // pay for a review invoice
      api.payInvoice(invoice.getId());
      fail("We should not be able to issue a payment against review invoice");
    } catch (SessionInternalError e) {
      System.out.println(e.getMessage());
    }

    // clean up
    api.deleteInvoice(invoice.getId());
    api.deleteItem(item.getId());
    api.deleteItemCategory(itemType.getId());
    api.deleteUser(user.getId());
  }
  @Test
  public void test120SearchAccountByUsernameJack() throws Exception {
    TestUtil.displayTestTile(this, "test120SearchAccountByUsernameJack");

    // GIVEN
    Task task =
        taskManager.createTaskInstance(
            TestModelServiceContract.class.getName() + ".test120SearchAccountByUsernameJack");
    OperationResult result = task.getResult();

    PrismObject<ResourceType> resource =
        modelService.getObject(ResourceType.class, RESOURCE_CSVFILE_BROKEN_OID, null, task, result);

    try {

      // WHEN
      PrismObject<ShadowType> account = findAccountByUsername("jack", resource, task, result);

      AssertJUnit.fail("Expected SystemException but the operation was successful");
    } catch (SystemException e) {
      // This is expected
      result.computeStatus();
      display("findAccountByUsername result", result);
      TestUtil.assertFailure("findAccountByUsername result", result);
    }
  }
  @Test(groups = "unstable")
  public void testInvalidationDuringStateTransfer() throws Exception {
    cache(0).put("key1", "value1");

    CheckPoint checkPoint = new CheckPoint();
    blockJoinResponse(manager(0), checkPoint);

    addClusterEnabledCacheManager(dccc);
    Future<Object> joinFuture =
        fork(
            new Callable<Object>() {
              @Override
              public Object call() throws Exception {
                // The cache only joins here
                return cache(2);
              }
            });

    checkPoint.awaitStrict("sending_join_response", 10, SECONDS);

    // This will invoke an invalidation on the joiner
    NotifyingFuture<Object> putFuture = cache(0).putAsync("key2", "value2");
    try {
      putFuture.get(1, SECONDS);
      fail("Put operation should have been blocked, but it finished successfully");
    } catch (java.util.concurrent.TimeoutException e) {
      // expected
    }

    checkPoint.trigger("resume_join_response");
    putFuture.get(10, SECONDS);
  }
  private void testLockMigration(int nodeThatPuts) throws Exception {
    Map<Object, DummyTransaction> key2Tx = new HashMap<Object, DummyTransaction>();
    for (int i = 0; i < NUM_KEYS; i++) {
      Object key = getKeyForCache(0);
      if (key2Tx.containsKey(key)) continue;

      dummyTm(nodeThatPuts).begin();
      cache(nodeThatPuts).put(key, key);
      DummyTransaction tx = dummyTm(nodeThatPuts).getTransaction();
      tx.runPrepare();
      dummyTm(nodeThatPuts).suspend();
      key2Tx.put(key, tx);

      assertLocked(0, key);
    }

    log.trace("Lock transfer happens here");

    addClusterEnabledCacheManager(dccc);
    waitForClusterToForm();

    Object migratedKey = null;
    ConsistentHash ch = advancedCache(2).getDistributionManager().getConsistentHash();
    for (Object key : key2Tx.keySet()) {
      if (ch.locatePrimaryOwner(key).equals(address(2))) {
        migratedKey = key;
        break;
      }
    }
    if (migratedKey == null) {
      log.trace("No key migrated to new owner.");
    } else {
      log.trace("migratedKey = " + migratedKey);
      dummyTm(2).begin();
      cache(2).put(migratedKey, "someValue");
      try {
        dummyTm(2).commit();
        fail("RollbackException should have been thrown here.");
      } catch (RollbackException e) {
        // expected
      }
    }

    log.trace("About to commit existing transactions.");

    log.trace("Committing the tx to the new node.");
    for (Transaction tx : key2Tx.values()) {
      tm(nodeThatPuts).resume(tx);
      dummyTm(nodeThatPuts).getTransaction().runCommitTx();
    }

    for (Object key : key2Tx.keySet()) {
      Object value =
          getValue(
              key); // make sure that data from the container, just to make sure all replicas are
                    // correctly set
      assertEquals(key, value);
    }
  }
 @Test(dependsOnMethods = {"testMetadataLevel"})
 public void testCreationDateIsReasonable() {
   List<IObjectContainer> containers = store.getIObjectContainers(Image.class);
   for (IObjectContainer container : containers) {
     Image image = (Image) container.sourceObject;
     assertNotNull(image.getAcquisitionDate());
     Date acquisitionDate = new Date(image.getAcquisitionDate().getValue());
     Date now = new Date(System.currentTimeMillis());
     Date january1st1995 = new GregorianCalendar(1995, 1, 1).getTime();
     if (acquisitionDate.after(now)) {
       fail(String.format("%s after %s", acquisitionDate, now));
     }
     if (acquisitionDate.before(january1st1995)) {
       fail(String.format("%s before %s", acquisitionDate, january1st1995));
     }
   }
 }
 @AfterMethod
 public void tearDown() throws Exception {
   driver.quit();
   String verificationErrorString = verificationErrors.toString();
   if (!"".equals(verificationErrorString)) {
     AssertJUnit.fail(verificationErrorString);
   }
 }
 public void verifyRowMissing(String rowIdSuffix) {
   try {
     waitForElementToDisappear(By.cssSelector("img[src='/images/ajax-loader.gif']"));
     browser.driver.findElement(By.id("responseCommentRow" + rowIdSuffix));
     fail("Row expected to be missing found.");
   } catch (NoSuchElementException expected) {
     // row expected to be missing
   }
 }
Example #22
0
  @SuppressWarnings("unchecked")
  protected void setupFolderSyncZone() throws Exception {

    int custId = getJspTestUtils().getCustId();
    IFolderSyncManager folderMgr = ManagementContainer.getInstance().getFolderSyncManager();
    IUserManager userService = ManagementContainer.getInstance().getUserManager();

    UserAccount account = userService.getUser(getJspTestUtils().getUserAddress());
    m_userId = account.getUserID();

    // first create the topology and zone itself
    CustomerTopology ct = createTopology();
    Iterator serverIterator = ct.getAllServers();
    if (!serverIterator.hasNext()) {
      fail("No server in topology.");
    }
    CustomerServer server = (CustomerServer) serverIterator.next();
    Iterator storesIterator = ct.getAllStores();
    if (!storesIterator.hasNext()) {
      fail("No stores in server.");
    }
    CustomerStore store = (CustomerStore) storesIterator.next();
    FolderSyncZone zone = new FolderSyncZone();
    zone.setCustomerId(getJspTestUtils().getCustId());
    zone.setDisplayName("foobar");
    zone.setRegistrationKey("12345");
    zone.getServers().add(server);
    folderMgr.saveFolderSyncZone(zone);

    // now enable the user for folder sync
    account.setMessageStoreID(store.getStoreID());
    userService.updateUsers(Arrays.asList(account));
    SavedUserSet userSet = new SavedUserSet(custId);
    List<Integer> userIDs = Arrays.asList(account.getUserID());
    List<SearchConstraint> oldScList = new ArrayList<SearchConstraint>();
    oldScList.add(
        new SearchConstraint(
            UserManagerConstants.PROP_USERID,
            SearchConstraintOperator.CONSTRAINT_IN_LIST,
            userIDs));
    userSet.addUsers(oldScList);
    folderMgr.saveUserSetEnabledForSync(custId, userSet);
  }
 protected ExperimentPE pickAnExperiment() {
   List<ExperimentPE> experiments = daoFactory.getExperimentDAO().listExperiments();
   for (ExperimentPE experimentPE : experiments) {
     if (experimentPE.getInvalidation() == null) {
       return experimentPE;
     }
   }
   fail("No valid experiment found.");
   return null; // to make the compiler happy
 }
Example #24
0
  public void testImmutabilityOfData() {

    Node<Object, Object> rootNode = cache.getRoot();

    rootNode.put("key", "value");
    Map<Object, Object> m = rootNode.getData();
    try {
      m.put("x", "y");
      fail("Map should be immutable!!");
    } catch (Exception e) {
      // expected
    }

    try {
      rootNode.getKeys().add(new Object());
      fail("Key set should be immutable");
    } catch (Exception e) {
      // expected
    }
  }
 @Test(dependsOnMethods = {"testMetadataLevel"})
 public void testAuthoritativeLSIDsAreUnique() {
   Set<String> authoritativeLSIDs = new HashSet<String>();
   Set<IObjectContainer> containers = new HashSet<IObjectContainer>(containerCache.values());
   for (IObjectContainer container : containers) {
     if (!authoritativeLSIDs.add(container.LSID)) {
       String e =
           String.format("LSID from %s,%s not unique.", container.sourceObject, container.LSID);
       fail(e);
     }
   }
 }
  @Test
  public void testReadWithConnection() throws Exception {
    PreparedStatement preparedStatement = EasyMock.createStrictMock(PreparedStatement.class);
    ResultSet resultSet = EasyMock.createStrictMock(ResultSet.class);
    Connection connection = EasyMock.createStrictMock(Connection.class);
    SavedReviewerSearch search = new SavedReviewerSearch();
    int id = 34;
    String name = "myName";
    SavedReviewerSearchDAO dao =
        EasyMock.createMockBuilder(SavedReviewerSearchDAO.class)
            .withConstructor()
            .addMockedMethod("resultFromResultSet")
            .createStrictMock();

    EasyMock.expect(connection.prepareStatement(SavedReviewerSearchDAO.READ_SQL))
        .andReturn(preparedStatement);
    preparedStatement.setInt(1, id);
    EasyMock.expectLastCall();
    preparedStatement.setString(2, name);
    EasyMock.expectLastCall();
    EasyMock.expect(preparedStatement.executeQuery()).andReturn(resultSet);
    EasyMock.expect(resultSet.next()).andReturn(true);
    EasyMock.expect(dao.resultFromResultSet(resultSet)).andReturn(search);
    resultSet.close();
    EasyMock.expectLastCall();
    preparedStatement.close();
    EasyMock.replay(preparedStatement, resultSet, connection, dao);
    SavedReviewerSearch result = dao.read(connection, id, name);
    assertEquals("Wrong search returned", search, result);
    EasyMock.verify(preparedStatement, resultSet, connection, dao);

    // failure case
    EasyMock.reset(preparedStatement, resultSet, connection, dao);
    EasyMock.expect(connection.prepareStatement(SavedReviewerSearchDAO.READ_SQL))
        .andReturn(preparedStatement);
    preparedStatement.setInt(1, id);
    EasyMock.expectLastCall();
    preparedStatement.setString(2, name);
    EasyMock.expectLastCall();
    EasyMock.expect(preparedStatement.executeQuery()).andReturn(resultSet);
    EasyMock.expect(resultSet.next()).andReturn(false);
    resultSet.close();
    EasyMock.expectLastCall();
    preparedStatement.close();
    EasyMock.replay(preparedStatement, resultSet, connection, dao);
    try {
      dao.read(connection, id, name);
      fail("Should have thrown a sql exception.");
    } catch (SQLException ex) {
      // expected
    }
    EasyMock.verify(preparedStatement, resultSet, connection, dao);
  }
 public void testGetEarliestValue() {
   ObjectTimeSeries<E, T> empty = createEmptyTimeSeries();
   ObjectTimeSeries<E, T> dts = createStandardTimeSeries();
   T[] values = testValues();
   assertEquals(values[0], dts.getEarliestValue());
   try {
     empty.getEarliestValue();
   } catch (NoSuchElementException nsee) {
     return;
   }
   fail();
 }
 public void testGetLatestInstant() {
   ObjectTimeSeries<E, T> empty = createEmptyTimeSeries();
   ObjectTimeSeries<E, T> dts = createStandardTimeSeries();
   E[] testDates = testTimes();
   assertEquals(testDates[5], dts.getLatestTime());
   try {
     empty.getLatestTime();
   } catch (NoSuchElementException nsee) {
     return;
   }
   fail();
 }
 @Test
 public void simpleTest() {
   try {
     doTest("10:00", 10, 0);
     doTest("10:10", 10, 10);
     doTest("23:58", 23, 58);
     doTest("1:01", 1, 1);
     doTest("24:61", 1, 1);
   } catch (ParseException e) {
     fail(String.format("unexpected exception %s", e));
   }
 }
  protected void testRemovePerformance(int count, Map<Integer, Integer> bchm, String evictionName) {
    long startIncludePut = System.currentTimeMillis();

    int j = 0;
    long firstHalfNano = System.nanoTime();
    // fill the cache
    for (; j < count / 2; j++) bchm.put(j, j);
    firstHalfNano = System.nanoTime() - firstHalfNano;

    long secondHalfNano = System.nanoTime();
    for (; j < count; j++) bchm.put(j, j);
    secondHalfNano = System.nanoTime() - secondHalfNano;

    // force a single cache hit (so that accessQueue has a head item)
    bchm.get(0);

    // remove items
    long start = System.currentTimeMillis();
    long getNano = 0;
    long removeNano = 0;
    for (int i = 1; i < count; i++) {
      long getBegin = System.nanoTime();
      assertNotNull(bchm.get(i));
      getNano += System.nanoTime() - getBegin;
      long removeBegin = System.nanoTime();
      bchm.remove(i);
      removeNano += System.nanoTime() - removeBegin;

      // Only check every 100
      if (i % 100 == 0) {
        if (System.currentTimeMillis() - start > TimeUnit.SECONDS.toMillis(50))
          fail(evictionName + ": removing " + count + " entries takes more than 50 seconds!");
      }
    }
    System.out.println(
        "BCHM Stress Test "
            + evictionName
            + " took "
            + (System.currentTimeMillis() - start)
            + " milliseconds");
    System.out.println(
        "BCHM Entire Stress Test "
            + evictionName
            + " took "
            + (System.currentTimeMillis() - startIncludePut)
            + " milliseconds");

    System.out.println("First half of puts took " + firstHalfNano + " nanoseconds");
    System.out.println("Second half of puts took " + secondHalfNano + " nanoseconds");
    System.out.println("Gets took: " + getNano + " nanoseconds");
    System.out.println("Removes took: " + removeNano + " nanoseconds");
  }