/** Start all cqs running for this VM, and create a CQHistory instance for each CQ. */
  private void startCQsWithHistory() {
    initializeQueryService();
    CqAttributesFactory cqFac = new CqAttributesFactory();
    cqFac.addCqListener(new CQHistoryListener());
    cqFac.addCqListener(new CQGatherListener());
    CqAttributes cqAttr = cqFac.create();
    Iterator it = queryMap.keySet().iterator();
    while (it.hasNext()) {
      String queryName = (String) (it.next());
      String query = (String) (queryMap.get(queryName));
      try {
        CqQuery cq = qService.newCq(queryName, query, cqAttr);
        CQHistory history = new CQHistory(cq.getName());
        CQHistoryListener.recordHistory(history);
        Log.getLogWriter()
            .info(
                "Creating CQ with name " + queryName + ": " + query + ", cq attributes: " + cqAttr);
        Log.getLogWriter().info("Calling executeWithInitialResults on " + cq);
        CqResults rs = cq.executeWithInitialResults();
        SelectResults sr = CQUtil.getSelectResults(rs);
        if (sr == null) {
          throw new TestException(
              "For cq "
                  + cq
                  + " with name "
                  + cq.getName()
                  + " executeWithInitialResults returned "
                  + sr);
        }
        Log.getLogWriter()
            .info(
                "Done calling executeWithInitializResults on "
                    + cq
                    + " with name "
                    + queryName
                    + ", select results size is "
                    + sr.size());
        history.setSelectResults(sr);
        logNumOps();

        // log the select results
        List srList = sr.asList();
        StringBuffer aStr = new StringBuffer();
        aStr.append("SelectResults returned from " + queryName + " is\n");
        for (int i = 0; i < srList.size(); i++) {
          aStr.append(srList.get(i) + "\n");
        }
        Log.getLogWriter().info(aStr.toString());
      } catch (CqExistsException e) {
        throw new TestException(TestHelper.getStackTrace(e));
      } catch (RegionNotFoundException e) {
        throw new TestException(TestHelper.getStackTrace(e));
      } catch (CqException e) {
        throw new TestException(TestHelper.getStackTrace(e));
      }
    }
  }
  /**
   * Verify the result of the CQs registered for this VM. Query results from
   * executeWithInitialResults are combined with subsequent cq events to form the final result.
   */
  protected void verifyQueryResultsCombine() {
    Log.getLogWriter().info("In verifyQueryResultsCombine");
    Iterator it = queryMap.keySet().iterator();
    int count = 0;
    while (it.hasNext()) {
      count++;
      String cqName = (String) (it.next());
      Log.getLogWriter()
          .info("Verifying query " + count + " out of " + queryMap.size() + " with name " + cqName);
      CqQuery cq = qService.getCq(cqName);
      String queryStr = cq.getQueryString();
      String readableQueryStr = CQTest.getReadableQueryString(queryStr);

      // combine the initial selectResults with history of events
      CQHistory history = CQHistoryListener.getCQHistory(cqName);
      Map combinedMap = history.getCombinedResults();
      List combinedList = new ArrayList(combinedMap.values());
      List expectedResults = CQTestInstance.getExpectedResults(queryStr);
      List missingInCombined = new ArrayList(expectedResults);
      List unexpectedInCombined = new ArrayList(combinedList);
      unexpectedInCombined.removeAll(expectedResults);
      missingInCombined.removeAll(combinedList);

      // prepare error Strings
      StringBuffer aStr = new StringBuffer();
      if (unexpectedInCombined.size() > 0) {
        String tmpStr =
            getLocationString(unexpectedInCombined, expectedResults, history)
                + "\n"
                + "Found the following "
                + unexpectedInCombined.size()
                + " unexpected elements in combined results for cq "
                + cqName
                + ", "
                + readableQueryStr
                + ": "
                + QueryObject.toStringFull(unexpectedInCombined);
        Log.getLogWriter().info(tmpStr);
        aStr.append(tmpStr);
      }
      if (missingInCombined.size() > 0) {
        String tmpStr =
            getLocationString(missingInCombined, expectedResults, history)
                + "\n"
                + "The following "
                + missingInCombined.size()
                + " elements were missing from combined results for cq "
                + cqName
                + ", "
                + readableQueryStr
                + ": "
                + QueryObject.toStringFull(missingInCombined);
        Log.getLogWriter().info(tmpStr);
        aStr.append(tmpStr);
      }

      if (aStr.length() > 0) {
        throw new TestException(
            "Probably bug 38065: For cq "
                + cqName
                + ", "
                + readableQueryStr
                + "\n"
                + aStr.toString());
      }
    }
    Log.getLogWriter().info("Done verifying " + count + " queries");
  }
  /**
   * check distributed ops that originate in a PROXY are correctly distributed to non-proxy regions.
   */
  private void distributedOps(DataPolicy dp, InterestPolicy ip) throws CacheException {
    initOtherId();
    AttributesFactory af = new AttributesFactory();
    af.setDataPolicy(dp);
    af.setSubscriptionAttributes(new SubscriptionAttributes(ip));
    af.setScope(Scope.DISTRIBUTED_ACK);
    Region r = createRootRegion("ProxyDUnitTest", af.create());

    doCreateOtherVm();

    r.put("putkey", "putvalue1");

    getOtherVm()
        .invoke(
            new CacheSerializableRunnable("check put") {
              public void run2() throws CacheException {
                Region r = getRootRegion("ProxyDUnitTest");
                assertEquals(true, r.containsKey("putkey"));
                assertEquals("putvalue1", r.getEntry("putkey").getValue());
                r.put("putkey", "putvalue2");
              }
            });

    assertEquals(false, r.containsKey("putkey"));
    assertEquals("putvalue2", r.get("putkey")); // netsearch

    r.invalidate("putkey");

    getOtherVm()
        .invoke(
            new CacheSerializableRunnable("check invalidate") {
              public void run2() throws CacheException {
                Region r = getRootRegion("ProxyDUnitTest");
                assertEquals(true, r.containsKey("putkey"));
                assertEquals(null, r.getEntry("putkey").getValue());
              }
            });
    assertEquals(null, r.get("putkey")); // invalid so total miss

    r.destroy("putkey");

    getOtherVm()
        .invoke(
            new CacheSerializableRunnable("check destroy") {
              public void run2() throws CacheException {
                Region r = getRootRegion("ProxyDUnitTest");
                assertEquals(false, r.containsKey("putkey"));
              }
            });

    assertEquals(null, r.get("putkey")); // total miss

    r.create("createKey", "createValue1");
    getOtherVm()
        .invoke(
            new CacheSerializableRunnable("check create") {
              public void run2() throws CacheException {
                Region r = getRootRegion("ProxyDUnitTest");
                assertEquals(true, r.containsKey("createKey"));
                assertEquals("createValue1", r.getEntry("createKey").getValue());
              }
            });
    {
      Map m = new HashMap();
      m.put("putAllKey1", "putAllValue1");
      m.put("putAllKey2", "putAllValue2");
      r.putAll(m, "putAllCallback");
    }
    getOtherVm()
        .invoke(
            new CacheSerializableRunnable("check putAll") {
              public void run2() throws CacheException {
                Region r = getRootRegion("ProxyDUnitTest");
                assertEquals(true, r.containsKey("putAllKey1"));
                assertEquals("putAllValue1", r.getEntry("putAllKey1").getValue());
                assertEquals(true, r.containsKey("putAllKey2"));
                assertEquals("putAllValue2", r.getEntry("putAllKey2").getValue());
              }
            });
    r.clear();
    getOtherVm()
        .invoke(
            new CacheSerializableRunnable("check clear") {
              public void run2() throws CacheException {
                Region r = getRootRegion("ProxyDUnitTest");
                assertEquals(0, r.size());
              }
            });

    getOtherVm()
        .invoke(
            new CacheSerializableRunnable("install CacheWriter") {
              public void run2() throws CacheException {
                Region r = getRootRegion("ProxyDUnitTest");
                AttributesMutator am = r.getAttributesMutator();
                CacheWriter cw =
                    new CacheWriterAdapter() {
                      public void beforeCreate(EntryEvent event) throws CacheWriterException {
                        throw new CacheWriterException("expected");
                      }
                    };
                am.setCacheWriter(cw);
              }
            });
    try {
      r.put("putkey", "putvalue");
      fail("expected CacheWriterException");
    } catch (CacheWriterException expected) {
    }
    getOtherVm()
        .invoke(
            new CacheSerializableRunnable("check clear") {
              public void run2() throws CacheException {
                Region r = getRootRegion("ProxyDUnitTest");
                assertEquals(0, r.size());
              }
            });

    assertEquals(null, r.get("loadkey")); // total miss
    getOtherVm()
        .invoke(
            new CacheSerializableRunnable("install CacheLoader") {
              public void run2() throws CacheException {
                Region r = getRootRegion("ProxyDUnitTest");
                AttributesMutator am = r.getAttributesMutator();
                am.setCacheWriter(null); // clear csche writer
                CacheLoader cl =
                    new CacheLoader() {
                      public Object load(LoaderHelper helper) throws CacheLoaderException {
                        if (helper.getKey().equals("loadkey")) {
                          return "loadvalue";
                        } else if (helper.getKey().equals("loadexception")) {
                          throw new CacheLoaderException("expected");
                        } else {
                          return null;
                        }
                      }

                      public void close() {}
                    };
                am.setCacheLoader(cl);
              }
            });
    assertEquals("loadvalue", r.get("loadkey")); // net load
    assertEquals(null, r.get("foobar")); // total miss
    try {
      r.get("loadexception");
      fail("expected CacheLoaderException");
    } catch (CacheLoaderException expected) {
    }
    r.destroyRegion();
    getOtherVm()
        .invoke(
            new CacheSerializableRunnable("check clear") {
              public void run2() throws CacheException {
                Region r = getRootRegion("ProxyDUnitTest");
                assertEquals(null, r);
              }
            });
  }