/**
 * Handles zero copy message sets. Consider your requirements and edit timeout nad matched status bits as needed.
 * QoS should drive all of you design decisions.
 */
void CAppNodeImpl::HandleWaitCondition()
{
	// Block until Subscriber is available
	DDS::StatusCondition_var condition = _writer->get_statuscondition();
	condition->set_enabled_statuses( DDS::PUBLICATION_MATCHED_STATUS );

	DDS::WaitSet_var waitSet = new DDS::WaitSet;
	waitSet->attach_condition( condition );

	DDS::ConditionSeq conditions;
	DDS::SubscriptionMatchedStatus matches = { 0, 0, 0, 0, 0 };
	DDS::Duration_t timeout = { 30, 0 };

	if ( waitSet->wait(conditions, timeout ) != DDS::RETCODE_OK )
	{
		LOG( ERROR ) << "wait condition failed.";
	}

	if ( _reader->get_subscription_matched_status( matches ) != DDS::RETCODE_OK )
	{
		LOG( ERROR ) << "Publication matched status failed.";
	}

	waitSet->detach_condition( condition );
}
Beispiel #2
0
int
OpenDDS::Model::WriterSync::wait_unmatch(const DDS::DataWriter_var& writer,
                                         unsigned int num_readers)
{
  DDS::ReturnCode_t stat;
  DDS::StatusCondition_var condition = writer->get_statuscondition();
  condition->set_enabled_statuses(DDS::PUBLICATION_MATCHED_STATUS);
  DDS::WaitSet_var ws = new DDS::WaitSet;
  ws->attach_condition(condition);
  DDS::ConditionSeq conditions;
  DDS::PublicationMatchedStatus ms = { 0, 0, 0, 0, 0 };
  DDS::Duration_t timeout = { 1, 0 };
  do {
    if (DCPS_debug_level > 4) {
      ACE_DEBUG((LM_NOTICE, ACE_TEXT("WriterSync: pub checking unmatched\n")));
    }
    stat = writer->get_publication_matched_status(ms);
    if (stat != DDS::RETCODE_OK) {
      ACE_ERROR_RETURN((
                  LM_ERROR,
                  ACE_TEXT("(%P|%t) ERROR: %N:%l: wait_unmatch() -")
                  ACE_TEXT(" get_publication_matched_status failed!\n")),
                 -1);
    } else if (ms.current_count == 0 && (unsigned int)ms.total_count >= num_readers) {
      if (DCPS_debug_level > 4) {
        ACE_DEBUG((LM_NOTICE, ACE_TEXT("WriterSync: pub match count %d total count %d\n"),
                                       ms.current_count, ms.total_count));
      }
      break;  // unmatched
    }
    if (DCPS_debug_level > 4) {
      ACE_DEBUG((LM_NOTICE, ACE_TEXT("WriterSync: pub match count %d total count %d\n"),
                                     ms.current_count, ms.total_count));
    }
    // wait for a change
    stat = ws->wait(conditions, timeout);
    if ((stat != DDS::RETCODE_OK) && (stat != DDS::RETCODE_TIMEOUT)) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("(%P|%t) ERROR: %N:%l: wait_unmatch() -")
                        ACE_TEXT(" wait failed!\n")),
                       -1);
    }
  } while (true);
  ws->detach_condition(condition);
  if (DCPS_debug_level > 4) {
    ACE_DEBUG((LM_NOTICE, ACE_TEXT("WriterSync: pub unmatched\n")));
  }
  return 0;
}
Beispiel #3
0
bool
wait_subscription_matched_status(const Options& /*opts*/, const DDS::DataReader_ptr r)
{
  //  To check the match status ?
  DDS::SubscriptionMatchedStatus matches = {0, 0, 0, 0, 0};
  TEST_ASSERT((r->get_subscription_matched_status(matches) == ::DDS::RETCODE_OK));

  // Block until Subscriber is available
  DDS::StatusCondition_var condition = r->get_statuscondition();
  condition->set_enabled_statuses(DDS::PUBLICATION_MATCHED_STATUS
                                  | DDS::SUBSCRIPTION_MATCHED_STATUS
                                  //                                  | DDS::REQUESTED_INCOMPATIBLE_QOS_STATUS
                                  //                                  | DDS::OFFERED_INCOMPATIBLE_QOS_STATUS
                                  );

  DDS::WaitSet_var ws = new DDS::WaitSet;
  ws->attach_condition(condition);

//  int duration = opts.test_duration;
  DDS::Duration_t timeout = {
    DDS::DURATION_INFINITE_SEC,
    DDS::DURATION_INFINITE_NSEC
//    (duration < 0) ? DDS::DURATION_INFINITE_SEC : duration,
//    (duration < 0) ? DDS::DURATION_INFINITE_NSEC : 0
  };

  DDS::ConditionSeq conditions;

  int status = ws->wait(conditions, timeout);
  ws->detach_condition(condition);

  if (status != DDS::RETCODE_OK)
    {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("(%P|%t)")
                        ACE_TEXT(" ERROR: wait failed: %p\n")), false);
    }

  return true;
}
int
ParticipantTask::svc()
{
    try
    {
        ACE_DEBUG((LM_INFO, ACE_TEXT("(%P|%t)    -> PARTICIPANT STARTED\n")));

        ACE_Time_Value delay_between_pubs(0, this->delay_between_pubs_msec_ * 1000);

        DDS::DomainParticipantFactory_var dpf = TheParticipantFactory;
        // Create Participant
        DDS::DomainParticipant_var participant =
            dpf->create_participant(42,
                                    PARTICIPANT_QOS_DEFAULT,
                                    DDS::DomainParticipantListener::_nil(),
                                    ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

        if (CORBA::is_nil(participant.in()))
            ACE_ERROR_RETURN((LM_ERROR,
                              ACE_TEXT("%N:%l: svc()")
                              ACE_TEXT(" create_participant failed!\n")), 1);

        // Create Publisher
        DDS::Publisher_var publisher =
            participant->create_publisher(PUBLISHER_QOS_DEFAULT,
                                          DDS::PublisherListener::_nil(),
                                          ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

        if (CORBA::is_nil(publisher.in()))
            ACE_ERROR_RETURN((LM_ERROR,
                              ACE_TEXT("%N:%l: svc()")
                              ACE_TEXT(" create_publisher failed!\n")), 1);


        // Register Type (FooType)
        FooTypeSupport_var ts = new FooTypeSupportImpl;
        if (ts->register_type(participant.in(), "") != DDS::RETCODE_OK)
            ACE_ERROR_RETURN((LM_ERROR,
                              ACE_TEXT("%N:%l: svc()")
                              ACE_TEXT(" register_type failed!\n")), 1);

        // Create Topic (FooTopic)
        DDS::Topic_var topic =
            participant->create_topic("FooTopic",
                                      ts->get_type_name(),
                                      TOPIC_QOS_DEFAULT,
                                      DDS::TopicListener::_nil(),
                                      ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

        if (CORBA::is_nil(topic.in()))
            ACE_ERROR_RETURN((LM_ERROR,
                              ACE_TEXT("%N:%l: svc()")
                              ACE_TEXT(" create_topic failed!\n")), 1);

        // Create DataWriter
        DDS::DataWriterQos writer_qos;
        publisher->get_default_datawriter_qos(writer_qos);

        writer_qos.history.depth = samples_per_thread_;

        if (deadline_.sec > 0 || deadline_.nanosec > 0)
        {
            writer_qos.deadline.period.sec = deadline_.sec;
            writer_qos.deadline.period.nanosec = deadline_.nanosec;
        }

        DDS::DataWriter_var writer =
            publisher->create_datawriter(topic.in(),
                                         writer_qos,
                                         DDS::DataWriterListener::_nil(),
                                         ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

        if (CORBA::is_nil(writer.in()))
            ACE_ERROR_RETURN((LM_ERROR,
                              ACE_TEXT("%N:%l: svc()")
                              ACE_TEXT(" create_datawriter failed!\n")), 1);

        FooDataWriter_var writer_i = FooDataWriter::_narrow(writer);
        if (CORBA::is_nil(writer_i))
            ACE_ERROR_RETURN((LM_ERROR,
                              ACE_TEXT("%N:%l: svc()")
                              ACE_TEXT(" _narrow failed!\n")), 1);

        // Block until Subscriber is available
        DDS::StatusCondition_var cond = writer->get_statuscondition();
        cond->set_enabled_statuses(DDS::PUBLICATION_MATCHED_STATUS);

        DDS::WaitSet_var ws = new DDS::WaitSet;
        ws->attach_condition(cond);

        DDS::Duration_t timeout =
        { DDS::DURATION_INFINITE_SEC, DDS::DURATION_INFINITE_NSEC };

        DDS::ConditionSeq conditions;
        DDS::PublicationMatchedStatus matches = {0, 0, 0, 0, 0};
        do
        {
            if (ws->wait(conditions, timeout) != DDS::RETCODE_OK)
                ACE_ERROR_RETURN((LM_ERROR,
                                  ACE_TEXT("%N:%l: svc()")
                                  ACE_TEXT(" wait failed!\n")), 1);

            if (writer->get_publication_matched_status(matches) != ::DDS::RETCODE_OK)
            {
                ACE_ERROR ((LM_ERROR,
                            "(%P|%t) ERROR: failed to get publication matched status\n"));
                ACE_OS::exit (1);
            }
        }
        while (matches.current_count < 1);

        ws->detach_condition(cond);

        // The following is intentionally inefficient to stress various
        // pathways related to publication; we should be especially dull
        // and write only one sample at a time per writer.

        ProgressIndicator progress("(%P|%t)       PARTICIPANT %d%% (%d samples sent)\n",
                                   samples_per_thread_);

        for (std::size_t i = 0; i < samples_per_thread_; ++i)
        {
            Foo foo;
            foo.key = 3;
            DDS::InstanceHandle_t handle = writer_i->register_instance(foo);

            if (writer_i->write(foo, handle) != DDS::RETCODE_OK)
                ACE_ERROR_RETURN((LM_ERROR,
                                  ACE_TEXT("%N:%l: svc()")
                                  ACE_TEXT(" write failed!\n")), 1);
            ++progress;
            ACE_OS::sleep(delay_between_pubs);
        }

        DDS::Duration_t interval = { 30, 0};
        if( DDS::RETCODE_OK != writer->wait_for_acknowledgments( interval)) {
            ACE_ERROR_RETURN((LM_ERROR,
                              ACE_TEXT("(%P:%t) ERROR: svc() - ")
                              ACE_TEXT("timed out waiting for acks!\n")
                             ), 1);
        }
        publisher->delete_datawriter(writer);

        // Clean-up!
        participant->delete_contained_entities();
        dpf->delete_participant(participant.in());
    }
    catch (const CORBA::Exception& e)
    {
        e._tao_print_exception("caught in svc()");
        return 1;
    }

    ACE_DEBUG((LM_INFO, ACE_TEXT("(%P|%t)    <- PARTICIPANT FINISHED\n")));

    return 0;
}
Beispiel #5
0
int ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
 try {
     // Initialize DomainParticipantFactory
     DDS::DomainParticipantFactory_var dpf =
       TheParticipantFactoryWithArgs(argc, argv);

     int error;
     if ((error = parse_args(argc, argv)) != 0) {
       return error;
     }

    // Create DomainParticipant
    DDS::DomainParticipant_var participant =
      dpf->create_participant(4,
                              PARTICIPANT_QOS_DEFAULT,
                              0,
                              OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (!participant) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("ERROR: %N:%l: main() -")
                        ACE_TEXT(" create_participant failed!\n")),
                       -1);
    }

    ACE_DEBUG((LM_DEBUG, "(%P|%t) Start publisher\n"));

    {
      // Register TypeSupport (Messenger::Message)
      Messenger::MessageTypeSupport_var ts =
        new Messenger::MessageTypeSupportImpl;

      if (ts->register_type(participant, "Messenger") != DDS::RETCODE_OK) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("ERROR: %N:%l: main() -")
                          ACE_TEXT(" register_type failed!\n")),
                         -1);
      }

      // Create Topic (Movie Discussion List)
      CORBA::String_var type_name = ts->get_type_name();
      ACE_DEBUG((LM_DEBUG, "registered type name = %s\n", type_name.in()));

      DDS::Topic_var topic =
        participant->create_topic("Movie Discussion List",
                                  type_name,
                                  TOPIC_QOS_DEFAULT,
                                  0,
                                  OpenDDS::DCPS::DEFAULT_STATUS_MASK);

      if (!topic) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("ERROR: %N:%l: main() -")
                          ACE_TEXT(" create_topic failed!\n")),
                         -1);
      }

      // setup partition
      DDS::PublisherQos pub_qos;
      participant->get_default_publisher_qos(pub_qos);

      DDS::StringSeq my_partition;
      my_partition.length(1);
      my_partition[0] = "One";
      pub_qos.partition.name = my_partition;

      // Create Publisher
      DDS::Publisher_var publisher =
        participant->create_publisher(pub_qos,
                                      0,
                                      OpenDDS::DCPS::DEFAULT_STATUS_MASK);

      if (!publisher) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("ERROR: %N:%l: main() -")
                          ACE_TEXT(" create_publisher failed!\n")),
                         -1);
      }

      // Create DataWriter
      DDS::DataWriter_var writer =
        publisher->create_datawriter(topic,
                                     DATAWRITER_QOS_DEFAULT,
                                     0,
                                     OpenDDS::DCPS::DEFAULT_STATUS_MASK);

      if (!writer) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("ERROR: %N:%l: main() -")
                          ACE_TEXT(" create_datawriter failed!\n")),
                         -1);
      }

      Messenger::MessageDataWriter_var message_writer =
        Messenger::MessageDataWriter::_narrow(writer);

      if (!message_writer) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("ERROR: %N:%l: main() -")
                          ACE_TEXT(" _narrow failed!\n")),
                         -1);
      }

      // Block until Subscriber is available
      DDS::StatusCondition_var condition = writer->get_statuscondition();
      condition->set_enabled_statuses(DDS::PUBLICATION_MATCHED_STATUS);

      DDS::WaitSet_var ws = new DDS::WaitSet;
      ws->attach_condition(condition);

      while (true) {
        DDS::PublicationMatchedStatus matches;
        if (writer->get_publication_matched_status(matches) != ::DDS::RETCODE_OK) {
          ACE_ERROR_RETURN((LM_ERROR,
                            ACE_TEXT("ERROR: %N:%l: main() -")
                            ACE_TEXT(" get_publication_matched_status failed!\n")),
                           -1);
        }

        if (matches.current_count >= 1) {
          break;
        }

        DDS::ConditionSeq conditions;
        DDS::Duration_t timeout = { 60, 0 };
        if (ws->wait(conditions, timeout) != DDS::RETCODE_OK) {
          ACE_ERROR_RETURN((LM_ERROR,
                            ACE_TEXT("ERROR: %N:%l: main() -")
                            ACE_TEXT(" wait failed!\n")),
                           -1);
        }
      }

      ws->detach_condition(condition);

      // Write samples
      Messenger::Message message;
      message.subject_id = 99;

      message.from       = "Comic Book Guy";
      message.subject    = "Review";
      message.text       = "Worst. Movie. Ever.";
      message.count      = 0;

      for (int i = 0; i < 10; ++i) {
        DDS::ReturnCode_t error = message_writer->write(message, DDS::HANDLE_NIL);
        ++message.count;
        ++message.subject_id;

        if (error != DDS::RETCODE_OK) {
          ACE_ERROR((LM_ERROR,
                     ACE_TEXT("ERROR: %N:%l: main() -")
                     ACE_TEXT(" write returned %d!\n"), error));
        }
      }
    }

    ACE_DEBUG((LM_DEBUG, "(%P|%t) Stop publisher\n"));

    // Clean-up!
    participant->delete_contained_entities();
    dpf->delete_participant(participant);

    TheServiceParticipant->shutdown();

  } catch (const CORBA::Exception& e) {
    e._tao_print_exception("Exception caught in main():");
    return -1;
  }

  ACE_DEBUG((LM_DEBUG, "(%P|%t) Publisher exiting\n"));

  return 0;
}
Beispiel #6
0
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  try {
    // Initialize DomainParticipantFactory
    DDS::DomainParticipantFactory_var dpf =
      TheParticipantFactoryWithArgs(argc, argv);

    // Create DomainParticipant
    DDS::DomainParticipant_var participant =
      dpf->create_participant(42,
                              PARTICIPANT_QOS_DEFAULT,
                              DDS::DomainParticipantListener::_nil(),
                              OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (CORBA::is_nil(participant.in())) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("ERROR: %N:%l: main() -")
                        ACE_TEXT(" create_participant failed!\n")),
                       -1);
    }

    // Register TypeSupport (Messenger::Message)
    Messenger::MessageTypeSupport_var ts =
      new Messenger::MessageTypeSupportImpl();

    if (ts->register_type(participant.in(), "") != DDS::RETCODE_OK) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("ERROR: %N:%l: main() -")
                        ACE_TEXT(" register_type failed!\n")),
                       -1);
    }

    // Create Topic (Movie Discussion List)
    CORBA::String_var type_name = ts->get_type_name();
    DDS::Topic_var topic =
      participant->create_topic("Movie Discussion List",
                                type_name.in(),
                                TOPIC_QOS_DEFAULT,
                                DDS::TopicListener::_nil(),
                                OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (CORBA::is_nil(topic.in())) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("ERROR: %N:%l: main() -")
                        ACE_TEXT(" create_topic failed!\n")),
                       -1);
    }

    // Create Publisher
    DDS::Publisher_var publisher =
      participant->create_publisher(PUBLISHER_QOS_DEFAULT,
                                    DDS::PublisherListener::_nil(),
                                    OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (CORBA::is_nil(publisher.in())) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("ERROR: %N:%l: main() -")
                        ACE_TEXT(" create_publisher failed!\n")),
                       -1);
    }

    // Create DataWriter
    DDS::DataWriter_var writer =
      publisher->create_datawriter(topic.in(),
                                   DATAWRITER_QOS_DEFAULT,
                                   DDS::DataWriterListener::_nil(),
                                   OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (CORBA::is_nil(writer.in())) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("ERROR: %N:%l: main() -")
                        ACE_TEXT(" create_datawriter failed!\n")),
                       -1);
    }

    Messenger::MessageDataWriter_var message_writer =
      Messenger::MessageDataWriter::_narrow(writer.in());

    if (CORBA::is_nil(message_writer.in())) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("ERROR: %N:%l: main() -")
                          ACE_TEXT(" _narrow failed!\n")),
                         -1);
    }

    // Block until Subscriber is available
    DDS::StatusCondition_var condition = writer->get_statuscondition();
    condition->set_enabled_statuses(DDS::PUBLICATION_MATCHED_STATUS);

    DDS::WaitSet_var ws = new DDS::WaitSet;
    ws->attach_condition(condition);

    DDS::ConditionSeq conditions;
    DDS::PublicationMatchedStatus matches = { 0, 0, 0, 0, 0 };
    DDS::Duration_t timeout = { 30, 0 };

    do {
      if (ws->wait(conditions, timeout) != DDS::RETCODE_OK) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("ERROR: %N:%l: main() -")
                          ACE_TEXT(" wait failed!\n")),
                         -1);
      }

      if (writer->get_publication_matched_status(matches) != ::DDS::RETCODE_OK) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("ERROR: %N:%l: main() -")
                          ACE_TEXT(" get_publication_matched_status failed!\n")),
                         -1);
      }

    } while (matches.current_count < 1);

    ws->detach_condition(condition);

    // Write samples
    Messenger::Message message;
    message.subject_id = 99;

    message.from       = CORBA::string_dup("Comic Book Guy");
    message.subject    = CORBA::string_dup("Review");
    message.text       = CORBA::string_dup("Worst. Movie. Ever.");
    message.count      = 0;

    for (int i = 0; i < 10; i++) {
      DDS::ReturnCode_t error = message_writer->write(message, DDS::HANDLE_NIL);

      if (error != DDS::RETCODE_OK) {
        ACE_ERROR((LM_ERROR,
                   ACE_TEXT("ERROR: %N:%l: main() -")
                   ACE_TEXT(" write returned %d!\n"), error));
      }
    }

    // Wait for samples to be acknowledged
    if (message_writer->wait_for_acknowledgments(timeout) != DDS::RETCODE_OK) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("ERROR: %N:%l: main() -")
                        ACE_TEXT(" wait_for_acknowledgments failed!\n")),
                       -1);
    }

    // Clean-up!
    participant->delete_contained_entities();
    dpf->delete_participant(participant.in());

    TheServiceParticipant->shutdown();

  } catch (const CORBA::Exception& e) {
    e._tao_print_exception("Exception caught in main():");
    return -1;
  }

  return 0;
}
int
ParticipantTask::svc()
{
  try
  {
    ACE_DEBUG((LM_INFO, ACE_TEXT("(%P|%t)    -> PARTICIPANT STARTED\n")));

    DDS::DomainParticipantFactory_var dpf = TheParticipantFactory;
    DDS::DomainParticipant_var participant;
    DDS::Publisher_var publisher;
    DDS::DataWriter_var writer;
    FooDataWriter_var writer_i;
    DDS::StatusCondition_var cond;
    DDS::WaitSet_var ws = new DDS::WaitSet;

    { // Scope for guard to serialize creating Entities.
      GuardType guard(lock_);

      // Create Participant
      participant =
        dpf->create_participant(42,
                                PARTICIPANT_QOS_DEFAULT,
                                DDS::DomainParticipantListener::_nil(),
                                ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

#ifdef OPENDDS_SAFETY_PROFILE
      // RTPS cannot be shared
      char config_name[64], inst_name[64];
      ACE_OS::snprintf(config_name, 64, "cfg_%d", thread_index_);
      ACE_OS::snprintf(inst_name, 64, "rtps_%d", thread_index_);
      ++thread_index_;

      ACE_DEBUG((LM_INFO,
        "(%P|%t)    -> PARTICIPANT creating transport config %C\n",
        config_name));
      OpenDDS::DCPS::TransportConfig_rch config =
        TheTransportRegistry->create_config(config_name);
      OpenDDS::DCPS::TransportInst_rch inst =
        TheTransportRegistry->create_inst(inst_name, "rtps_udp");
      config->instances_.push_back(inst);
      TheTransportRegistry->bind_config(config_name, participant);
#endif

    } // End of lock scope.

    if (CORBA::is_nil(participant.in()))
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l: svc()")
                        ACE_TEXT(" create_participant failed!\n")), 1);

    {
      // Create Publisher
      publisher =
        participant->create_publisher(PUBLISHER_QOS_DEFAULT,
                                      DDS::PublisherListener::_nil(),
                                      ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

      if (CORBA::is_nil(publisher.in()))
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("%N:%l: svc()")
                          ACE_TEXT(" create_publisher failed!\n")), 1);


      // Register Type (FooType)
      FooTypeSupport_var ts = new FooTypeSupportImpl;
      if (ts->register_type(participant.in(), "") != DDS::RETCODE_OK)
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("%N:%l: svc()")
                          ACE_TEXT(" register_type failed!\n")), 1);

      // Create Topic (FooTopic)
      DDS::Topic_var topic =
        participant->create_topic("FooTopic",
                                  ts->get_type_name(),
                                  TOPIC_QOS_DEFAULT,
                                  DDS::TopicListener::_nil(),
                                  ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

      if (CORBA::is_nil(topic.in()))
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("%N:%l: svc()")
                          ACE_TEXT(" create_topic failed!\n")), 1);

      // Create DataWriter
      DDS::DataWriterQos writer_qos;
      publisher->get_default_datawriter_qos(writer_qos);
