bool waitForSample(const DataReader_var& dr)
{
  ReadCondition_var dr_rc = dr->create_readcondition(ANY_SAMPLE_STATE,
    ANY_VIEW_STATE, ALIVE_INSTANCE_STATE);
  WaitSet_var ws = new WaitSet;
  ws->attach_condition(dr_rc);
  Duration_t infinite = {DURATION_INFINITE_SEC, DURATION_INFINITE_NSEC};
  ConditionSeq active;
  ReturnCode_t ret = ws->wait(active, infinite);
  ws->detach_condition(dr_rc);
  dr->delete_readcondition(dr_rc);
  if (ret != RETCODE_OK) {
    cout << "ERROR: wait(rc) failed" << endl;
    return false;
  }
  return true;
}
int run_test_instance(DDS::DomainParticipant_ptr dp)
{
  using namespace DDS;
  using namespace OpenDDS::DCPS;
  using namespace Messenger;
  WaitSet_var ws = new WaitSet;
  MessageTypeSupport_var ts = new MessageTypeSupportImpl;
  ts->register_type(dp, "");
  CORBA::String_var type_name = ts->get_type_name();
  Topic_var topic = dp->create_topic("MyTopic", type_name,
    TOPIC_QOS_DEFAULT, 0, ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

  Publisher_var pub = dp->create_publisher(PUBLISHER_QOS_DEFAULT, 0,
    ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
  DataWriter_var dw = pub->create_datawriter(topic, DATAWRITER_QOS_DEFAULT, 0,
    ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

  Subscriber_var sub = dp->create_subscriber(SUBSCRIBER_QOS_DEFAULT, 0,
    ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
  DataReader_var dr = sub->create_datareader(topic, DATAREADER_QOS_DEFAULT, 0,
    ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

  StatusCondition_var dw_sc = dw->get_statuscondition();
  dw_sc->set_enabled_statuses(PUBLICATION_MATCHED_STATUS);
  ws->attach_condition(dw_sc);
  Duration_t infinite = {DURATION_INFINITE_SEC, DURATION_INFINITE_NSEC};
  ConditionSeq active;

  ReturnCode_t ret = ws->wait(active, infinite);
  if (ret != RETCODE_OK) return ret;

  ret = ws->detach_condition(dw_sc);
  if (ret != RETCODE_OK) return ret;

  MessageDataWriter_var mdw = MessageDataWriter::_narrow(dw);
  Message msg = {0};
  for (int i(0); i < 12; ++i) {
    ++msg.subject_id;
    ret = mdw->write(msg, HANDLE_NIL);
    if (ret != RETCODE_OK) return ret;
  }

  ReadCondition_var dr_rc = dr->create_readcondition(NOT_READ_SAMPLE_STATE,
    NEW_VIEW_STATE, ALIVE_INSTANCE_STATE);
  ReadCondition_var dr_rc2 = dr->create_readcondition(ANY_SAMPLE_STATE,
    ANY_VIEW_STATE, NOT_ALIVE_DISPOSED_INSTANCE_STATE);
  ws->attach_condition(dr_rc);
  ws->attach_condition(dr_rc2);
  MessageDataReader_var mdr = MessageDataReader::_narrow(dr);
  bool passed = true, done = false;
  while (!done) {
    ret = ws->wait(active, infinite);
    if (ret != RETCODE_OK) {
      passed = false;
      break;
    }
    cout << "wait returned" << endl;
    for (CORBA::ULong i(0); i < active.length(); ++i) {
      if (active[i] == dr_rc) {
        // To test both take_w_condition and
        // take_next_instance_w_condition, we'll limit the "take" to 3
        // samples and then use take_next_instance_w_condition.
        MessageSeq data;
        SampleInfoSeq info;
        ret = mdr->take_w_condition(data, info, 3, dr_rc);
        if (ret == RETCODE_NO_DATA) break;
        if (ret != RETCODE_OK) {
          cout << "ERROR: take_w_condition returned " << ret << endl;
          passed = false;
          done = true;
        }
        InstanceHandle_t handle = HANDLE_NIL;
        received_data(data, mdw, msg);
        handle = info[info.length() - 1].instance_handle;
        if (handle == HANDLE_NIL) {
          cout << "ERROR: instance handle is nil" << endl;
          passed = false;
          done = true;
          break;
        }
        cout << "testing take_instance_w_condition" << endl;
        while (true) {
          ret = mdr->take_instance_w_condition(data, info, 1,
                                               handle, dr_rc);
          if (ret == RETCODE_NO_DATA) break;
          if (ret != RETCODE_OK) {
            cout << "ERROR: take_instance_w_condition returned "
                 << ret << endl;
            passed = false;
            done = true;
            break;
          }
          received_data(data, mdw, msg);
        }
      } else if (active[i] == dr_rc2) {
        cout << "an instance has been disposed, exiting" << endl;
        done = true;
      }
    }
  }
  ws->detach_condition(dr_rc);
  ws->detach_condition(dr_rc2);

  dp->delete_contained_entities();
  return passed ? 0 : 1;
}
bool read_subscription_bit(const Subscriber_var& bit_sub,
                           const DomainParticipant_var& publisher,
                           const OpenDDS::DCPS::RepoId& subscriber_repo_id,
                           InstanceHandle_t& handle,
                           int user_data,
                           int topic_data,
                           bool ignored_subscription = false)
{
  OpenDDS::DCPS::Discovery_rch disc =
    TheServiceParticipant->get_discovery(publisher->get_domain_id());
  OpenDDS::DCPS::DomainParticipantImpl* publisher_impl =
    dynamic_cast<OpenDDS::DCPS::DomainParticipantImpl*>(publisher.in());

  DataReader_var dr = bit_sub->lookup_datareader(BUILT_IN_SUBSCRIPTION_TOPIC);
  if (!ignored_subscription) {
    ReadCondition_var rc = dr->create_readcondition(ANY_SAMPLE_STATE,
                                                    ANY_VIEW_STATE,
                                                    ALIVE_INSTANCE_STATE);
    WaitSet_var waiter = new WaitSet;
    waiter->attach_condition(rc);
    ConditionSeq activeConditions;
    Duration_t forever = { DURATION_INFINITE_SEC,
                           DURATION_INFINITE_NSEC };
    ReturnCode_t result = waiter->wait(activeConditions, forever);
    waiter->detach_condition(rc);
    if (result != RETCODE_OK) {
      ACE_DEBUG((LM_ERROR,
        "ERROR: %P (subscription BIT) could not wait for condition: %d\n", result));
      return false;
    }
  } else {
    ACE_OS::sleep(1);
  }
  SubscriptionBuiltinTopicDataDataReader_var pub_bit =
    SubscriptionBuiltinTopicDataDataReader::_narrow(dr);

  SubscriptionBuiltinTopicDataSeq data;
  SampleInfoSeq infos;
  ReturnCode_t ret =
    pub_bit->read(data, infos, LENGTH_UNLIMITED,
                  ANY_SAMPLE_STATE, ANY_VIEW_STATE, ALIVE_INSTANCE_STATE);
  if (ignored_subscription && (ret != RETCODE_NO_DATA)) {
    ACE_DEBUG((LM_ERROR, "ERROR: %P could not read ignored subscription BIT: %d\n",
               ret));
    return false;
  } else if (ret != RETCODE_OK && ret != RETCODE_NO_DATA) {
    ACE_DEBUG((LM_ERROR, "ERROR: %P could not read subscription BIT: %d\n", ret));
    return false;
  }

  int num_valid = 0;
  bool found_subscriber = false;
  for (CORBA::ULong i = 0; i < data.length(); ++i) {
    if (infos[i].valid_data) {
      ++num_valid;

      OpenDDS::DCPS::RepoId repo_id =
        disc->bit_key_to_repo_id(publisher_impl,
                                 OpenDDS::DCPS::BUILT_IN_PARTICIPANT_TOPIC,
                                 data[i].participant_key);

      OpenDDS::DCPS::GuidConverter converter(repo_id);

      ACE_DEBUG((LM_DEBUG,
                 "%P Read Subscription BIT with key: %x %x %x and handle %d\n"
                 "\tParticipant's GUID=%C\n\tTopic: %C\tType: %C\n",
                 data[i].key.value[0], data[i].key.value[1],
                 data[i].key.value[2], infos[i].instance_handle,
                 std::string(converter).c_str (), data[i].topic_name.in(),
                 data[i].type_name.in()));
      if (repo_id == subscriber_repo_id) {
        found_subscriber = true;
        if (data[i].user_data.value.length() != 1) {
          ACE_ERROR_RETURN((LM_ERROR,
                            "ERROR: %P subscription [%d] user data length %d "
                            "not expected length of 1\n",
                            i,
                            data[i].user_data.value.length()),
                           false);
        }
        if (data[i].topic_data.value.length() != 1) {
          ACE_ERROR_RETURN((LM_ERROR,
                            "ERROR: %P subscription [%d] topic data length %d "
                            "not expected length of 1\n",
                            i,
                            data[i].topic_data.value.length()),
                           false);
        }
        if (data[i].user_data.value[0] != user_data) {
          ACE_ERROR_RETURN((LM_ERROR,
                            "ERROR: %P subscription [%d] user data value %d "
                            "not expected value %d\n",
                            i,
                            data[i].user_data.value[0],
                            user_data),
                           false);
        }
        if (data[i].topic_data.value[0] != topic_data) {
          ACE_ERROR_RETURN((LM_ERROR,
                            "ERROR: %P subscription [%d] topic data value %d "
                            "not expected value %d\n",
                            i,
                            data[i].topic_data.value[0],
                            topic_data),
                           false);
        }
      }
      handle = infos[i].instance_handle;
    }
  }
  if (ignored_subscription) {
    if (num_valid != 0) {
      ACE_ERROR_RETURN((LM_ERROR, "ERROR: %P expected 0 discovered "
                        "subscriptions, found %d\n",
                        num_valid), false);
    }
  }
  else {
    if (num_valid != 1) {
      ACE_ERROR_RETURN((LM_ERROR, "ERROR: %P expected 1 discovered "
                        "subscriptions, found %d\n",
                        num_valid), false);
    }
    if (!found_subscriber) {
      ACE_ERROR_RETURN((LM_ERROR, "ERROR: %P did not find expected subscription\n"), false);
    }
  }

  return true;
}
bool run_test(DomainParticipant_var& dp_sub,
              DomainParticipant_var& dp_pub)
{
  OpenDDS::DCPS::RepoId sub_repo_id, pub_repo_id;

  {
    OpenDDS::DCPS::DomainParticipantImpl* dp_impl =
      dynamic_cast<OpenDDS::DCPS::DomainParticipantImpl*>(dp_sub.in());
    sub_repo_id = dp_impl->get_id ();
    OpenDDS::DCPS::GuidConverter converter(sub_repo_id);
    ACE_DEBUG ((LM_DEBUG,
                ACE_TEXT("%P ")
                ACE_TEXT("Sub Domain Participant GUID=%C\n"),
                std::string(converter).c_str()));
  }

  {
    OpenDDS::DCPS::DomainParticipantImpl* dp_impl =
      dynamic_cast<OpenDDS::DCPS::DomainParticipantImpl*>(dp_pub.in());
    pub_repo_id = dp_impl->get_id ();
    OpenDDS::DCPS::GuidConverter converter(pub_repo_id);
    ACE_DEBUG ((LM_DEBUG,
                ACE_TEXT("%P ")
                ACE_TEXT("Pub Domain Participant GUID=%C\n"),
                std::string(converter).c_str()));
  }

  // If we are running with an rtps_udp transport, it can't be shared between
  // participants.
  TransportConfig_rch cfg = TheTransportRegistry->get_config("dp1");
  if (!cfg.is_nil()) {
    TheTransportRegistry->bind_config(cfg, dp_sub);
  }
  cfg = TheTransportRegistry->get_config("dp2");
  if (!cfg.is_nil()) {
    TheTransportRegistry->bind_config(cfg, dp_pub);
  }

  Subscriber_var bit_sub = dp_sub->get_builtin_subscriber();

  if (!read_participant_bit(bit_sub, dp_sub, pub_repo_id, TestConfig::PARTICIPANT_USER_DATA())) {
    return false;
  }

  // Each domain participant's handle to the other
  InstanceHandle_t dp_sub_ih, dp_pub_ih;
  InstanceHandle_t pub_ih, sub_ih, ig_ih;

  if (!(check_discovered_participants(dp_sub, dp_pub_ih) &&
        check_discovered_participants(dp_pub, dp_sub_ih)))
  {
    return false;
  }

  DataWriter_var dw = create_data_writer(dp_pub);
  if (!dw) {
    ACE_DEBUG((LM_ERROR, "ERROR: %P could not create Data Writer (participant 2)\n"));
    return false;
  }

  if (!read_publication_bit(bit_sub, dp_sub, pub_repo_id, pub_ih, TestConfig::DATA_WRITER_USER_DATA(), TestConfig::TOPIC_DATA(), 1, 1)) {
    return false;
  }

  DataReader_var dr = create_data_reader(dp_sub);
  if (!dr) {
    ACE_DEBUG((LM_ERROR, "ERROR: %P could not create Data Reader (participant 1)\n"));
    return false;
  }
  if (!read_subscription_bit(dp_pub->get_builtin_subscriber(), dp_pub, sub_repo_id, sub_ih, TestConfig::DATA_READER_USER_DATA(), TestConfig::TOPIC_DATA())) {
    return false;
  }

  // Wait for the reader to associate with the writer.
  WriterSync::wait_match(dw);

  // Remove the writer and its topic, then re-create them.  The writer's
  // participant should still have discovery info about the reader so that
  // the association between the new writer and old reader can be established.
  recreate_data_writer_and_topic(dw, dr);

  // Wait for the reader to associate with the writer.
  WriterSync::wait_match(dw);

  // The new writer is associated with the reader, but the reader may still
  // also be associated with the old writer.
  wait_match(dr, 1);

  // Get the new instance handle as pub_ih
  if (!read_publication_bit(bit_sub, dp_sub, pub_repo_id, pub_ih, TestConfig::DATA_WRITER_USER_DATA(), TestConfig::TOPIC_DATA(), 1, 2)) {
    return false;
  }

  TestMsgDataWriter_var tmdw = TestMsgDataWriter::_narrow(dw);
  const TestMsg msg = {42};
  tmdw->write(msg, HANDLE_NIL);

  ReadCondition_var rc = dr->create_readcondition(ANY_SAMPLE_STATE,
                                                  ANY_VIEW_STATE,
                                                  ALIVE_INSTANCE_STATE);
  WaitSet_var waiter = new WaitSet;
  waiter->attach_condition(rc);
  ConditionSeq activeConditions;
  const Duration_t timeout = { 90, 0 };
  ReturnCode_t result = waiter->wait(activeConditions, timeout);
  waiter->detach_condition(rc);
  if (result != RETCODE_OK) {
    ACE_DEBUG((LM_ERROR,
      "ERROR: %P TestMsg reader could not wait for condition: %d\n", result));
    return false;
  }

  TestMsgDataReader_var tmdr = TestMsgDataReader::_narrow(dr);

  TestMsgSeq data;
  SampleInfoSeq infos;
  ReturnCode_t ret = tmdr->read_w_condition(data, infos, LENGTH_UNLIMITED, rc);
  if (ret != RETCODE_OK) {
    ACE_DEBUG((LM_ERROR, "ERROR: %P could not read TestMsg: %d\n", ret));
    return false;
  }

  bool ok = false;
  for (CORBA::ULong i = 0; i < data.length(); ++i) {
    if (infos[i].valid_data) {
      ok = true;
      ACE_DEBUG((LM_DEBUG, "%P Read data sample: %d\n", data[i].value));
    }
  }

  if (!ok) {
    ACE_DEBUG((LM_ERROR, "ERROR: %P no valid data from TestMsg data reader\n"));
  }

  // Change dp qos
  {
    DomainParticipantQos dp_qos;
    dp_pub->get_qos(dp_qos);
    set_qos(dp_qos.user_data.value, TestConfig::PARTICIPANT_USER_DATA2());
    dp_pub->set_qos(dp_qos);
  }
  // Change dw qos
  {
    DataWriterQos dw_qos;
    dw->get_qos(dw_qos);
    set_qos(dw_qos.user_data.value, TestConfig::DATA_WRITER_USER_DATA2());
    dw->set_qos(dw_qos);
  }
  // Change dr qos
  {
    DataReaderQos dr_qos;
    dr->get_qos(dr_qos);
    set_qos(dr_qos.user_data.value, TestConfig::DATA_READER_USER_DATA2());
    dr->set_qos(dr_qos);
  }
  // Wait for propagation
  ACE_OS::sleep(3);
  if (!read_participant_bit(bit_sub, dp_sub, pub_repo_id, TestConfig::PARTICIPANT_USER_DATA2())) {
    return false;
  }
  if (!read_publication_bit(bit_sub, dp_sub, pub_repo_id, ig_ih, TestConfig::DATA_WRITER_USER_DATA2(), TestConfig::TOPIC_DATA(), 1, 1)) {
    return false;
  }
  if (!read_subscription_bit(dp_pub->get_builtin_subscriber(), dp_pub, sub_repo_id, ig_ih, TestConfig::DATA_READER_USER_DATA2(), TestConfig::TOPIC_DATA())) {
    return false;
  }

  // Set dw topic qos
  Topic_var topic = dw->get_topic();
  TopicQos topic_qos;
  topic->get_qos(topic_qos);
  set_qos(topic_qos.topic_data.value, TestConfig::TOPIC_DATA2());
  topic->set_qos(topic_qos);

  // Set dr topic qos
  TopicDescription_var topic_desc = dr->get_topicdescription();
  topic = Topic::_narrow(topic_desc);
  topic->get_qos(topic_qos);
  set_qos(topic_qos.topic_data.value, TestConfig::TOPIC_DATA2());
  topic->set_qos(topic_qos);

  // Wait for propagation
  ACE_OS::sleep(3);
  if (!read_publication_bit(bit_sub, dp_sub, pub_repo_id, ig_ih, TestConfig::DATA_WRITER_USER_DATA2(), TestConfig::TOPIC_DATA2(), 1, 1)) {
    return false;
  }
  if (!read_subscription_bit(dp_pub->get_builtin_subscriber(), dp_pub, sub_repo_id, ig_ih, TestConfig::DATA_READER_USER_DATA2(), TestConfig::TOPIC_DATA2())) {
    return false;
  }

  // Test ignore
  dp_sub->ignore_publication(pub_ih);
  if (!read_publication_bit(bit_sub, dp_sub, pub_repo_id, pub_ih, TestConfig::DATA_WRITER_USER_DATA2(), TestConfig::TOPIC_DATA2(), 0, 0)) {
    ACE_ERROR_RETURN((LM_ERROR,
                     ACE_TEXT("ERROR: %P Could not ignore publication\n")), false);
  }

  dp_pub->ignore_subscription(sub_ih);
  if (!read_subscription_bit(dp_pub->get_builtin_subscriber(), dp_pub, sub_repo_id, sub_ih, TestConfig::DATA_READER_USER_DATA2(), TestConfig::TOPIC_DATA2(), true)) {
    ACE_ERROR_RETURN((LM_ERROR,
                     ACE_TEXT("ERROR: %P Could not ignore subscription\n")), false);
  }

  dp_sub->ignore_participant(dp_pub_ih);
  InstanceHandleSeq handles;
  dp_sub->get_discovered_participants(handles);
  // Check that the handle is no longer in the sequence.
  for (CORBA::ULong i = 0; i < handles.length (); ++i) {
    if (handles[i] == dp_pub_ih) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("ERROR: %P Could not ignore participant\n")), false);

    }
  }

  return ok;
}
bool read_participant_bit(const Subscriber_var& bit_sub,
                          const DomainParticipant_var& dp,
                          const OpenDDS::DCPS::RepoId& other_dp_repo_id,
                          int user_data)
{
  OpenDDS::DCPS::Discovery_rch disc =
    TheServiceParticipant->get_discovery(dp->get_domain_id());
  OpenDDS::DCPS::DomainParticipantImpl* dp_impl =
    dynamic_cast<OpenDDS::DCPS::DomainParticipantImpl*>(dp.in());

  DataReader_var dr = bit_sub->lookup_datareader(BUILT_IN_PARTICIPANT_TOPIC);
  ReadCondition_var rc = dr->create_readcondition(ANY_SAMPLE_STATE,
                                                  ANY_VIEW_STATE,
                                                  ALIVE_INSTANCE_STATE);
  WaitSet_var waiter = new WaitSet;
  waiter->attach_condition(rc);
  ConditionSeq activeConditions;
  Duration_t forever = { DURATION_INFINITE_SEC,
                         DURATION_INFINITE_NSEC };
  ReturnCode_t result = waiter->wait(activeConditions, forever);
  waiter->detach_condition(rc);
  if (result != RETCODE_OK) {
    ACE_ERROR_RETURN((LM_ERROR, "ERROR: %P could not wait for condition: %d\n", result), false);
  }

  ParticipantBuiltinTopicDataDataReader_var part_bit =
    ParticipantBuiltinTopicDataDataReader::_narrow(dr);

  ParticipantBuiltinTopicDataSeq data;
  SampleInfoSeq infos;
  ReturnCode_t ret =
    part_bit->read_w_condition(data, infos, LENGTH_UNLIMITED, rc);
  if (ret != RETCODE_OK) {
    ACE_DEBUG((LM_ERROR, "ERROR: %P could not read participant BIT: %d\n", ret));
    return false;
  }

  bool found_other_dp = false;
  int num_valid = 0;

  for (CORBA::ULong i = 0; i < data.length(); ++i) {
    if (infos[i].valid_data) {
      ++num_valid;
      OpenDDS::DCPS::RepoId repo_id =
        disc->bit_key_to_repo_id(dp_impl,
                                 OpenDDS::DCPS::BUILT_IN_PARTICIPANT_TOPIC,
                                 data[i].key);

      OpenDDS::DCPS::GuidConverter converter(repo_id);
      ACE_DEBUG((LM_DEBUG,
                 ACE_TEXT("%P ")
                 ACE_TEXT("Read Participant BIT GUID=%C handle=%d\n"),
                 std::string(converter).c_str(), infos[i].instance_handle));

      if (repo_id == other_dp_repo_id) {
        if (data[i].user_data.value.length() != 1) {
          ACE_ERROR_RETURN((LM_ERROR,
                            "ERROR: %P participant[%d] user data length %d "
                            "not expected length of 1\n",
                            i,
                            data[i].user_data.value.length()),
                           false);
        }

        if (data[i].user_data.value[0] != user_data) {
          ACE_ERROR_RETURN((LM_ERROR,
                            "ERROR: %P participant[%d] user data value %d "
                            "not expected value %d\n",
                            i,
                            data[i].user_data.value[0],
                            user_data),
                           false);
        }

        found_other_dp = true;
      }
    }
  }

  if (num_valid != 1) {
    ACE_DEBUG((LM_ERROR, "ERROR: %P expected to discover 1 other participant, found %d\n", data.length ()));
  }

  part_bit->return_loan(data, infos);

  if (!found_other_dp) {
    ACE_ERROR_RETURN((LM_ERROR, "ERROR: %P did not find expected participant\n"), false);
  }

  return true;
}