#ifndef OPENDDS_NO_OWNERSHIP_PROFILE
      writer_qos.history.depth = samples_per_thread_;
#endif

      writer =
        publisher->create_datawriter(topic.in(),
                                     writer_qos,
                                     DDS::DataWriterListener::_nil(),
                                     ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

      if (CORBA::is_nil(writer.in()))
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("%N:%l: svc()")
                          ACE_TEXT(" create_datawriter failed!\n")), 1);

      writer_i = FooDataWriter::_narrow(writer);
      if (CORBA::is_nil(writer_i))
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("%N:%l: svc()")
                          ACE_TEXT(" _narrow failed!\n")), 1);

      // Block until Subscriber is available
      cond = writer->get_statuscondition();
      cond->set_enabled_statuses(DDS::PUBLICATION_MATCHED_STATUS);

      ws->attach_condition(cond);

      DDS::Duration_t timeout =
        { DDS::DURATION_INFINITE_SEC, DDS::DURATION_INFINITE_NSEC };

      DDS::ConditionSeq conditions;
      DDS::PublicationMatchedStatus matches = {0, 0, 0, 0, 0};
      do
      {
        if (ws->wait(conditions, timeout) != DDS::RETCODE_OK)
          ACE_ERROR_RETURN((LM_ERROR,
                            ACE_TEXT("%N:%l: svc()")
                            ACE_TEXT(" wait failed!\n")), 1);

        if (writer->get_publication_matched_status(matches) != ::DDS::RETCODE_OK)
        {
          ACE_ERROR ((LM_ERROR,
            "(%P|%t) ERROR: failed to get publication matched status\n"));
          ACE_OS::exit (1);
        }
      }
      while (matches.current_count < 1);

      ws->detach_condition(cond);

      // The following is intentionally inefficient to stress various
      // pathways related to publication; we should be especially dull
      // and write only one sample at a time per writer.

      ProgressIndicator progress("(%P|%t)       PARTICIPANT %d%% (%d samples sent)\n",
                                 samples_per_thread_);

      for (std::size_t i = 0; i < samples_per_thread_; ++i)
      {
        Foo foo;
        foo.key = 3;
        DDS::InstanceHandle_t handle = writer_i->register_instance(foo);

        if (writer_i->write(foo, handle) != DDS::RETCODE_OK) {
          ACE_ERROR_RETURN((LM_ERROR,
                            ACE_TEXT("%N:%l: svc()")
                            ACE_TEXT(" write failed!\n")), 1);
        }
        ++progress;
      }

      DDS::Duration_t interval = { 30, 0};
      if( DDS::RETCODE_OK != writer->wait_for_acknowledgments( interval)) {
        ACE_ERROR_RETURN((LM_ERROR,
          ACE_TEXT("(%P:%t) ERROR: svc() - ")
          ACE_TEXT("timed out waiting for acks!\n")
        ), 1);
      }
    }

    // Clean-up!
    ACE_DEBUG((LM_INFO, ACE_TEXT("(%P|%t)       <- PUBLISHER PARTICIPANT DEL CONT ENTITIES\n")));
    participant->delete_contained_entities();
    ACE_DEBUG((LM_INFO, ACE_TEXT("(%P|%t)       <- PUBLISHER DELETE PARTICIPANT\n")));
    dpf->delete_participant(participant.in());
    ACE_DEBUG((LM_INFO, ACE_TEXT("(%P|%t)       <- PUBLISHER PARTICIPANT VARS GOING OUT OF SCOPE\n")));
  }
  catch (const CORBA::Exception& e)
  {
    e._tao_print_exception("caught in svc()");
    return 1;
  }

  ACE_DEBUG((LM_INFO, ACE_TEXT("(%P|%t)    <- PARTICIPANT FINISHED\n")));

  return 0;
}
Beispiel #8
0
int
Writer::svc()
{
  DDS::InstanceHandleSeq handles;

  try {
    // Block until Subscriber is available
    DDS::StatusCondition_var condition = writer_->get_statuscondition();
    condition->set_enabled_statuses(DDS::PUBLICATION_MATCHED_STATUS);

    DDS::WaitSet_var ws = new DDS::WaitSet;
    ws->attach_condition(condition);

    DDS::Duration_t timeout =
      { DDS::DURATION_INFINITE_SEC, DDS::DURATION_INFINITE_NSEC };

    DDS::ConditionSeq conditions;
    DDS::PublicationMatchedStatus matches = {0, 0, 0, 0, 0};

    do {
      if (ws->wait(conditions, timeout) != DDS::RETCODE_OK) {
        ACE_ERROR((LM_ERROR,
                   ACE_TEXT("%N:%l: svc()")
                   ACE_TEXT(" ERROR: wait failed!\n")));
        ACE_OS::exit(-1);
      }

      if (writer_->get_publication_matched_status(matches) != ::DDS::RETCODE_OK) {
        ACE_ERROR((LM_ERROR,
                   ACE_TEXT("%N:%l: svc()")
                   ACE_TEXT(" ERROR: get_publication_matched_status failed!\n")));
        ACE_OS::exit(-1);
      }

    } while (matches.current_count < 1);

    ws->detach_condition(condition);

    // Write samples
    Messenger::MessageDataWriter_var message_dw
      = Messenger::MessageDataWriter::_narrow(writer_.in());

    if (CORBA::is_nil(message_dw.in())) {
        ACE_ERROR((LM_ERROR,
                   ACE_TEXT("%N:%l: svc()")
                   ACE_TEXT(" ERROR: _narrow failed!\n")));
        ACE_OS::exit(-1);
    }

    Messenger::Message message;
    message.subject_id = 99;

    DDS::InstanceHandle_t handle = message_dw->register_instance(message);

    message.from         = "Comic Book Guy";
    message.subject      = "Review";
    message.text         = "Worst. Movie. Ever.";
    message.count        = 0;

    for (int i = 0; i < num_messages; i++) {
      DDS::ReturnCode_t error;
      do {
        error = message_dw->write(message, handle);
      } while (error == DDS::RETCODE_TIMEOUT);

      if (error != DDS::RETCODE_OK) {
        ACE_ERROR((LM_ERROR,
                   ACE_TEXT("%N:%l: svc()")
                   ACE_TEXT(" ERROR: write returned %d!\n"), error));
      }

      message.count++;
    }

  } catch (const CORBA::Exception& e) {
    e._tao_print_exception("Exception caught in svc():");
  }

  finished_instances_ ++;

  return 0;
}
Beispiel #9
0
int
TestCase::test()
{
  wait_for_subscribers(); // wait for association

  // As there are no fully association establishment between pub and sub for UDP
  // transport, a delay is required for the test to receive all messages.
  ACE_OS::sleep (3);

  // Write test data to exercise the data paths:
  for (int i = 0; i < num_messages; ++i) {
    int pind = 0;
    for (TestPublisherVector::iterator pub = publishers_.begin();
         pub != publishers_.end(); ++pub) {
      TestMessage message = { (100*pind) + i, "Testing!" };
      if ((*pub)->write_message(message)) {
        return -1;
      }
      ++pind;
    }
  }

  // wait for delivery
  for (TestSubscriberVector::iterator sub = subscribers_.begin();
       sub != subscribers_.end(); ++sub) {
    int read = 0;
    DDS::WaitSet_var ws = new DDS::WaitSet;
    DDS::ReadCondition_var rc =
        (*sub)->create_readcondition(DDS::NOT_READ_SAMPLE_STATE,
                                     DDS::NEW_VIEW_STATE,
                                     DDS::ALIVE_INSTANCE_STATE);
    ws->attach_condition(rc);
    DDS::Duration_t finite = {30, 0};
    CORBA::Long num_expected = num_messages * publishers_.size();

    do {
      TestMessageSeq data_values;
      DDS::SampleInfoSeq sample_infos;
      (*sub)->read_w_condition(data_values, sample_infos, num_expected, rc);
      read += data_values.length();
      if (read != num_expected) {
        DDS::ConditionSeq active;
        DDS::ReturnCode_t ret = ws->wait(active, finite);
        if (ret != DDS::RETCODE_OK) {
          ACE_ERROR_RETURN((LM_ERROR,
                      ACE_TEXT("%N:%l: wait()")
                      ACE_TEXT(" ERROR: wait for samples failed: %d\n"),
                      ret), -1);
        }
      }
    } while (read != num_expected);

    ws->detach_condition(rc);
  }

  // This test verifies associations formed between subscribers and
  // publishers attached to the same TransportImpl. There is nothing
  // which needs to be verified other than the association is formed
  // without crashing the DCPS subsystem.
  for (int i = 0; i < num_messages; ++i) {
    TestMessageSeq message_seq;
    DDS::SampleInfoSeq si_seq;
    ::CORBA::Long max_take = 1;

    // For each subscriber
    for (TestSubscriberVector::iterator sub = subscribers_.begin();
         sub != subscribers_.end(); ++sub) {
      DDS::ReadCondition_var tc = (*sub)->create_readcondition(DDS::READ_SAMPLE_STATE,
                                                               DDS::ANY_VIEW_STATE,
                                                               DDS::ALIVE_INSTANCE_STATE);
      // For each publisher
      size_t num_pubs = publishers_.size();
      for (unsigned int i = 0; i < num_pubs; ++i) {
        DDS::ReturnCode_t status = (*sub)->take_w_condition(message_seq, si_seq, max_take, tc);
        if (status == DDS::RETCODE_OK) {
          DDS::SampleInfo si = si_seq[0];
          TestMessage message = message_seq[0];
          std::cout << "SampleInfo.sample_rank = " << si.sample_rank << std::endl;
          std::cout << "SampleInfo.instance_state = " << si.instance_state << std::endl;

          if (si.valid_data) {
            std::cout << "Message: key    = " << message.key << std::endl
                      << "         message = " << message.message.in()   << std::endl;
          } else if (si.instance_state == DDS::NOT_ALIVE_DISPOSED_INSTANCE_STATE) {
            ACE_DEBUG((LM_DEBUG, ACE_TEXT("%N:%l: INFO: instance is disposed\n")));
            return -1;
          } else if (si.instance_state == DDS::NOT_ALIVE_NO_WRITERS_INSTANCE_STATE) {
            ACE_DEBUG((LM_DEBUG, ACE_TEXT("%N:%l: INFO: instance is unregistered\n")));
            return -1;
          } else {
            ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l: take_next_sample()")
                        ACE_TEXT(" ERROR: unknown instance state: %d\n"),
                        si.instance_state), -1);
          }
        } else {
          ACE_ERROR_RETURN((LM_ERROR,
                      ACE_TEXT("%N:%l: take_next_sample()")
                      ACE_TEXT(" ERROR: unexpected status: %d\n"),
                      status), -1);
        }
      }
    }
  }
  return 0;
}
int OSPL_MAIN (int argc, char *argv[])
{
  MsgSeq msgList;
  SampleInfoSeq infoSeq;
  Duration_t timeout = { 0, 200000000 };
  int count = 0;

  DDSEntityManager mgr;

   // create domain participant
  char partition_name[] = "Listener example";
  mgr.createParticipant(partition_name);

  //create type
  MsgTypeSupport_var st = new MsgTypeSupport();
  mgr.registerType(st.in());

  //create Topic
  char topic_name[] = "ListenerData_Msg";
  mgr.createTopic(topic_name);

  //create Subscriber
  mgr.createSubscriber();

  // create DataReader
  mgr.createReader();

  DataReader_var dreader = mgr.getReader();
  ListenerDataListener *myListener = new ListenerDataListener();
  myListener->m_MsgReader = MsgDataReader::_narrow(dreader.in());
  checkHandle(myListener->m_MsgReader.in(), "MsgDataReader::_narrow");

  cout << "=== [ListenerDataSubscriber] set_listener" << endl;
  DDS::StatusMask mask =
           DDS::DATA_AVAILABLE_STATUS | DDS::REQUESTED_DEADLINE_MISSED_STATUS;
  myListener->m_MsgReader->set_listener(myListener, mask);
  cout << "=== [ListenerDataSubscriber] Ready ..." << endl;
  myListener->m_closed = false;

  // waitset used to avoid spinning in the loop below
  DDS::WaitSet_var ws = new DDS::WaitSet();
  ws->attach_condition(myListener->m_guardCond);
  DDS::ConditionSeq condSeq;
  while (!myListener->m_closed && count < 1500 ){
    // To avoid spinning here. We can either use a sleep or better a WaitSet.
    ws->wait(condSeq, timeout);
    myListener->m_guardCond->set_trigger_value(false);
    ++count;
 }

  cout << "===[ListenerDataSubscriber] Market Closed" << endl;

  //cleanup
  mgr.deleteReader(myListener->m_MsgReader.in ());
  mgr.deleteSubscriber();
  mgr.deleteTopic();
  mgr.deleteParticipant();
  delete myListener;
  cout << "Completed Listener example." << endl;
  return 0;
}
Beispiel #11
0
int
ACE_TMAIN(int argc, ACE_TCHAR** argv)
{
  try
  {
    TheParticipantFactoryWithArgs(argc, argv);

    // Create Participant
    DDS::DomainParticipant_var participant =
      TheParticipantFactory->create_participant(42,
                                                PARTICIPANT_QOS_DEFAULT,
                                                DDS::DomainParticipantListener::_nil(),
                                                OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (CORBA::is_nil(participant.in()))
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l: main()")
                        ACE_TEXT(" ERROR: create_participant failed!\n")), 1);

    // Create Subscriber
    DDS::Subscriber_var subscriber =
      participant->create_subscriber(SUBSCRIBER_QOS_DEFAULT,
                                     DDS::SubscriberListener::_nil(),
                                     OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (CORBA::is_nil(subscriber.in()))
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l: main()")
                        ACE_TEXT(" ERROR: create_subscriber failed!\n")), 2);

    // Create Publisher
    DDS::Publisher_var publisher =
      participant->create_publisher(PUBLISHER_QOS_DEFAULT,
                                    DDS::PublisherListener::_nil(),
                                    OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (CORBA::is_nil(publisher.in()))
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l: main()")
                        ACE_TEXT(" ERROR: create_publisher failed!\n")), 1);

    OpenDDS::DCPS::TransportIdType transportId(0);

    // Attach Subscriber Transport
    ++transportId;

    OpenDDS::DCPS::TransportConfiguration_rch sub_config =
      TheTransportFactory->get_or_create_configuration(transportId, ACE_TEXT("SimpleTcp"));

    OpenDDS::DCPS::TransportImpl_rch sub_transport =
      TheTransportFactory->create_transport_impl(transportId);

    OpenDDS::DCPS::SubscriberImpl* subscriber_i =
      dynamic_cast<OpenDDS::DCPS::SubscriberImpl*>(subscriber.in());

    if (subscriber_i == 0)
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l: main()")
                        ACE_TEXT(" ERROR: dynamic_cast failed!\n")), 1);

    OpenDDS::DCPS::AttachStatus sub_status =
      subscriber_i->attach_transport(sub_transport.in());

    if (sub_status != OpenDDS::DCPS::ATTACH_OK)
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l: main()")
                        ACE_TEXT(" ERROR: attach_transport failed!\n")), 1);

    // Attach Publisher Transport
    ++transportId;

    OpenDDS::DCPS::TransportConfiguration_rch pub_config =
      TheTransportFactory->get_or_create_configuration(transportId, ACE_TEXT("SimpleTcp"));

    OpenDDS::DCPS::TransportImpl_rch pub_transport =
      TheTransportFactory->create_transport_impl(transportId);

    OpenDDS::DCPS::PublisherImpl* publisher_i =
      dynamic_cast<OpenDDS::DCPS::PublisherImpl*>(publisher.in());

    if (publisher_i == 0)
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l: main()")
                        ACE_TEXT(" ERROR: dynamic_cast failed!\n")), 1);

    OpenDDS::DCPS::AttachStatus pub_status =
      publisher_i->attach_transport(pub_transport.in());

    if (pub_status != OpenDDS::DCPS::ATTACH_OK)
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l: main()")
                        ACE_TEXT(" ERROR: attach_transport failed!\n")), 1);

    // Register Type (FooType)
    FooTypeSupport_var ts = new FooTypeSupportImpl;
    if (ts->register_type(participant.in(), "") != DDS::RETCODE_OK)
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l: main()")
                        ACE_TEXT(" ERROR: register_type failed!\n")), 1);

    // Create Topic (FooTopic)
    DDS::Topic_var topic =
      participant->create_topic("FooTopic",
                                ts->get_type_name(),
                                TOPIC_QOS_DEFAULT,
                                DDS::TopicListener::_nil(),
                                OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (CORBA::is_nil(topic.in()))
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l: main()")
                        ACE_TEXT(" ERROR: create_topic failed!\n")), 1);

    // Create DataReader
    DDS::DataReaderQos qos;

    if (subscriber->get_default_datareader_qos(qos) != DDS::RETCODE_OK)
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l main()")
                        ACE_TEXT(" ERROR: create_datareader failed!\n")), -1);

    qos.history.kind = DDS::KEEP_ALL_HISTORY_QOS;

    DDS::DataReader_var reader =
      subscriber->create_datareader(topic.in(),
                                    qos,
                                    DDS::DataReaderListener::_nil(),
                                    OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (CORBA::is_nil(reader.in()))
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l: main()")
                        ACE_TEXT(" ERROR: create_datareader failed!\n")), 7);

    FooDataReader_var reader_i = FooDataReader::_narrow(reader);
    if (CORBA::is_nil(reader_i))
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l: main()")
                        ACE_TEXT(" ERROR: _narrow failed!\n")), 1);

    // Create DataWriter
    DDS::DataWriter_var writer =
      publisher->create_datawriter(topic.in(),
                                   DATAWRITER_QOS_DEFAULT,
                                   DDS::DataWriterListener::_nil(),
                                   OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (CORBA::is_nil(writer.in()))
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l: main()")
                        ACE_TEXT(" ERROR: create_datawriter failed!\n")), 1);

    FooDataWriter_var writer_i = FooDataWriter::_narrow(writer);
    if (CORBA::is_nil(writer_i))
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l: main()")
                        ACE_TEXT(" ERROR: _narrow failed!\n")), 1);

    // Block until Subscriber is associated
    DDS::StatusCondition_var cond = writer->get_statuscondition();
    cond->set_enabled_statuses(DDS::PUBLICATION_MATCHED_STATUS);

    DDS::WaitSet_var ws = new DDS::WaitSet;
    ws->attach_condition(cond);

    DDS::Duration_t timeout =
      { DDS::DURATION_INFINITE_SEC, DDS::DURATION_INFINITE_NSEC };

    DDS::ConditionSeq conditions;
    DDS::PublicationMatchedStatus matches = { 0, 0, 0, 0, 0 };
    do
    {
      if (ws->wait(conditions, timeout) != DDS::RETCODE_OK)
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("%N:%l: main()")
                          ACE_TEXT(" ERROR: wait failed!\n")), 1);

      if (writer->get_publication_matched_status(matches) != ::DDS::RETCODE_OK)
      {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("%N:%l: main()")
                          ACE_TEXT(" ERROR: failed to get publication matched status!\n")),
                          2);
      }
    }
    while (matches.current_count < 1);

    ws->detach_condition(cond);

    //
    // FooDataWriter::dispose should cause an instance to be
    // deleted after the last sample in the instance has been
    // taken from the ReceivedDataElementList:
    //
    DDS_TEST test(reader_i);
    if (!test) return 1;

    Foo foo;
    DDS::InstanceHandle_t handle;

    handle = writer_i->register_instance(foo);

    writer_i->write(foo, handle);
    writer_i->dispose(foo, handle);

    ACE_OS::sleep(5); // wait for samples to arrive

    if (!test.take_all_samples())
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("%N:%l: main()")
                          ACE_TEXT(" ERROR: unable to take samples!\n")), 2);
    /// Verify instance has been deleted
    if (test.has_instance(handle))
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("%N:%l: main()")
                          ACE_TEXT(" ERROR: instance not removed!\n")), 3);

    // Clean-up!
    participant->delete_contained_entities();
    TheParticipantFactory->delete_participant(participant);

    TheTransportFactory->release();
    TheServiceParticipant->shutdown();
  }
  catch (const CORBA::Exception& e)
  {
    e._tao_print_exception("caught in main()");
    return -1;
  }

  return 0;
}
Beispiel #12
0
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  int status = 0;
  try {
    // Initialize DomainParticipantFactory
    DDS::DomainParticipantFactory_var dpf =
      TheParticipantFactoryWithArgs(argc, argv);

    int error;
    if ((error = parse_args(argc, argv)) != 0) {
      return error;
    }

    // Create DomainParticipant
    DDS::DomainParticipant_var participant =
      dpf->create_participant(4,
                              PARTICIPANT_QOS_DEFAULT,
                              DDS::DomainParticipantListener::_nil(),
                              OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (CORBA::is_nil(participant.in())) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l main()")
                        ACE_TEXT(" ERROR: create_participant() failed!\n")), -1);
    }

    // Register Type (Messenger::Message)
    Messenger::MessageTypeSupport_var ts =
      new Messenger::MessageTypeSupportImpl();

    if (ts->register_type(participant.in(), "") != DDS::RETCODE_OK) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l main()")
                        ACE_TEXT(" ERROR: register_type() failed!\n")), -1);
    }

    // Create Topic (Movie Discussion List)
    CORBA::String_var type_name = ts->get_type_name();
    DDS::Topic_var topic =
      participant->create_topic("Movie Discussion List",
                                type_name.in(),
                                TOPIC_QOS_DEFAULT,
                                DDS::TopicListener::_nil(),
                                OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (CORBA::is_nil(topic.in())) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l main()")
                        ACE_TEXT(" ERROR: create_topic() failed!\n")), -1);
    }

    // Create Subscriber
    DDS::Subscriber_var sub =
      participant->create_subscriber(SUBSCRIBER_QOS_DEFAULT,
                                     DDS::SubscriberListener::_nil(),
                                     OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (CORBA::is_nil(sub.in())) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l main()")
                        ACE_TEXT(" ERROR: create_subscriber() failed!\n")), -1);
    }

    // Create DataReader
    DataReaderListenerImpl* const listener_servant = new DataReaderListenerImpl;
    DDS::DataReaderListener_var listener(listener_servant);

    DDS::DataReaderQos dr_qos;
    sub->get_default_datareader_qos(dr_qos);
    if (DataReaderListenerImpl::is_reliable()) {
      std::cout << "Reliable DataReader" << std::endl;
      dr_qos.reliability.kind = DDS::RELIABLE_RELIABILITY_QOS;
    }

    DDS::DataReader_var reader =
      sub->create_datareader(topic.in(),
                             dr_qos,
                             listener.in(),
                             OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (CORBA::is_nil(reader.in())) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l main()")
                        ACE_TEXT(" ERROR: create_datareader() failed!\n")), -1);
    }

    // Block until Publisher completes
    DDS::StatusCondition_var condition = reader->get_statuscondition();
    condition->set_enabled_statuses(DDS::SUBSCRIPTION_MATCHED_STATUS);

    DDS::WaitSet_var ws = new DDS::WaitSet;
    ws->attach_condition(condition);

    DDS::Duration_t timeout =
      { DDS::DURATION_INFINITE_SEC, DDS::DURATION_INFINITE_NSEC };

    DDS::ConditionSeq conditions;
    DDS::SubscriptionMatchedStatus matches = { 0, 0, 0, 0, 0 };

    while (true) {
      if (reader->get_subscription_matched_status(matches) != DDS::RETCODE_OK) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("%N:%l main()")
                          ACE_TEXT(" ERROR: get_subscription_matched_status() failed!\n")), -1);
      }
      if (matches.current_count == 0 && matches.total_count > 0) {
        break;
      }
      if (ws->wait(conditions, timeout) != DDS::RETCODE_OK) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("%N:%l main()")
                          ACE_TEXT(" ERROR: wait() failed!\n")), -1);
      }
    }

    status = listener_servant->is_valid() ? 0 : -1;

    ws->detach_condition(condition);

    // Clean-up!
    participant->delete_contained_entities();
    dpf->delete_participant(participant.in());
    TheServiceParticipant->shutdown();

  } catch (const CORBA::Exception& e) {
    e._tao_print_exception("Exception caught in main():");
    status = -1;
  }

  return status;
}
Beispiel #13
0
int
ACE_TMAIN(int argc, ACE_TCHAR** argv)
{
  parse_args(argc, argv);

  ACE_DEBUG((LM_INFO, ACE_TEXT("(%P|%t) -> SUBSCRIBER STARTED\n")));

  try
  {
    DDS::DomainParticipantFactory_var dpf =
      TheParticipantFactoryWithArgs(argc, argv);

    // Create Participant
    DDS::DomainParticipant_var participant =
      dpf->create_participant(42,
                              PARTICIPANT_QOS_DEFAULT,
                              DDS::DomainParticipantListener::_nil(),
                              ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (CORBA::is_nil(participant.in()))
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l: main()")
                        ACE_TEXT(" create_participant failed!\n")), 1);

    // Create Subscriber
    DDS::Subscriber_var subscriber =
      participant->create_subscriber(SUBSCRIBER_QOS_DEFAULT,
                                     DDS::SubscriberListener::_nil(),
                                     ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (CORBA::is_nil(subscriber.in()))
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l: main()")
                        ACE_TEXT(" create_subscriber failed!\n")), 2);

    // Attach Transport
    OpenDDS::DCPS::TransportImpl_rch transport =
      TheTransportFactory->create_transport_impl(
          OpenDDS::DCPS::DEFAULT_SIMPLE_TCP_ID,
          "SimpleTcp");

    OpenDDS::DCPS::SubscriberImpl* subscriber_i =
      dynamic_cast<OpenDDS::DCPS::SubscriberImpl*>(subscriber.in());

    if (subscriber_i == 0)
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l: main()")
                        ACE_TEXT(" dynamic_cast failed!\n")), 3);

    OpenDDS::DCPS::AttachStatus status =
      subscriber_i->attach_transport(transport.in());

    if (status != OpenDDS::DCPS::ATTACH_OK)
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l: main()")
                        ACE_TEXT(" attach_transport failed!\n")), 4);

    // Register Type (FooType)
    FooTypeSupport_var ts = new FooTypeSupportImpl;
    if (ts->register_type(participant.in(), "") != DDS::RETCODE_OK)
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l: main()")
                        ACE_TEXT(" register_type failed!\n")), 5);

    // Create Topic (FooTopic)
    DDS::Topic_var topic =
      participant->create_topic("FooTopic",
                                ts->get_type_name(),
                                TOPIC_QOS_DEFAULT,
                                DDS::TopicListener::_nil(),
                                ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (CORBA::is_nil(topic.in()))
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l: main()")
                        ACE_TEXT(" create_topic failed!\n")), 6);

    // Create DataReader
    ProgressIndicator progress =
      ProgressIndicator("(%P|%t)    SUBSCRIBER %d%% (%d samples received)\n",
                        expected_samples);

    DDS::DataReaderListener_var listener =
      new DataReaderListenerImpl(received_samples, progress);

    DDS::DataReaderQos reader_qos;
    subscriber->get_default_datareader_qos(reader_qos);

    reader_qos.history.kind = DDS::KEEP_ALL_HISTORY_QOS;

    DDS::DataReader_var reader =
      subscriber->create_datareader(topic.in(),
                                    reader_qos,
                                    listener.in(),
                                    ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (CORBA::is_nil(reader.in()))
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l: main()")
                        ACE_TEXT(" create_datareader failed!\n")), 7);

    // Block until Publisher completes
    DDS::StatusCondition_var cond = reader->get_statuscondition();
    cond->set_enabled_statuses(DDS::SUBSCRIPTION_MATCHED_STATUS);

    DDS::WaitSet_var ws = new DDS::WaitSet;
    ws->attach_condition(cond);

    DDS::Duration_t timeout =
      { DDS::DURATION_INFINITE_SEC, DDS::DURATION_INFINITE_NSEC };

    DDS::ConditionSeq conditions;
    DDS::SubscriptionMatchedStatus matches = {0, 0, 0, 0, 0};
    do
    {
      if (ws->wait(conditions, timeout) != DDS::RETCODE_OK)
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("%N:%l: main()")
                          ACE_TEXT(" wait failed!\n")), 8);

      if (reader->get_subscription_matched_status(matches) != ::DDS::RETCODE_OK)
      {
        ACE_ERROR ((LM_ERROR,
          "ERROR: failed to get subscription matched status\n"));
        return 1;
      }
    }
    while (matches.current_count > 0 || matches.total_count < n_publishers);
    ws->detach_condition(cond);

    // Clean-up!
    participant->delete_contained_entities();
    dpf->delete_participant(participant.in());

    TheTransportFactory->release();
    TheServiceParticipant->shutdown();
  }
  catch (const CORBA::Exception& e)
  {
    e._tao_print_exception("caught in main()");
    return 9;
  }

  ACE_DEBUG((LM_INFO, ACE_TEXT("(%P|%t) <- SUBSCRIBER FINISHED\n")));

  if (received_samples != expected_samples) {
    ACE_DEBUG((LM_DEBUG,
      ACE_TEXT("(%P|%t) ERROR: subscriber - ")
      ACE_TEXT("received %d of expected %d samples.\n"),
      received_samples,
      expected_samples
    ));
    return 10;
  }

  return 0;
}
void
DataReaderListenerImpl::on_data_available(DDS::DataReader_ptr reader)
{
  TestMsgDataReader_var reader_i =
    TestMsgDataReader::_narrow(reader);

  if (!reader_i) {
    ACE_ERROR((LM_ERROR,
               ACE_TEXT("ERROR: %N:%l: on_data_available() -")
               ACE_TEXT(" _narrow failed!\n")));
    ACE_OS::exit(-1);
  }

  TestMsg message;
  DDS::SampleInfo info;

  DDS::ReturnCode_t error = reader_i->take_next_sample(message, info);

  if (error == DDS::RETCODE_OK) {
    if (info.valid_data) {
      ACE_DEBUG((LM_DEBUG, "(%P|%t) DataReader %C has received message: %d from: %C\n", id_.c_str(), message.value, std::string(message.from).c_str()));

      if (!origin_) {
        TestMsgDataWriter_var message_writer =
          TestMsgDataWriter::_narrow(writer_);

        if (!message_writer) {
          ACE_ERROR((LM_ERROR,
                     ACE_TEXT("ERROR: %N:%l: on_data_available() -")
                     ACE_TEXT(" _narrow failed!\n")));
          ACE_OS::exit(-1);
        }

        // Block until Subscriber is available
        DDS::StatusCondition_var condition = writer_->get_statuscondition();
        condition->set_enabled_statuses(DDS::PUBLICATION_MATCHED_STATUS);

        DDS::WaitSet_var ws = new DDS::WaitSet;
        ws->attach_condition(condition);

        while (true) {
          DDS::PublicationMatchedStatus matches;
          if (writer_->get_publication_matched_status(matches) != ::DDS::RETCODE_OK) {
            ACE_ERROR((LM_ERROR,
                              ACE_TEXT("ERROR: %N:%l: on_data_available() -")
                              ACE_TEXT(" get_publication_matched_status failed!\n")));
            ACE_OS::exit(-1);
          }

          ACE_DEBUG((LM_DEBUG, "(%P|%t) DataWriter %C has %d of %d readers\n", writer_id_.c_str(), matches.current_count, total_readers_));
          if (matches.current_count >= total_readers_) {
            break;
          }

          DDS::ConditionSeq conditions;
          DDS::Duration_t timeout = { 60, 0 };
          if (ws->wait(conditions, timeout) != DDS::RETCODE_OK) {
            ACE_ERROR((LM_ERROR,
                       ACE_TEXT("ERROR: %N:%l: on_data_available() -")
                       ACE_TEXT(" wait failed!\n")));
            ACE_OS::exit(-1);
          }
        }

        ws->detach_condition(condition);
        std::string from_list = std::string(message.from) + "->" + writer_id_;
        message.from = from_list.c_str();
        DDS::ReturnCode_t error;
        do {
          error = message_writer->write(message, DDS::HANDLE_NIL);

          if ((error != DDS::RETCODE_OK) && (error != DDS::RETCODE_TIMEOUT)) {
            ACE_ERROR((LM_ERROR,
                       ACE_TEXT("ERROR: %N:%l: on_data_available() -")
                       ACE_TEXT(" write returned %d!\n"), error));
          }
        } while (error == DDS::RETCODE_TIMEOUT);
      }
      if (++received_samples_ == expected_samples_) {
        ACE_DEBUG((LM_DEBUG, "(%P|%t) DataReader %C has received expected number of samples\n", id_.c_str()));
        if (!origin_) {
          ACE_DEBUG((LM_DEBUG, "(%P|%t) DataWriter %C is waiting for acknowledgments\n", writer_id_.c_str()));
          DDS::Duration_t timeout = { 30, 0 };
          writer_->wait_for_acknowledgments(timeout);
        }
        done_callback_();
      }
    }

  } else {
    ACE_ERROR((LM_ERROR,
               ACE_TEXT("ERROR: %N:%l: on_data_available() -")
               ACE_TEXT(" take_next_sample failed!\n")));
  }
}
Beispiel #15
0
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  try {
    // Initialize DomainParticipantFactory
    DDS::DomainParticipantFactory_var dpf =
      TheParticipantFactoryWithArgs(argc, argv);
    DDS::DomainParticipant_var participant;

    bool result1, result2;

    int error;
    if ((error = parse_args(argc, argv)) != 0) {
      ACE_DEBUG((LM_ERROR, "(%P|%t) Parsing error, returning %d\n", error));
      return error;
    }

    {  // Scope of entities
      // Create DomainParticipant
      participant =
        dpf->create_participant(411,
                                PARTICIPANT_QOS_DEFAULT,
                                DDS::DomainParticipantListener::_nil(),
                                OpenDDS::DCPS::DEFAULT_STATUS_MASK);

      if (CORBA::is_nil(participant.in())) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("%N:%l main()")
                          ACE_TEXT(" ERROR: create_participant() failed!\n")), -1);
      }

      // Register Type (Messenger::Message)
      Messenger::MessageTypeSupport_var ts =
        new Messenger::MessageTypeSupportImpl();

      if (ts->register_type(participant.in(), "") != DDS::RETCODE_OK) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("%N:%l main()")
                          ACE_TEXT(" ERROR: register_type() failed!\n")), -1);
      }

      // Create Topic (Movie Discussion List)
      DDS::Topic_var topic =
        participant->create_topic("Movie Discussion List",
                                  ts->get_type_name(),
                                  TOPIC_QOS_DEFAULT,
                                  DDS::TopicListener::_nil(),
                                  OpenDDS::DCPS::DEFAULT_STATUS_MASK);

      if (CORBA::is_nil(topic.in())) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("%N:%l main()")
                          ACE_TEXT(" ERROR: create_topic() failed!\n")), -1);
      }

      // Create Subscriber
      DDS::Subscriber_var sub =
        participant->create_subscriber(SUBSCRIBER_QOS_DEFAULT,
                                       DDS::SubscriberListener::_nil(),
                                       OpenDDS::DCPS::DEFAULT_STATUS_MASK);

      if (CORBA::is_nil(sub.in())) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("%N:%l main()")
                          ACE_TEXT(" ERROR: create_subscriber() failed!\n")), -1);
      }

      // Create DataReader
      DataReaderListenerImpl* listener_svt1 = new DataReaderListenerImpl("DataReader1");
      DataReaderListenerImpl* listener_svt2 = new DataReaderListenerImpl("DataReader2");

      DDS::DataReaderListener_var listener1(listener_svt1);
      DDS::DataReaderListener_var listener2(listener_svt2);

      ::DDS::DataReaderQos dr_qos;
      sub->get_default_datareader_qos (dr_qos);
      dr_qos.ownership.kind = ::DDS::EXCLUSIVE_OWNERSHIP_QOS;
      dr_qos.deadline.period.sec = deadline.sec;
      dr_qos.deadline.period.nanosec = deadline.nanosec;
      dr_qos.liveliness.lease_duration.sec = liveliness.sec;
      dr_qos.liveliness.lease_duration.nanosec = liveliness.nanosec;

      DDS::DataReader_var reader1 =
        sub->create_datareader(topic.in(),
                               dr_qos,
                               listener1.in(),
                               OpenDDS::DCPS::DEFAULT_STATUS_MASK);

      if (CORBA::is_nil(reader1.in())) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("%N:%l main()")
                          ACE_TEXT(" ERROR: create_datareader() failed!\n")), -1);
      }

      DDS::DataReader_var reader2 =
        sub->create_datareader(topic.in(),
                               dr_qos,
                               listener2.in(),
                               OpenDDS::DCPS::DEFAULT_STATUS_MASK);

      if (CORBA::is_nil(reader2.in())) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("%N:%l main()")
                          ACE_TEXT(" ERROR: create_datareader() failed!\n")), -1);
      }

      // Block until Publisher completes
      DDS::StatusCondition_var condition1 = reader1->get_statuscondition();
      DDS::StatusCondition_var condition2 = reader2->get_statuscondition();
      condition1->set_enabled_statuses(DDS::SUBSCRIPTION_MATCHED_STATUS);
      condition2->set_enabled_statuses(DDS::SUBSCRIPTION_MATCHED_STATUS);

      DDS::WaitSet_var ws = new DDS::WaitSet;
      ws->attach_condition(condition1);
      ws->attach_condition(condition2);

      DDS::Duration_t timeout =
        { DDS::DURATION_INFINITE_SEC, DDS::DURATION_INFINITE_NSEC };

      DDS::ConditionSeq conditions;
      DDS::SubscriptionMatchedStatus matches1 = { 0, 0, 0, 0, 0 };
      DDS::SubscriptionMatchedStatus matches2 = { 0, 0, 0, 0, 0 };
      while (true) {
        if (reader1->get_subscription_matched_status(matches1) != DDS::RETCODE_OK) {
          ACE_ERROR_RETURN((LM_ERROR,
                            ACE_TEXT("%N:%l main()")
                            ACE_TEXT(" ERROR: get_subscription_matched_status() failed!\n")), -1);
        }

        if (reader2->get_subscription_matched_status(matches2) != DDS::RETCODE_OK) {
          ACE_ERROR_RETURN((LM_ERROR,
                            ACE_TEXT("%N:%l main()")
                            ACE_TEXT(" ERROR: get_subscription_matched_status() failed!\n")), -1);
        }

        if ((matches1.current_count == 0 && matches1.total_count > 0) ||
            (matches2.current_count == 0 && matches2.total_count > 0)) {
          break;
        }
        DDS::ReturnCode_t wait_status = ws->wait(conditions, timeout);
        if (wait_status != DDS::RETCODE_OK) {
          std::cerr << "ERROR: Subscriber failed during waiting on wait set with return code "
                    << wait_status << std::endl;
        }
      }

      ws->detach_condition(condition1);
      ws->detach_condition(condition2);

      result1 = listener_svt1->verify_result();
      result2 = listener_svt2->verify_result();
    }  // Scope of entities

    // Clean-up!
    participant->delete_contained_entities();
    dpf->delete_participant(participant.in());

    TheServiceParticipant->shutdown();


    if (result1 == false || result2 == false) {
      ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("%N:%l main()")
                          ACE_TEXT(" ERROR: failed to verify message!\n")), -2);
    }

  } catch (const CORBA::Exception& e) {
    e._tao_print_exception("Exception caught in main():");
    return -1;
  }

  return 0;
}
Beispiel #16
0
int
Writer::svc()
{
  DDS::InstanceHandleSeq handles;

  try {
    // Block until Subscriber is available
    DDS::StatusCondition_var condition = writer_->get_statuscondition();
    condition->set_enabled_statuses(DDS::PUBLICATION_MATCHED_STATUS);

    DDS::WaitSet_var ws = new DDS::WaitSet;
    ws->attach_condition(condition);

    DDS::Duration_t timeout =
      { DDS::DURATION_INFINITE_SEC, DDS::DURATION_INFINITE_NSEC };

    DDS::ConditionSeq conditions;
    DDS::PublicationMatchedStatus matches = {0, 0, 0, 0, 0};

    do {
      if (ws->wait(conditions, timeout) != DDS::RETCODE_OK) {
        ACE_ERROR((LM_ERROR,
                   ACE_TEXT("%N:%l: svc()")
                   ACE_TEXT(" ERROR: wait failed!\n")));
        ACE_OS::exit(-1);
      }

      if (writer_->get_publication_matched_status(matches) != ::DDS::RETCODE_OK) {
        ACE_ERROR((LM_ERROR,
                   ACE_TEXT("%N:%l: svc()")
                   ACE_TEXT(" ERROR: get_publication_matched_status failed!\n")));
        ACE_OS::exit(-1);
      }

    } while (matches.current_count < 2);

    ws->detach_condition(condition);

    // Write samples
    Messenger::MessageDataWriter_var message_dw
      = Messenger::MessageDataWriter::_narrow(writer_.in());

    if (CORBA::is_nil(message_dw.in())) {
        ACE_ERROR((LM_ERROR,
                   ACE_TEXT("%N:%l: svc()")
                   ACE_TEXT(" ERROR: _narrow failed!\n")));
        ACE_OS::exit(-1);
    }

    Messenger::Message message;

    message.from       = CORBA::string_dup(ownership_dw_id_.c_str());
    message.subject    = CORBA::string_dup("Review");
    message.text       = CORBA::string_dup("Worst. Movie. Ever.");
    message.count      = 1;
    message.strength   = ownership_strength;

    for (int i = 0; i < num_messages; i++) {
      message.subject_id = message.count % 2;  // 0 or 1
      ACE_DEBUG ((LM_DEBUG, "(%P|%t) %s writes instance %d count %d str %d\n",
      ownership_dw_id_.c_str(), message.subject_id, message.count, message.strength));
      DDS::ReturnCode_t error = message_dw->write(message, ::DDS::HANDLE_NIL);

      if (error != DDS::RETCODE_OK) {
        ACE_ERROR((LM_ERROR,
                   ACE_TEXT("%N:%l: svc()")
                   ACE_TEXT(" ERROR: write returned %d!\n"), error));

        if (error == DDS::RETCODE_TIMEOUT) {
          timeout_writes_++;
        }
      }

      if (message.count == 5) {
        ::DDS::DataWriterQos qos;
        error = this->writer_->get_qos (qos);
        if (error != ::DDS::RETCODE_OK) {
          ACE_ERROR((LM_ERROR,
                   ACE_TEXT("%N:%l: svc()")
                   ACE_TEXT(" ERROR: get_qos returned %d!\n"), error));
        }
        CORBA::Long old = qos.ownership_strength.value;
        if (reset_ownership_strength != -1 && old != reset_ownership_strength) {
          qos.ownership_strength.value = reset_ownership_strength;
          // Add a delay so the builtin topic data update arrives after samples
          // with previous strength is received by datareader. This helps simplify
          // result verification on subscriber side.
          ACE_OS::sleep (1);
          ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) %s : reset ownership strength from %d to %d\n"),
            ownership_dw_id_.c_str(), old, reset_ownership_strength));
          error = this->writer_->set_qos (qos);
          if (error != ::DDS::RETCODE_OK) {
            ACE_ERROR((LM_ERROR,
                   ACE_TEXT("%N:%l: svc()")
                   ACE_TEXT(" ERROR: set_qos returned %d!\n"), error));
          }
          else {
            message.strength   =  reset_ownership_strength;
            ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) ownership strength in message is now %d\n"),
              message.strength));
            error = this->writer_->get_qos(qos);
            if (error != ::DDS::RETCODE_OK) {
              ACE_ERROR((LM_ERROR,
                       ACE_TEXT("%N:%l: svc()")
                       ACE_TEXT(" ERROR: get_qos returned %d!\n"), error));
            } else {
              ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) ownership strength in qos is now %d\n"),
                qos.ownership_strength.value));
            }
          }
        }

      }

      if ((message.count == 5)
           && reset_delay > ACE_Time_Value::zero) {
        ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) %s : reset delay from %d to %d at sample %d\n"),
          ownership_dw_id_.c_str(), dds_delay.msec(), reset_delay.msec(), message.count));
        ACE_OS::sleep (reset_delay);
      }
      else if (dds_delay > ACE_Time_Value::zero) {
        ACE_OS::sleep (dds_delay);
      }

      message.count++;
    }


  } catch (const CORBA::Exception& e) {
    e._tao_print_exception("Exception caught in svc():");
  }

  finished_instances_ ++;

  return 0;
}
Beispiel #17
0
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  try
    {
      DDS::DomainParticipantFactory_var dpf;
      DDS::DomainParticipant_var participant;

      dpf = TheParticipantFactoryWithArgs(argc, argv);
      participant =
        dpf->create_participant(11,
                                PARTICIPANT_QOS_DEFAULT,
                                DDS::DomainParticipantListener::_nil(),
                                ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
      if (CORBA::is_nil (participant.in ())) {
        cerr << "create_participant failed." << endl;
        return 1 ;
      }

      Messenger::MessageTypeSupportImpl* mts_servant =
        new Messenger::MessageTypeSupportImpl;

      if (DDS::RETCODE_OK != mts_servant->register_type(participant.in (),
                                                        ""))
      {
        cerr << "Failed to register the MessageTypeTypeSupport." << endl;
        exit(1);
      }

      CORBA::String_var type_name = mts_servant->get_type_name ();

      DDS::TopicQos topic_qos;
      participant->get_default_topic_qos(topic_qos);
      DDS::Topic_var topic =
        participant->create_topic("Movie Discussion List",
                                  type_name.in (),
                                  topic_qos,
                                  DDS::TopicListener::_nil(),
                                  ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
      if (CORBA::is_nil (topic.in ())) {
        cerr << "Failed to create_topic." << endl;
        exit(1);
      }

      // Create the subscriber and attach to the corresponding
      // transport.
      DDS::Subscriber_var sub =
        participant->create_subscriber (SUBSCRIBER_QOS_DEFAULT,
                                        DDS::SubscriberListener::_nil(),
                                        ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
      if (CORBA::is_nil (sub.in ())) {
        cerr << "Failed to create_subscriber." << endl;
        exit(1);
      }

     DDS::DataReaderQos dr_qos;
      sub->get_default_datareader_qos (dr_qos);

      // Make reliable
      dr_qos.reliability.kind = DDS::RELIABLE_RELIABILITY_QOS;

      // Set up a 5 second recurring deadline.
      dr_qos.deadline.period.sec     = 5;
      dr_qos.deadline.period.nanosec = 0;

      // Create two listeners. One for each DataReader.
      DDS::DataReaderListener_var listener1 (new DataReaderListenerImpl);
      if (CORBA::is_nil (listener1.in ()))
      {
        cerr << "ERROR: listener1 is nil." << endl;
        exit(1);
      }

      DDS::DataReaderListener_var listener2 (new DataReaderListenerImpl);
      if (CORBA::is_nil (listener2.in ()))
      {
        cerr << "ERROR: listener2 is nil." << endl;
        exit(1);
      }


      // First data reader has 5 second deadline period.
      DDS::DataReader_var dr1 =
        sub->create_datareader (topic.in (),
                                dr_qos,
                                listener1.in (),
                                ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

      // Set up a 3 second recurring deadline.
      dr_qos.deadline.period.sec     = 3;
      dr_qos.deadline.period.nanosec = 0;

      // Second data reader has 3 second deadline period which
      // is not compatible with DataWriter.
      DDS::DataReader_var dr2 =
        sub->create_datareader (topic.in (),
                                dr_qos,
                                listener2.in (),
                                ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

      if (CORBA::is_nil (dr1.in ()) || CORBA::is_nil (dr2.in ()))
      {
        cerr << "ERROR: create_datareader failed." << endl;
        exit(1);
      }

      DataReaderListenerImpl* listener_servant1 =
        dynamic_cast<DataReaderListenerImpl*>(listener1.in());
      DataReaderListenerImpl* listener_servant2 =
        dynamic_cast<DataReaderListenerImpl*>(listener2.in());

      int expected = 10;
      // Writer of deadline 4 -> Reader of deadline 5
      while ( listener_servant1->num_reads() < expected) {
        //cout << "subscriber listener1 waiting for " << expected
             //<< " reads, got " << listener_servant1->num_reads() << std::endl;
        ACE_OS::sleep (1);
      }

      // Writer of deadline 4 and Reader of deadline 3 is not
      // compatible so second DataReader should not receive
      // any message from DataWriter.
      if (listener_servant2->num_reads() > 0)
      {
        cerr << "ERROR: second DataReader should not receive message from "
          << "datawriter as their deadline QoS is not compatible" << endl;
        exit (1);
      }

      // Wait for dr1 to be unmatched from the writer (due to writer set_qos).
      ACE_DEBUG((LM_DEBUG, "(%P|%t) check for dr1 unmatch\n"));
      DDS::WaitSet_var ws = new DDS::WaitSet;
      DDS::StatusCondition_var sc = dr1->get_statuscondition();
      sc->set_enabled_statuses(DDS::SUBSCRIPTION_MATCHED_STATUS);
      ws->attach_condition(sc);
      DDS::SubscriptionMatchedStatus matched;
      const DDS::Duration_t timeout = {5, 0}; // seconds
      while (dr1->get_subscription_matched_status(matched) == DDS::RETCODE_OK
             && matched.current_count == matched.total_count)
      {
        DDS::ConditionSeq active;
        ACE_DEBUG((LM_DEBUG, "(%P|%t) wait for dr1 unmatch\n"));
        if (ws->wait(active, timeout) == DDS::RETCODE_TIMEOUT)
        {
          cerr << "ERROR: timeout expired while waiting for dr1 to be "
            "unmatched from the writer which now has a 6 second deadline\n";
          exit (1);
        }
      }
      ws->detach_condition(sc);
      ACE_DEBUG((LM_DEBUG, "(%P|%t) done dr1 unmatch\n"));

      // Now change second DataReader to have deadline period to be 5 seconds. This
      // value is compatible with DataWriter so it will be matched.
      dr_qos.deadline.period.sec = 5;

      if (dr2->set_qos (dr_qos) != ::DDS::RETCODE_OK)
      {
        cerr << "ERROR: DataReader changed deadline period to make it compatible "
          << "with datawriter" << endl;
        exit (1);
      }

      // second DataReader should receive 20 messages so far.
      while ( listener_servant1->num_reads() < 2 * expected) {
        //cout << "subscriber listener1 waiting for " << 2 * expected
             //<< " reads, got " << listener_servant1->num_reads() << std::endl;
        ACE_OS::sleep (1);
      }

      // second DataReader should receive 10 messages.
      while ( listener_servant2->num_reads() < expected) {
        //cout << "subscriber listener2 waiting for " << expected
             //<< " reads, got " << listener_servant2->num_reads() << std::endl;
        ACE_OS::sleep (1);
      }

      // During this period, the 5 second should have at most 1 missed
      // deadline, but with 3 seconds, it should have at least 2 missed
      // deadline.
      ACE_OS::sleep (9);

      if (listener_servant2->num_deadline_missed () > 1)
      {
        cerr << "ERROR: failed to verify deadline missed count " << endl;
        exit (1);
      }

      if (!CORBA::is_nil (participant.in ())) {
        participant->delete_contained_entities();
      }
      if (!CORBA::is_nil (dpf.in ())) {
        dpf->delete_participant(participant.in ());
      }

      TheServiceParticipant->shutdown ();
    }
  catch (CORBA::Exception& e)
    {
      cerr << "SUB: Exception caught in main ():" << endl << e << endl;
      return 1;
    }
  TheServiceParticipant->shutdown ();

  return 0;
}
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  DDS::DomainParticipantFactory_var dpf = DDS::DomainParticipantFactory::_nil();
  DDS::DomainParticipant_var participant = DDS::DomainParticipant::_nil();

  try 
  {
     QuantLibAddinCpp::initializeAddin();

     boost::gregorian::date date ( boost::gregorian::from_undelimited_string( "20111019" ) );

     long evaluationDate = QuantLib::Date( date.day(), QuantLib::Month(date.month().as_number()), date.year() ).serialNumber(); 

     QuantLibAddinCpp::qlSettingsSetEvaluationDate(evaluationDate, OH_NULL);

     std::string ticker;

     // Initialize, and create a DomainParticipant
     dpf = TheParticipantFactoryWithArgs(argc, argv);
     
     qldds_utils::BasicDomainParticipant participant( dpf, EQUITY_OPTIONS_DOMAIN_ID );
     participant.createPublisher();
     participant.createSubscriber();
     DDS::DomainParticipant_var dp = participant.getDomainParticipant();  

 
     ACE_Get_Opt cmd_opts( argc, argv, ":s:" );
  
     int option;
  
     while ( (option = cmd_opts()) != EOF )
     {
       switch( option )
       {
         case 's' :
           ticker = cmd_opts.opt_arg();
           break;
       }
     }


     // Topics
     // setting up qlBlackConstantVols Topic
     DDS::Topic_var ql_black_constant_vols_topic = participant.createTopicAndRegisterType
        < qlBlackConstantVolsTypeSupport_var, qlBlackConstantVolsTypeSupportImpl >
         ( QL_BLACK_CONSTANT_VOLS_TOPIC_NAME );

     // setting up qlGeneralizedBlackScholesProcesses Topic
     DDS::Topic_var ql_generalized_black_scholes_processes_topic = participant.createTopicAndRegisterType
        < qlGeneralizedBlackScholesProcessesTypeSupport_var, qlGeneralizedBlackScholesProcessesTypeSupportImpl >
         ( QL_GENERALIZED_BLACK_SCHOLES_PROCESSES_TOPIC_NAME );

     // setting up qlStrikedTypePayoff Topic
     DDS::Topic_var ql_striked_type_payoffs_topic = participant.createTopicAndRegisterType
       < qlStrikedTypePayoffsTypeSupport_var, qlStrikedTypePayoffsTypeSupportImpl >
         ( QL_STRIKED_TYPE_PAYOFFS_TOPIC_NAME );

     // setting up qlEuropeanExercises Topic
     DDS::Topic_var ql_european_exercises_topic = participant.createTopicAndRegisterType
        < qlEuropeanExercisesTypeSupport_var, qlEuropeanExercisesTypeSupportImpl >
         ( QL_EUROPEAN_EXERCISES_TOPIC_NAME ); 

     StraddleSetupTypeSupport_var ts_res = new StraddleSetupTypeSupportImpl;
     if ( ts_res->register_type(dp, "") != DDS::RETCODE_OK )
     {
       std::cout << "Registration of the Topic FAILED!!!!" << std::endl;
     }

     CORBA::String_var type_name = ts_res->get_type_name();
     std::cout << "Type Name : " << type_name << std::endl; 

     std::stringstream multi_topic_select;

     multi_topic_select << "SELECT ticker, putVols, callVols, putPayoffs, callPayoffs, process, exercises FROM "<<
                          QL_BLACK_CONSTANT_VOLS_TOPIC_NAME << " NATURAL JOIN " << 
                          QL_GENERALIZED_BLACK_SCHOLES_PROCESSES_TOPIC_NAME << " NATURAL JOIN " <<
                          QL_STRIKED_TYPE_PAYOFFS_TOPIC_NAME << " NATURAL JOIN " << 
                          QL_EUROPEAN_EXERCISES_TOPIC_NAME << " WHERE ticker = '" << ticker << "'";

     std::cout << multi_topic_select.str() << std::endl; 

     DDS::MultiTopic_var mt = dp->create_multitopic("MyMultiTopic", type_name, multi_topic_select.str().c_str(), DDS::StringSeq()); 

     if ( CORBA::is_nil( mt ) ) 
       std::cout << "MultiTopic Subscribtion failed.!!!!" << mt << std::endl;

     DDS::Subscriber_var sub = participant.getSubscriber();
     std::cout << "Creating Data Reader"<< std::endl;
     DDS::DataReader_var dr = sub->create_datareader(mt, DATAREADER_QOS_DEFAULT, 0, ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
     std::cout << "Done..."<< std::endl;

     DDS::WaitSet_var ws = new DDS::WaitSet;
     DDS::ReadCondition_var rc = dr->create_readcondition( DDS::ANY_SAMPLE_STATE, DDS::ANY_VIEW_STATE, DDS::ANY_INSTANCE_STATE);
     ws->attach_condition(rc);
     DDS::Duration_t infinite = { DDS::DURATION_INFINITE_SEC, DDS::DURATION_INFINITE_NSEC};
     DDS::ConditionSeq active;
     int ret = ws->wait(active, infinite);
     if (ret != DDS::RETCODE_OK) return false;
     ws->detach_condition(rc);

     // setting up topic for Straddles 
     DDS::Topic_var straddles_topic = participant.createTopicAndRegisterType
        < StraddlesTypeSupport_var, StraddlesTypeSupportImpl >
         ( STRADDLES_TOPIC_NAME );

     StraddlesDataWriter_var straddles_dw = participant.createDataWriter
       < StraddlesDataWriter_var, StraddlesDataWriter >
         ( straddles_topic );

     
      int calculation_performed = 0;

      do {
       StraddleSetupDataReader_var res_dr = StraddleSetupDataReader::_narrow(dr);
       StraddleSetupSeq data;
       DDS::SampleInfoSeq info;

       int ret = res_dr->take_w_condition(data, info, DDS::LENGTH_UNLIMITED, rc);

       if (ret == DDS::RETCODE_OK) 
       {
         qlBlackConstantVolMatrix& putVols = data[0].putVols;
         qlStrikedTypePayoffSeq& putPayoffs = data[0].putPayoffs;

         qlBlackConstantVolMatrix& callVols = data[0].callVols;
         qlStrikedTypePayoffSeq& callPayoffs = data[0].callPayoffs;

         processes::qlGeneralizedBlackScholesProcess& process = data[0].process;
         qlEuropeanExerciseSeq& exercises = data[0].exercises;

         Straddles straddles;
         straddles.ticker = CORBA::string_dup( ticker.c_str() );
         straddles.underlying = data[0].process.Underlying; 

         int strike_count = putPayoffs.length() + callPayoffs.length();
         int exercises_count = exercises.length();

         straddles.options.length( strike_count * exercises_count );

         int priced_options = 0;

         price( ticker, putVols, putPayoffs, process, exercises, straddles, priced_options );
         price( ticker, callVols, callPayoffs, process, exercises, straddles, priced_options );

         ACE_DEBUG( (LM_INFO, "(%T|%P|%t) Publishing Straddles for ticker : %s trading @%f\n", ticker.c_str(), data[0].process.Underlying )  );

         int ret = straddles_dw->write( straddles, DDS::HANDLE_NIL );
         if (ret != DDS::RETCODE_OK) {
             ACE_ERROR ((LM_ERROR, ACE_TEXT("(%P|%t) ERROR: Publishing Straddles for ticker : %s failed %d.\n"), ticker.c_str(), ret));
         }

         calculation_performed++;
       } 
     } while ( calculation_performed < 30 );

    cout << "Exiting..." << endl; 
  } catch (CORBA::Exception& e) 
  {
    cerr << "Exception caught in main.cpp:" << endl << e << endl;
    ACE_OS::exit(1);
  }

  TheServiceParticipant->shutdown(); 
    
  return 0;
}
Beispiel #19
0
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  try {
    // Initialize DomainParticipantFactory
    DDS::DomainParticipantFactory_var dpf =
      TheParticipantFactoryWithArgs(argc, argv);

    // Create DomainParticipant
    DDS::DomainParticipant_var participant =
      dpf->create_participant(42,
                              PARTICIPANT_QOS_DEFAULT,
                              0,
                              OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (!participant) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("ERROR: %N:%l: main() -")
                        ACE_TEXT(" create_participant failed!\n")), -1);
    }

    // Register Type (Messenger::Message)
    Messenger::MessageTypeSupport_var ts =
      new Messenger::MessageTypeSupportImpl;

    if (ts->register_type(participant, "") != DDS::RETCODE_OK) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("ERROR: %N:%l: main() -")
                        ACE_TEXT(" register_type failed!\n")), -1);
    }

    // Create Topic (Movie Discussion List)
    CORBA::String_var type_name = ts->get_type_name();
    DDS::Topic_var topic =
      participant->create_topic("Movie Discussion List",
                                type_name,
                                TOPIC_QOS_DEFAULT,
                                0,
                                OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (!topic) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("ERROR: %N:%l: main() -")
                        ACE_TEXT(" create_topic failed!\n")), -1);
    }

    // Create Subscriber
    DDS::Subscriber_var subscriber =
      participant->create_subscriber(SUBSCRIBER_QOS_DEFAULT,
                                     0,
                                     OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (!subscriber) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("ERROR: %N:%l: main() -")
                        ACE_TEXT(" create_subscriber failed!\n")), -1);
    }

    // Create DataReader
    DDS::DataReaderListener_var listener(new DataReaderListenerImpl);

    DDS::DataReader_var reader =
      subscriber->create_datareader(topic,
                             DATAREADER_QOS_DEFAULT,
                             listener,
                             OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (!reader) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("ERROR: %N:%l: main() -")
                        ACE_TEXT(" create_datareader failed!\n")), -1);
    }

    Messenger::MessageDataReader_var reader_i =
      Messenger::MessageDataReader::_narrow(reader);

    if (!reader_i) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("ERROR: %N:%l: main() -")
                        ACE_TEXT(" _narrow failed!\n")),
                       -1);
    }

    // Block until Publisher completes
    DDS::StatusCondition_var condition = reader->get_statuscondition();
    condition->set_enabled_statuses(DDS::SUBSCRIPTION_MATCHED_STATUS);

    DDS::WaitSet_var ws = new DDS::WaitSet;
    ws->attach_condition(condition);

    while (true) {
      DDS::SubscriptionMatchedStatus matches;
      if (reader->get_subscription_matched_status(matches) != DDS::RETCODE_OK) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("ERROR: %N:%l: main() -")
                          ACE_TEXT(" get_subscription_matched_status failed!\n")), -1);
      }

      if (matches.current_count == 0 && matches.total_count > 0) {
        break;
      }

      DDS::ConditionSeq conditions;
      DDS::Duration_t timeout = { 60, 0 };
      if (ws->wait(conditions, timeout) != DDS::RETCODE_OK) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("ERROR: %N:%l: main() -")
                          ACE_TEXT(" wait failed!\n")), -1);
      }
    }

    ws->detach_condition(condition);

    // Clean-up!
    participant->delete_contained_entities();
    dpf->delete_participant(participant);

    TheServiceParticipant->shutdown();

  } catch (const CORBA::Exception& e) {
    e._tao_print_exception("Exception caught in main():");
    return -1;
  }

  return 0;
}
Beispiel #20
0
int ACE_TMAIN (int argc, ACE_TCHAR *argv[]){
  try
    {
      DDS::DomainParticipantFactory_var dpf =
        TheParticipantFactoryWithArgs(argc, argv);

      DDS::DomainParticipant_var participant =
        dpf->create_participant(11,
                                PARTICIPANT_QOS_DEFAULT,
                                DDS::DomainParticipantListener::_nil(),
                                ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
      if (CORBA::is_nil (participant.in ())) {
        ACE_DEBUG((LM_DEBUG, "create_participant failed.\n"));
        return 1;
      }

      MessageTypeSupportImpl* servant = new MessageTypeSupportImpl();

      if (DDS::RETCODE_OK != servant->register_type(participant.in (), "")) {
        ACE_DEBUG((LM_DEBUG, "register_type failed.\n"));
        exit(1);
      }

      CORBA::String_var type_name = servant->get_type_name ();

      DDS::TopicQos topic_qos;
      participant->get_default_topic_qos(topic_qos);
      DDS::Topic_var topic =
        participant->create_topic ("Movie Discussion List",
                                   type_name.in (),
                                   topic_qos,
                                   DDS::TopicListener::_nil(),
                                   ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
      if (CORBA::is_nil (topic.in ())) {
        ACE_DEBUG((LM_DEBUG, "create_topic failed.\n"));
        exit(1);
      }

      DDS::Publisher_var pub =
        participant->create_publisher(PUBLISHER_QOS_DEFAULT,
        DDS::PublisherListener::_nil(),
        ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
      if (CORBA::is_nil (pub.in ())) {
        ACE_DEBUG((LM_DEBUG, "create_publisher failed.\n"));
        exit(1);
      }

      DDS::DataWriterQos dw_qos;
      pub->get_default_datawriter_qos (dw_qos);

      dw_qos.deadline.period.sec     = 4;
      dw_qos.deadline.period.nanosec = 0;

      // Create DataWriter with 4 second deadline period which
      // should be compatible with first DataReader which has 5
      // seconds deadline period and not with second DataReader
      // which has 3 seconds deadline period.
      DDS::DataWriter_var dw =
        pub->create_datawriter(topic, dw_qos, 0,
                               OpenDDS::DCPS::DEFAULT_STATUS_MASK);

      int const max_attempts = 20000;
      int attempts = 1;
      {
        // Wait for both first DataReader connect and write messages.
        std::auto_ptr<Writer> writer (new Writer (dw.in ()));

        while (attempts != max_attempts)
        {
          ::DDS::InstanceHandleSeq handles;
          dw->get_matched_subscriptions(handles);
          if (handles.length() == 1)
            break;
          else
            ACE_OS::sleep(1);
          ++attempts;
        }

        if (attempts == max_attempts)
        {
          ACE_DEBUG((LM_DEBUG, "ERROR: subscriptions failed to match.\n"));
          exit (1);
        }

        writer->start ();
        writer->end ();

        ACE_DEBUG((LM_DEBUG, "Writer changing deadline to incompatible value\n"));

        // Now set DataWriter deadline to be 6 seconds which is not
        // compatible with the existing DataReader. This QoS change
        // should be applied and the association broken.
        dw_qos.deadline.period.sec = 6;

        if (dw->set_qos (dw_qos) != ::DDS::RETCODE_OK) {
          ACE_DEBUG((LM_DEBUG,
            "ERROR: DataWriter could not change deadline period which "
             "should break DataReader associations\n"));
          exit (1);
        } else {

          DDS::WaitSet_var ws = new DDS::WaitSet;
          DDS::StatusCondition_var sc = dw->get_statuscondition();
          sc->set_enabled_statuses(DDS::PUBLICATION_MATCHED_STATUS);
          ws->attach_condition(sc);
          DDS::PublicationMatchedStatus matched;
          DDS::ConditionSeq active;
          const DDS::Duration_t timeout = {5, 0}; // seconds
          while (dw->get_publication_matched_status(matched) == DDS::RETCODE_OK
                 && matched.current_count) {
            if (ws->wait(active, timeout) == DDS::RETCODE_TIMEOUT) {
              break;
            }
          }
          ws->detach_condition(sc);
          if (matched.current_count != 0) {
            ACE_DEBUG((LM_DEBUG,
              "ERROR: DataWriter changed deadline period which should "
              "break association with all existing DataReaders, but did not\n"));
            exit(1);
          }
        }

        // We know the reader has been disassociated, but the reader itself may
        // not have been notified yet.  Introducing delay here to let the reader
        // sync up with the disassociated state before re-associating.

        // Wait for reader to finish unmatching.
        FILE* fp = ACE_OS::fopen (synch_fname, ACE_TEXT("r"));
        int i = 0;
        while (fp == 0 &&  i < 15)
        {
          ACE_DEBUG ((LM_DEBUG,
            ACE_TEXT("(%P|%t) waiting reader to unmatch...\n")));
          ACE_OS::sleep (1);
          ++i;
          fp = ACE_OS::fopen (synch_fname, ACE_TEXT("r"));
        }
        if (fp != 0)
          ACE_OS::fclose (fp);

        ACE_DEBUG((LM_DEBUG, "Writer restoring deadline to compatible value\n"));

        // change it back
        dw_qos.deadline.period.sec = 5;

        if (dw->set_qos (dw_qos) != ::DDS::RETCODE_OK)
        {
          ACE_DEBUG((LM_DEBUG,
            "ERROR: DataWriter could not change deadline period which "
            "should restore DataReader associations\n"));
          exit (1);
        }
      }

      {
        // Wait for both second DataReader connect which changed deadline period
        // from 3 seconds to 5 seconds.
        std::auto_ptr<Writer> writer (new Writer (dw.in ()));
        attempts = 1;
        while (attempts != max_attempts)
        {
          ::DDS::InstanceHandleSeq handles;
          dw->get_matched_subscriptions(handles);
          if (handles.length() == 2)
            break;
          else
            ACE_OS::sleep(1);
          ++attempts;
        }

        if (attempts == max_attempts)
        {
          ACE_DEBUG((LM_DEBUG, "ERROR: subscriptions failed to match.\n"));
          exit(1);
        }

        writer->start ();
        writer->end ();
      }

      {
        // Wait for subscriber exit.
        attempts = 1;
        while (attempts != max_attempts)
        {
          ::DDS::InstanceHandleSeq handles;

          dw->get_matched_subscriptions(handles);
          if (handles.length() == 0)
            break;
          else
            ACE_OS::sleep(1);

          ++ attempts;
        }

        if (attempts == max_attempts)
        {
          ACE_DEBUG((LM_DEBUG, "ERROR: failed to wait for DataReader exit.\n"));
          exit (1);
        }
      }

      participant->delete_contained_entities();
      dpf->delete_participant(participant.in ());
  }
  catch (CORBA::Exception& e)
  {
    cerr << "PUB: Exception caught in main.cpp:" << endl
         << e << endl;
    exit(1);
  }
  TheServiceParticipant->shutdown ();

  return 0;
}
Beispiel #21
0
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  try
    {
      DDS::DomainParticipantFactory_var dpf;
      DDS::DomainParticipant_var participant;

      dpf = TheParticipantFactoryWithArgs(argc, argv);
      participant =
        dpf->create_participant(11,
                                PARTICIPANT_QOS_DEFAULT,
                                DDS::DomainParticipantListener::_nil(),
                                ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
      if (CORBA::is_nil (participant.in ())) {
        cerr << "create_participant failed." << endl;
        return 1 ;
      }

      Messenger::MessageTypeSupportImpl* mts_servant =
        new Messenger::MessageTypeSupportImpl;

      if (DDS::RETCODE_OK != mts_servant->register_type(participant.in (),
                                                        ""))
      {
        cerr << "Failed to register the MessageTypeTypeSupport." << endl;
        exit(1);
      }

      CORBA::String_var type_name = mts_servant->get_type_name ();

      DDS::TopicQos topic_qos;
      participant->get_default_topic_qos(topic_qos);
      DDS::Topic_var topic =
        participant->create_topic("Movie Discussion List",
                                  type_name.in (),
                                  topic_qos,
                                  DDS::TopicListener::_nil(),
                                  ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
      if (CORBA::is_nil (topic.in ())) {
        cerr << "Failed to create_topic." << endl;
        exit(1);
      }

      // Create the subscriber and attach to the corresponding
      // transport.
      DDS::Subscriber_var sub =
        participant->create_subscriber (SUBSCRIBER_QOS_DEFAULT,
                                        DDS::SubscriberListener::_nil(),
                                        ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
      if (CORBA::is_nil (sub.in ())) {
        cerr << "Failed to create_subscriber." << endl;
        exit(1);
      }


      // ----------------------------------------------
      {
        // Attempt to create a DataReader with intentionally
        // incompatible QoS.
        DDS::DataReaderQos bogus_qos;
        sub->get_default_datareader_qos (bogus_qos);

        // Set up a 2 second recurring deadline.  DataReader creation
        // should fail with this QoS since the requested deadline period
        // will be less than the test configured offered deadline
        // period.
        bogus_qos.deadline.period.sec = 2;
        bogus_qos.deadline.period.nanosec = 0;

        DDS::DataReader_var tmp_dr =
          sub->create_datareader (topic.in (),
                                  bogus_qos,
                                  DDS::DataReaderListener::_nil (),
                                  ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

        if (CORBA::is_nil (tmp_dr.in ()))
        {
          cerr << "ERROR: DataReader creation with bogus QoS failed."
               << endl;
          exit (1);
        }

        DDS::StatusCondition_var cond = tmp_dr->get_statuscondition();
        cond->set_enabled_statuses(DDS::REQUESTED_INCOMPATIBLE_QOS_STATUS);
        DDS::WaitSet_var ws = new DDS::WaitSet;
        ws->attach_condition(cond);
        DDS::Duration_t four_sec = {4, 0};
        DDS::ConditionSeq active;
        ws->wait(active, four_sec);

        // Check if the incompatible deadline was correctly flagged.
        if ((active.length() == 0) || (active[0] != cond)) {
          cerr << "ERROR: Failed to get requested incompatible qos status" << endl;
          exit (1);
        }

        DDS::RequestedIncompatibleQosStatus incompatible_status;
        if (tmp_dr->get_requested_incompatible_qos_status (incompatible_status) != ::DDS::RETCODE_OK)
        {
          cerr << "ERROR: Failed to get requested incompatible qos status" << endl;
          exit (1);
        }

        DDS::QosPolicyCountSeq const & policies =
          incompatible_status.policies;

        bool incompatible_deadline = false;
        CORBA::ULong const len = policies.length ();
        for (CORBA::ULong i = 0; i < len; ++i)
        {
          if (policies[i].policy_id == DDS::DEADLINE_QOS_POLICY_ID)
          {
            incompatible_deadline = true;
            break;
          }
        }

        if (!incompatible_deadline)
        {
          cerr << "ERROR: A DataReader/Writer association was created " << endl
               << "       despite use of deliberately incompatible deadline "
               << "QoS." << endl;
          exit (1);
        }
      }


      // ----------------------------------------------

      // Create the listener.
      DDS::DataReaderListener_var listener (new DataReaderListenerImpl);
      DataReaderListenerImpl* listener_servant =
        dynamic_cast<DataReaderListenerImpl*>(listener.in());

      if (CORBA::is_nil (listener.in ()))
      {
        cerr << "ERROR: listener is nil." << endl;
        exit(1);
      }

      DDS::DataReaderQos dr_qos; // Good QoS.
      sub->get_default_datareader_qos (dr_qos);

      assert (DEADLINE_PERIOD.sec > 1); // Requirement for the test.

      // First data reader will have a listener to test listener
      // callback on deadline expiration.
      DDS::DataReader_var dr1 =
        sub->create_datareader (topic.in (),
                                dr_qos,
                                listener.in (),
                                ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

      // Second data reader will not have a listener to test proper
      // handling of a nil listener in the deadline handling code.
      DDS::DataReader_var dr2 =
        sub->create_datareader (topic.in (),
                                dr_qos,
                                DDS::DataReaderListener::_nil (),
                                ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

      if (CORBA::is_nil (dr1.in ()) || CORBA::is_nil (dr2.in ()))
      {
        cerr << "ERROR: create_datareader failed." << endl;
        exit(1);
      }

      dr_qos.deadline.period.sec     = DEADLINE_PERIOD.sec;
      dr_qos.deadline.period.nanosec = DEADLINE_PERIOD.nanosec;

      // Reset qos to have deadline. The watch dog now starts.
      if (dr1->set_qos (dr_qos) != ::DDS::RETCODE_OK
        || dr2->set_qos (dr_qos) != ::DDS::RETCODE_OK)
      {
        cerr << "ERROR: set deadline qos failed." << endl;
        exit(1);
      }

      Messenger::MessageDataReader_var message_dr1 =
        Messenger::MessageDataReader::_narrow(dr1.in());

      Messenger::MessageDataReader_var message_dr2 =
        Messenger::MessageDataReader::_narrow(dr2.in());

      int max_attempts = 10;
      int attempts = 0;

      // Synchronize with publisher. Wait until both associate with DataWriter.
      while (attempts < max_attempts)
      {
        ::DDS::SubscriptionMatchedStatus status1;
        ::DDS::SubscriptionMatchedStatus status2;
        if (dr1->get_subscription_matched_status (status1) == ::DDS::RETCODE_OK
          && dr2->get_subscription_matched_status (status2) == ::DDS::RETCODE_OK)
        {
          if (status1.total_count == 1 && status2.total_count == 1)
            break;
          ++ attempts;
          ACE_OS::sleep (1);
        }
        else
        {
          cerr << "ERROR: Failed to get subscription matched status" << endl;
          exit (1);
        }
      }

      if (attempts >= max_attempts)
      {
        cerr << "ERROR: failed to make associations. " << endl;
        exit (1);
      }
      // ----------------------------------------------

      ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) Subscriber: sleep for %d milliseconds\n"),
                            SLEEP_DURATION.msec()));

      // Wait for deadline periods to expire.
      ACE_OS::sleep (SLEEP_DURATION);

      ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) Subscriber: now verify missed ")
                            ACE_TEXT ("deadline status \n")));

      DDS::RequestedDeadlineMissedStatus deadline_status1;
      if (dr1->get_requested_deadline_missed_status(deadline_status1) != ::DDS::RETCODE_OK)
      {
        cerr << "ERROR: Failed to get requested deadline missed status" << endl;
        exit (1);
      }

      DDS::RequestedDeadlineMissedStatus deadline_status2;
      if (dr2->get_requested_deadline_missed_status(deadline_status2) != ::DDS::RETCODE_OK)
      {
        cerr << "ERROR: Failed to get requested deadline missed status" << endl;
        exit (1);
      }

      ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) Subscriber: got missed")
                            ACE_TEXT ("deadline status \n")));

      Messenger::Message message;
      message.subject_id = 99;
      ::DDS::InstanceHandle_t dr1_hd1 = message_dr1->lookup_instance (message);
      ::DDS::InstanceHandle_t dr2_hd1 = message_dr2->lookup_instance (message);
      message.subject_id = 100;
      ::DDS::InstanceHandle_t dr1_hd2 = message_dr1->lookup_instance (message);
      ::DDS::InstanceHandle_t dr2_hd2 = message_dr2->lookup_instance (message);

      if (deadline_status1.last_instance_handle != dr1_hd1
        && deadline_status1.last_instance_handle != dr1_hd2)
      {
        cerr << "ERROR: Expected DR1 last instance handle ("
             << dr1_hd1 << " or " << dr1_hd2 << ") did not occur ("
             << deadline_status1.last_instance_handle << ")" << endl;

        exit (1);
      }

      if (deadline_status2.last_instance_handle != dr2_hd1
        && deadline_status2.last_instance_handle != dr2_hd2)
      {
        cerr << "ERROR: Expected DR2 last instance handle ("
             << dr2_hd1 << " or " << dr2_hd2 << ") did not occur ("
             << deadline_status2.last_instance_handle << endl;

        exit (1);
      }

      //The reader deadline period is 5 seconds and writer writes
      //each instance every 9 seconds, so after SLEEP_DURATION(11secs),
      //the deadline missed should be 1 per instance
      if (deadline_status1.total_count != NUM_INSTANCE
          || deadline_status2.total_count != NUM_INSTANCE)
      {
        cerr << "ERROR: Expected number of missed requested "
             << "deadlines (" << NUM_INSTANCE << ") " << "did " << endl
             << "       not occur ("
             << deadline_status1.total_count << " and/or "
             << deadline_status2.total_count << ")." << endl;

        exit (1);
      }

      if (deadline_status1.total_count_change != NUM_INSTANCE
          || deadline_status2.total_count_change != NUM_INSTANCE)
      {
        cerr << "ERROR: Incorrect missed requested "
             << "deadline count change" << endl
             << "       ("
             << deadline_status1.total_count_change
             << " and/or "
             << deadline_status2.total_count_change
             << " instead of " << NUM_EXPIRATIONS * NUM_INSTANCE << ")."
             << endl;

        exit (1);
      }

      // Here the writers should continue writes all samples with
      // .5 second interval.
      ACE_Time_Value no_miss_period = num_messages * write_interval;

      ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) Subscriber: sleep for %d msec\n"),
                            (SLEEP_DURATION + no_miss_period).msec()));

      // Wait for another set of deadline periods(5 + 11 secs).
      // During this period, the writers continue write all samples with
      // .5 second interval.
      ACE_OS::sleep (SLEEP_DURATION + no_miss_period);

      ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) Subscriber: now verify missed ")
                            ACE_TEXT ("deadline status \n")));

      if ((dr1->get_requested_deadline_missed_status(deadline_status1) != ::DDS::RETCODE_OK)
        || (dr2->get_requested_deadline_missed_status(deadline_status2) != ::DDS::RETCODE_OK))
      {
        cerr << "ERROR: failed to get requested deadline missed status" << endl;
        exit (1);
      }

      ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) Subscriber: got missed")
                            ACE_TEXT ("deadline status \n")));

      if (deadline_status1.last_instance_handle != dr1_hd1
        && deadline_status1.last_instance_handle != dr1_hd2)
      {
        cerr << "ERROR: Expected DR1 last instance handle ("
             << dr1_hd1 << " or " << dr1_hd2 << ") did not occur ("
             << deadline_status1.last_instance_handle << ")" << endl;

        exit (1);
      }

      if (deadline_status2.last_instance_handle != dr2_hd1
        && deadline_status2.last_instance_handle != dr2_hd2)
      {
        cerr << "ERROR: Expected DR2 last instance handle ("
             << dr2_hd1 << " or " << dr2_hd2 << ") did not occur ("
             << deadline_status2.last_instance_handle << endl;

        exit (1);
      }

      if (deadline_status1.total_count != 3 * NUM_INSTANCE
          || deadline_status2.total_count != 3 * NUM_INSTANCE)
      {
        cerr << "ERROR: Another expected number of missed requested "
             << "deadlines (" << NUM_INSTANCE << ")" << endl
             << "       did not occur ("
             << deadline_status1.total_count << " and/or "
             << deadline_status2.total_count << ")." << endl;

        exit (1);
      }

      if (deadline_status1.total_count_change != 2 * NUM_INSTANCE
          || deadline_status2.total_count_change != 2 * NUM_INSTANCE)
      {
        cerr << "ERROR: Incorrect missed requested "
             << "deadline count" << endl
             << "       change ("
             << deadline_status1.total_count_change
             << "and/or "
             << deadline_status2.total_count_change
             << " instead of " << NUM_EXPIRATIONS << ")." << endl;

        exit (1);
      }


      int expected = 10;
      while ( listener_servant->num_arrived() < expected) {
        ACE_OS::sleep (1);
      }

      if (!CORBA::is_nil (participant.in ())) {
        participant->delete_contained_entities();
      }
      if (!CORBA::is_nil (dpf.in ())) {
        dpf->delete_participant(participant.in ());
      }

      ACE_OS::sleep(2);

      TheServiceParticipant->shutdown ();
    }
  catch (CORBA::Exception& e)
    {
      cerr << "SUB: Exception caught in main ():" << endl << e << endl;
      return 1;
    }

  return 0;
}
  int svc()
  {
    int thread_id = thread_counter_++;

    // Create Publisher
    DDS::Publisher_var publisher =
      participant_->create_publisher(PUBLISHER_QOS_DEFAULT,
                                     0,
                                     OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (!publisher) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("ERROR: %N:%l: main() -")
                        ACE_TEXT(" create_publisher failed!\n")),
                       -1);
    }

    writers_[thread_id].resize(6);

    ACE_DEBUG((LM_DEBUG, "(%P|%t) Starting DataWriter %C\n", writers_[thread_id].c_str()));

    DDS::DataWriterQos qos;
    publisher->get_default_datawriter_qos(qos);
    qos.user_data.value.length(3);
    qos.user_data.value[0] = fromhex(writers_[thread_id], 0);
    qos.user_data.value[1] = fromhex(writers_[thread_id], 1);
    qos.user_data.value[2] = fromhex(writers_[thread_id], 2);

    if (reliable_) {
      qos.reliability.kind = DDS::RELIABLE_RELIABILITY_QOS;
      qos.reliability.max_blocking_time.sec = DDS::DURATION_INFINITE_SEC;
      // qos.resource_limits.max_instances = 10;
      // qos.history.depth = 10;
    } else {
      qos.reliability.kind = DDS::BEST_EFFORT_RELIABILITY_QOS;
    }

    // Create DataWriter
    DDS::DataWriter_var writer =
      publisher->create_datawriter(topic_,
                                   qos,
                                   0,
                                   OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (!writer) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("ERROR: %N:%l: main() -")
                        ACE_TEXT(" create_datawriter failed!\n")),
                       -1);
    }

    TestMsgDataWriter_var message_writer =
      TestMsgDataWriter::_narrow(writer);

    if (!message_writer) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("ERROR: %N:%l: main() -")
                        ACE_TEXT(" _narrow failed!\n")),
                       -1);
    }

    // Block until Subscriber is available
    DDS::StatusCondition_var condition = writer->get_statuscondition();
    condition->set_enabled_statuses(DDS::PUBLICATION_MATCHED_STATUS);

    DDS::WaitSet_var ws = new DDS::WaitSet;
    ws->attach_condition(condition);

    while (true) {
      DDS::PublicationMatchedStatus matches;
      if (writer->get_publication_matched_status(matches) != ::DDS::RETCODE_OK) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("ERROR: %N:%l: main() -")
                          ACE_TEXT(" get_publication_matched_status failed!\n")),
                         -1);
      }

      ACE_DEBUG((LM_DEBUG, "(%P|%t) DataWriter %C has %d of %d readers\n", writers_[thread_id].c_str(), matches.current_count, total_readers_));
      if (matches.current_count >= total_readers_) {
        break;
      }

      DDS::ConditionSeq conditions;
      DDS::Duration_t timeout = { 60, 0 };
      if (ws->wait(conditions, timeout) != DDS::RETCODE_OK) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("ERROR: %N:%l: main() -")
                          ACE_TEXT(" wait failed!\n")),
                         -1);
      }
    }

    ws->detach_condition(condition);

    // Write samples
    TestMsg message;
    message.value = 0;
    for (int i = 0; i < MSGS_PER_WRITER; ++i) {
      DDS::ReturnCode_t error = message_writer->write(message, DDS::HANDLE_NIL);
      ++message.value;

      if (error != DDS::RETCODE_OK) {
        ACE_ERROR((LM_ERROR,
                   ACE_TEXT("ERROR: %N:%l: main() -")
                   ACE_TEXT(" write returned %d!\n"), error));
      }
    }

    ACE_DEBUG((LM_DEBUG, "(%P|%t) DataWriter %C is waiting for acknowledgements\n", writers_[thread_id].c_str()));
    DDS::Duration_t timeout = { 30, 0 };
    message_writer->wait_for_acknowledgments(timeout);
    // With static discovery, it's not an error for wait_for_acks to fail
    // since the peer process may have terminated before sending acks.
    ACE_DEBUG((LM_DEBUG, "(%P|%t) DataWriter %C is done\n", writers_[thread_id].c_str()));

    return 0;
  }
Beispiel #23
0
int ACE_TMAIN(int argc, ACE_TCHAR** argv)
{
  try {
    OpenDDS::Model::Application application(argc, argv);
    UDP::DefaultUDPType model(application, argc, argv);

    using OpenDDS::Model::UDP::Elements;

    DDS::DataWriter_var writer = model.writer( Elements::DataWriters::writer);

    // START OF EXISTING MESSENGER EXAMPLE CODE

    MessageDataWriter_var message_writer =
      MessageDataWriter::_narrow(writer.in());

    if (CORBA::is_nil(message_writer.in())) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("(%P|%t) ERROR: %N:%l: main() -")
                          ACE_TEXT(" _narrow failed!\n")),
                         -1);
    }

    // Block until Subscriber is available
    DDS::StatusCondition_var condition = writer->get_statuscondition();
    condition->set_enabled_statuses(DDS::PUBLICATION_MATCHED_STATUS);

    DDS::WaitSet_var ws = new DDS::WaitSet;
    ws->attach_condition(condition);

    DDS::ConditionSeq conditions;
    DDS::PublicationMatchedStatus matches = { 0, 0, 0, 0, 0 };
    DDS::Duration_t timeout = { 30, 0 };

    do {
      if (ws->wait(conditions, timeout) != DDS::RETCODE_OK) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("(%P|%t) ERROR: %N:%l: main() -")
                          ACE_TEXT(" wait failed!\n")),
                         -1);
      }

      if (writer->get_publication_matched_status(matches) != ::DDS::RETCODE_OK) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("(%P|%t) ERROR: %N:%l: main() -")
                          ACE_TEXT(" get_publication_matched_status failed!\n")),
                         -1);
      }

    } while (matches.current_count < 1);

    ws->detach_condition(condition);

    // Write samples
    Message message;
    message.subject_id = 99;

    message.from       = CORBA::string_dup("Comic Book Guy");
    message.subject    = CORBA::string_dup("Review");
    message.text       = CORBA::string_dup("Worst. Movie. Ever.");
    message.count      = 0;

    for (int i = 0; i < 10; i++) {
      DDS::ReturnCode_t error = message_writer->write(message, DDS::HANDLE_NIL);
      ++message.count;

      if (error != DDS::RETCODE_OK) {
        ACE_ERROR((LM_ERROR,
                   ACE_TEXT("(%P|%t) ERROR: %N:%l: main() -")
                   ACE_TEXT(" write returned %d!\n"), error));
      }
    }

    // Cannot wait for samples to be acknowledged - not supported in UDP
    std::cout << "publisher sleeping...." << std::endl;
    ACE_OS::sleep(2);
    std::cout << "publisher done sleeping" << std::endl;

    // END OF EXISTING MESSENGER EXAMPLE CODE
  } catch (const CORBA::Exception& e) {
    e._tao_print_exception("Exception caught in main():");
    return -1;

  } catch( const std::exception& ex) {
    ACE_ERROR_RETURN((LM_ERROR,
                      ACE_TEXT("(%P|%t) ERROR: %N:%l: main() -")
                      ACE_TEXT(" Exception caught: %C\n"),
                      ex.what()),
                     -1);
  }

  return 0;
}
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  try {
    // Initialize DomainParticipantFactory
    DDS::DomainParticipantFactory_var dpf =
      TheParticipantFactoryWithArgs(argc, argv);

    int error;
    if ((error = parse_args(argc, argv)) != 0) {
      return error;
    }

    // Create DomainParticipant
    DDS::DomainParticipant_var participant =
      dpf->create_participant(4,
                              PARTICIPANT_QOS_DEFAULT,
                              DDS::DomainParticipantListener::_nil(),
                              OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (CORBA::is_nil(participant.in())) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l main()")
                        ACE_TEXT(" ERROR: create_participant() failed!\n")), -1);
    }

    // Register Type (Messenger::Message)
    Messenger::MessageTypeSupport_var ts =
      new Messenger::MessageTypeSupportImpl();

    if (ts->register_type(participant.in(), "") != DDS::RETCODE_OK) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l main()")
                        ACE_TEXT(" ERROR: register_type() failed!\n")), -1);
    }

    // Create Topic (Movie Discussion List)
    DDS::Topic_var topic =
      participant->create_topic("Movie Discussion List",
                                ts->get_type_name(),
                                TOPIC_QOS_DEFAULT,
                                DDS::TopicListener::_nil(),
                                OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (CORBA::is_nil(topic.in())) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l main()")
                        ACE_TEXT(" ERROR: create_topic() failed!\n")), -1);
    }

    // Create Subscriber
    DDS::Subscriber_var sub =
      participant->create_subscriber(SUBSCRIBER_QOS_DEFAULT,
                                     DDS::SubscriberListener::_nil(),
                                     OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (CORBA::is_nil(sub.in())) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l main()")
                        ACE_TEXT(" ERROR: create_subscriber() failed!\n")), -1);
    }

    // Create DataReader
    DataReaderListenerImpl listener;

    DDS::DataReader_var reader =
      sub->create_datareader(topic.in(),
                             DATAREADER_QOS_DEFAULT,
                             &listener,
                             OpenDDS::DCPS::DEFAULT_STATUS_MASK);

    if (CORBA::is_nil(reader.in())) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("%N:%l main()")
                        ACE_TEXT(" ERROR: create_datareader() failed!\n")), -1);
    }

    // Block until Publisher completes
    DDS::StatusCondition_var condition = reader->get_statuscondition();
    condition->set_enabled_statuses(DDS::SUBSCRIPTION_MATCHED_STATUS);

    DDS::WaitSet_var ws = new DDS::WaitSet;
    ws->attach_condition(condition);

    DDS::Duration_t timeout =
      { DDS::DURATION_INFINITE_SEC, DDS::DURATION_INFINITE_NSEC };

    DDS::ConditionSeq conditions;
    DDS::SubscriptionMatchedStatus matches = { 0, 0, 0, 0, 0 };

    do {
      if (ws->wait(conditions, timeout) != DDS::RETCODE_OK) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("%N:%l main()")
                          ACE_TEXT(" ERROR: wait() failed!\n")), -1);
      }

      if (reader->get_subscription_matched_status(matches) != DDS::RETCODE_OK) {
        ACE_ERROR_RETURN((LM_ERROR,
                          ACE_TEXT("%N:%l main()")
                          ACE_TEXT(" ERROR: get_subscription_matched_status() failed!\n")), -1);
      }
    } while (matches.current_count > 0);

    ws->detach_condition(condition);

    // Clean-up!
    participant->delete_contained_entities();
    dpf->delete_participant(participant.in());

    TheServiceParticipant->shutdown();

  } catch (const CORBA::Exception& e) {
    e._tao_print_exception("Exception caught in main():");
    return -1;
  }

  return 0;
}