int runTests(CORBA::ORB_var orb, First::IHello_ptr hello)
{
	result = 0;

	try
	{
		std::cout << "  AddValue: ";
		check(5 == hello->AddValue(2, 3));
	}
	catch (...)
	{
		check(false);
	}

	try
	{
		std::cout << "  SayHello: ";
		check(std::wstring(L"Hello, Andy. It's Bob.") == (wchar_t*)CORBA::WString_var(hello->SayHello(L"Andy")));
	}
	catch (...)
	{
		check(false);
	}

	try
	{
		std::cout << "  SayHello2: ";
		CORBA::String_var greeting;
		hello->SayHello2("Andy", greeting.out());
		check(std::string("Hello, Andy. It's Bob.") == (char*)greeting);
	}
	catch (...)
	{
		check(false);
	}

	try
	{
		std::cout << "  Message: ";
		CORBA::String_var message = "Hello, Bob";
		hello->Message(message.inout());
		check(std::string("Hello, Andy.") == (char*)message);
	}
	catch (...)
	{
		check(false);
	}

	try
	{
		std::cout << "  MulComplex: ";
		First::MyComplexNumber x, y;
		x.re = 2, x.im = 3;
		y.re = 5, y.im = 6;
		First::MyComplexNumber expected;
		expected.re = x.re * y.re - x.im * y.im;
		expected.im = x.re * y.im + x.im - y.re;

		First::MyComplexNumber result = hello->MulComplex(x, y);
		check(equal(result, expected) && equal(result, y));
	}
	catch (...)
	{
		check(false);
	}

	try
	{
		std::cout << "  MulComplexAsAny: ";
		First::MyComplexNumber x, y;
		x.re = 2, x.im = 3;
		y.re = 5, y.im = 6;
		First::MyComplexNumber expected;
		expected.re = x.re * y.re - x.im * y.im;
		expected.im = x.re * y.im + x.im - y.re;

		CORBA::Any _x, _y;
		_x <<= x;
		_y <<= y;

		CORBA::Any_var _result;
		bool success = hello->MulComplexAsAny(_x, _y, _result.out());

		First::MyComplexNumber* result;
		_result >>= result;

		check(success && result && equal(*result, expected));
	}
	catch (...)
	{
		check(false);
	}

	try
	{
		std::cout << "  DataTimeTransfer: ";
		SYSTEMTIME initial_systemtime = {};
		initial_systemtime.wMilliseconds = 0;
		initial_systemtime.wSecond = 0;
		initial_systemtime.wMinute = 0;
		initial_systemtime.wHour = 0;
		initial_systemtime.wDay = 8;
		initial_systemtime.wDayOfWeek = 1;
		initial_systemtime.wMonth = 2;
		initial_systemtime.wYear = 2016;

		FILETIME initial_filetime;
		SystemTimeToFileTime(&initial_systemtime, &initial_filetime);
		__int64 val = SysytemTimeToInt64(initial_systemtime);

		hello->DataTimeTransfer(val);

		FILETIME return_filetime;
		Int64ToFileTime(&val, &return_filetime);

		check(CompareFileTime(&initial_filetime, &return_filetime) == 0);
	}
	catch (...)
	{
		check(false);
	}

	try
	{
		std::cout << "  Install exceptions hadlers: ";
		omniORB::installTransientExceptionHandler(hello, 0, transientExceptionHandler);
		omniORB::installSystemExceptionHandler(hello, 0, systemExceptionHandler);
		check(true);
	}
	catch (...)
	{
		check(false);
	}

	try
	{
		std::cout << "  Catch NO_IMPLEMENT: ";
		expectedExceptionType = SYSTEM_EXCEPTION_TYPE;
		exceptionProperlyHandled = false;
		hello->ThrowExceptions(0);
	}
	catch (CORBA::NO_IMPLEMENT& se)
	{
		check(exceptionProperlyHandled && 1 == se.minor());
	}
	catch (...)
	{
		check(false);
	}

	try
	{
		std::cout << "  Catch TRANSIENT: ";
		expectedExceptionType = TRANSIENT_EXCEPTION_TYPE;
		exceptionProperlyHandled = false;
		hello->ThrowExceptions(3);
	}
	catch (CORBA::TRANSIENT& se)
	{
		std::string ex_neame = se._name();
		check(exceptionProperlyHandled && ex_neame.compare("TRANSIENT") == 0);
	}
	catch (...)
	{
		check(false);
	}

	try
	{
		std::cout << "  Catch plain user exception: ";
		hello->ThrowExceptions(1);
	}
	catch (First::IHello::UserExceptionS& ue)
	{
		check(std::string("UserExceptionS") == ue._name());
	}
	catch (...)
	{
		check(false);
	}

	try
	{
		std::cout << "  Catch user exception with members: ";
		hello->ThrowExceptions(2);
	}
	catch (First::IHello::UserExceptionExt& ue)
	{
		check((std::string("EXCEPTIONS_WORKS") == (char*)ue.reason) && (254 == ue.codeError));
	}
	catch (...)
	{
		check(false);
	}

	try
	{
		std::cout << "  Catch unknown exception: ";
		hello->ThrowExceptions(4);
	}
	catch (CORBA::UNKNOWN& se)
	{
		check(std::string("UNKNOWN") == (char*)se._name());
	}
	catch (...)
	{
		check(false);
	}

	try
	{
		std::cout << "  Sequence reversed: ";

		int row[] = { 1, 3, 5, 7, 10 };
		int length = sizeof(row) / sizeof(row[0]);

		First::SequenceLong_var sequence(new First::SequenceLong());
		sequence->length(length);
		for (int i = 0; i < length; ++i)
		{
			sequence[i] = row[i];
		}

		First::SequenceLong_var reversed = hello->Reverse(sequence.in());

		if (5 == reversed->length())
		{
			check((reversed[0] == row[4]) && (reversed[1] == row[3]) && (reversed[2] == row[2]) && (reversed[3] == row[1]) && (reversed[4] == row[0]));
		}
		else
			check(false);
	}
	catch (...)
	{
		check(false);
	}

	try
	{
		std::cout << "  Callback: ";

		PortableServer::POA_var poa = createBidirectionalPOA(orb);

		TestCallBackImpl* pCallback = new TestCallBackImpl();
		PortableServer::ObjectId_var oid = poa->activate_object(pCallback);
		First::ITestCallBack_var callback(pCallback->_this());
		pCallback->_remove_ref();

		check(hello->CallMe(callback) && pCallback->Greeting() == "Hello from Server");
	}
	catch (...)
	{
		check(false);
	}

	try
	{
		std::cout << "  Pass single dimensional array: ";

		First::Vector4_var x = First::Vector4_alloc();
		x[0] = 1.0; x[1] = 2.0; x[2] = 3; x[3] = -4.0;

		First::Vector4_var y = First::Vector4_alloc();
		y[0] = -1.0; y[1] = 12.0; y[2] = 4.1; y[3] = 0;

		double expected[] = {
			x[0] + y[0],
			x[1] + y[1],
			x[2] + y[2],
			x[3] + y[3]
		};

		First::Vector4_slice* result = hello->AddVectors(x, y);
		bool equal = result[0] == expected[0] && result[1] == expected[1] && result[2] == expected[2] && result[3] == expected[3];
		
		First::Vector4_free(result);

		check(equal);
	}
	catch (...)
	{
		check(false);
	}

	try
	{
		std::cout << "  Pass multi dimensional array: ";

		First::Matrix3x4_var x = First::Matrix3x4_alloc();
		x[0][0] =  1.0; x[0][1] = -2.0; x[0][2] =  3; x[0][3] = 4.1;
		x[1][0] =  2.0; x[1][1] =  4.0; x[1][2] = -6; x[1][3] = 8.1;
		x[2][0] = -3.0; x[2][1] = -5.0; x[2][2] =  7; x[2][3] =  -1;

		First::Matrix3x4_var y = First::Matrix3x4_alloc();
		y[0][0] =  3.0; y[0][1] = -2.4; y[0][2] =  3; y[0][3] =  -0;
		y[1][0] =  6.0; y[1][1] =  2.0; y[1][2] = -7; y[1][3] = 8.9;
		y[2][0] = -7.0; y[2][1] = -1.0; y[2][2] =  7; y[2][3] =   1;

		double expected[3][4] = {
			{ x[0][0] + y[0][0], x[0][1] + y[0][1], x[0][2] + y[0][2], x[0][3] + y[0][3] },
			{ x[1][0] + y[1][0], x[1][1] + y[1][1], x[1][2] + y[1][2], x[1][3] + y[1][3] },
			{ x[2][0] + y[2][0], x[2][1] + y[2][1], x[2][2] + y[2][2], x[2][3] + y[2][3] }
		};

		First::Matrix3x4_slice* result = hello->AddMatrixes(x, y);

		//check selectively
		bool equal = result[0][0] == expected[0][0] && result[1][3] == expected[1][3] && result[2][0] == expected[2][0] && result[2][3] == expected[2][3];

		First::Matrix3x4_free(result);

		check(equal);
	}
	catch (...)
	{
		check(false);
	}

	try
	{
		std::cout << "  Shutdown: ";
		hello->Shutdown();
		check(true);
	}
	catch (...)
	{
		check(false);
	}

	return result;
}
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{

    try {
        // Initialize orb
        CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);

        if (parse_args (argc, argv) != 0)
            return 1;

        //Get reference to Root POA
        CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
        PortableServer::POA_var poa = PortableServer::POA::_narrow(obj.in());

        // Activate POA Manager
        PortableServer::POAManager_var mgr = poa->the_POAManager();
        mgr->activate();

        // Find the Naming Service
        obj = orb->resolve_initial_references("NameService");
        CosNaming::NamingContextExt_var root =
            CosNaming::NamingContextExt::_narrow(obj.in());
        if (CORBA::is_nil(root.in())) {
            std::cerr << "Nil Naming Context reference" << std::endl;
            return 1;
        }

        // Bind a new context.
        CosNaming::Name name;
        name.length( 1 );
        name[0].id = CORBA::string_dup( "root.esc-dot" );
        name[0].kind = CORBA::string_dup( "kind1" );

        try {
            obj = root->resolve(name);
        }
        catch(const CosNaming::NamingContext::NotFound&) {
            CosNaming::NamingContext_var dummy = root->bind_new_context(name);
        }

        name.length( 2 );
        name[1].id = CORBA::string_dup( "leaf/esc-slash" );
        name[1].kind = CORBA::string_dup( "kind2" );

        // Create an object
        PortableServer::Servant_var<Messenger_i> servant = new Messenger_i;
        PortableServer::ObjectId_var oid = poa->activate_object(servant.in());
        CORBA::Object_var messenger_obj = poa->id_to_reference(oid.in());
        root->rebind(name, messenger_obj.in());

        // Also try rebinding to a simple path.
        CosNaming::Name_var simp_name = root->to_name("Simple");
        try {
            obj = root->resolve(simp_name.in());
        }
        catch(const CosNaming::NamingContext::NotFound&) {
            CosNaming::NamingContext_var dummy =
                root->bind_new_context(simp_name.in());
        }
        simp_name = root->to_name("Simple/Messenger");
        root->rebind(simp_name.in(), messenger_obj.in());

        // Convert Name to String Name.
        CORBA::String_var str_name = root->to_string(name);
        std::cout << "str_name:  " << str_name.in() << std::endl;
        CORBA::String_var str_simple = root->to_string(simp_name.in());
        std::cout << "simple: " << str_simple.in() << std::endl;

        // Convert String Name to Name.
        CosNaming::Name_var tname = root->to_name(str_name.in());

        std::cout << "converted back to a CosNaming::Name: " << std::endl;
        std::cout << "   name[0] = " << (* tname)[0].id.in() << " , "
                  << (* tname)[0].kind.in() << std::endl;
        std::cout << "   name[1] = " << (* tname)[1].id.in() << " , "
                  << (* tname)[1].kind.in() << std::endl;

        // Find the application object by resolve_str.
        try {
            obj = root->resolve_str(str_name.in());
        }
        catch(const CosNaming::NamingContext::NotFound&) {
            std::cerr<<"Couldn't resolve the string name:  " << str_name << std::endl;
            return 1;
        }

        ACE_CString base_address (":");
        base_address += ACE_TEXT_ALWAYS_CHAR (hostname);
        base_address += ":";
        base_address += ACE_TEXT_ALWAYS_CHAR (port);
        ACE_CString addr ("");
        addr = base_address + "/key/str";

        // Create an URL string for application object.
        CORBA::String_var address = CORBA::string_dup (addr.c_str());

        std::cout << "call to_url(\"" << address.in() << "\"" << std::endl;
        std::cout << "           ,\"" << str_simple.in() << "\")"<< std::endl;

        CORBA::String_var url_string = root->to_url(address.in(), str_simple.in());

        std::cout << "to_url result: " << url_string.in() << std::endl;


        // Write NS url to a file to let client read NS URL to get
        // NamingContext reference.
        CORBA::String_var ns_addr = CORBA::string_dup(base_address.c_str());

        std::cout << "call to_url(\"" <<ns_addr.in() << "\",\""
                  << str_simple.in() << "\")"<< std::endl;

        CORBA::String_var url = root->to_url(ns_addr.in(), str_simple.in());
        std::cout << "to_url result:    " << url.in() << std::endl;


        std::ofstream iorFile(ACE_TEXT_ALWAYS_CHAR (ior_output_file));
        iorFile << url.in() << std::endl;
        iorFile.close();

        std::cout << "Naming Service URL written to file " << ior_output_file << std::endl;

        // Accept requests
        orb->run();
        orb->destroy();
    }
    catch(const CORBA::Exception& ex) {
        std::cerr << "Caught a CORBA::Exception: " << ex << std::endl;
        return 1;
    }

    return 0;
}
Exemple #3
0
int
ACE_TMAIN (int argc, ACE_TCHAR *argv [])
{
  try {
    // Initialize the ORB.
    CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);

    if (parse_args (argc, argv) != 0)
      return 1;

    // Get a reference to Root POA.
    CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
    PortableServer::POA_var poa = PortableServer::POA::_narrow(obj.in());

    // Activate the POA manager.
    PortableServer::POAManager_var mgr = poa->the_POAManager();
    mgr->activate();

    // Create a Logger_i servant.
    PortableServer::Servant_var<Logger_i> logger_servant = new Logger_i;

    // Register the servant with the RootPOA, obtain its object reference,
    // stringify it, and write it to a file.
    PortableServer::ObjectId_var oid = poa->activate_object(logger_servant.in());
    CORBA::Object_var logger_obj = poa->id_to_reference(oid.in());
    CORBA::String_var str = orb->object_to_string(logger_obj.in());
    std::ofstream iorFile(ACE_TEXT_ALWAYS_CHAR(ior_output_file));
    iorFile << str.in() << std::endl;
    iorFile.close();
    std::cout << "IOR written to file " << ACE_TEXT_ALWAYS_CHAR(ior_output_file) << std::endl;

    // Accept requests from clients.
    orb->run();

    // Release resources.
    orb->destroy();
  }
  catch(const CORBA::Exception& ex) {
    std::cerr << "Caught a CORBA exception:" << ex << std::endl;
    return 1;
  }
  return 0;
}
Exemple #4
0
int
ACE_TMAIN (int argc, ACE_TCHAR *argv [])
{
  try {
    // Initialize orb
    CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);

    if (parse_args (argc, argv) != 0)
      return 1;

    // Get reference to Root POA.
    CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
    PortableServer::POA_var poa = PortableServer::POA::_narrow(obj.in());

    // Activate POA manager
    PortableServer::POAManager_var mgr = poa->the_POAManager();
    mgr->activate();

    // Create an object
    PortableServer::Servant_var<Messenger_i> messenger_servant =
      new Messenger_i;

    // Write its stringified reference to a file
    PortableServer::ObjectId_var oid = poa->activate_object(messenger_servant.in());
    obj = poa->id_to_reference(oid.in());
    Messenger_var messenger = Messenger::_narrow(obj.in());
    CORBA::String_var str = orb->object_to_string(messenger.in());
    std::ofstream fout(ACE_TEXT_ALWAYS_CHAR(ior_output_file));
    fout << str.in() << std::endl;
    fout.close();
    std::cout << "IOR written to file " << ACE_TEXT_ALWAYS_CHAR(ior_output_file) << std::endl;

    // Accept requests
    orb->run();
    orb->destroy();
  }
  catch(const CORBA::Exception& ex) {
    std::cerr << "CORBA::Exception " << ex << std::endl;
    return 1;
  }

  return 0;
}
Exemple #5
0
int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  try
    {
      CORBA::ORB_var orb = CORBA::ORB_init (argc, argv);

      TestShutdown killer (orb.in ());

      if (parse_args (argc, argv) != 0)
        return 1;

      CORBA::Object_var pPoaObj =
        orb->resolve_initial_references ("RootPOA");
      PortableServer::POA_var poa =
        PortableServer::POA::_narrow (pPoaObj.in ());
      PortableServer::POAManager_var pMgr = poa->the_POAManager ();
      pMgr->activate ();

      SimpleNamingService_i* servant = new SimpleNamingService_i;
      PortableServer::ObjectId_var oid = poa->activate_object (servant);
      CORBA::Object_var obj = poa->id_to_reference (oid.in ());
      CORBA::String_var str = orb->object_to_string (obj.in ());

      FILE *output_file= ACE_OS::fopen (iorFileName, "w");
      if (output_file == 0)
        ACE_ERROR_RETURN ((LM_ERROR,
                           "Cannot open output file for writing IOR: %s\n",
                           iorFileName),
                           1);
      ACE_OS::fprintf (output_file, "%s", str.in ());
      ACE_OS::fclose (output_file);

      orb->run ();
    }
  catch (CORBA::Exception& ex)
    {
      ACE_DEBUG ((LM_ERROR, "Corba Exception: %s\n", ex._info ().c_str ()));
      return 1;
    }

  return 0;
}
Exemple #6
0
int
ACE_TMAIN (int argc, ACE_TCHAR *argv [])
{
  try
    {
      CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);

      if (parse_args (argc, argv) != 0)
        return 1;

      CORBA::Object_var rootObj = orb->resolve_initial_references("NameService");
      CosNaming::NamingContext_var rootNC =
      CosNaming::NamingContext::_narrow(rootObj.in());

      CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
      PortableServer::POA_var poa = PortableServer::POA::_narrow(obj.in());
      PortableServer::POAManager_var mgr = poa->the_POAManager();
      mgr->activate();

      PortableServer::Servant_var<Messenger_i> messenger_servant =
        new Messenger_i(orb.in ());
      PortableServer::ObjectId_var oid = poa->activate_object (messenger_servant.in());
      CORBA::Object_var messenger_obj = poa->id_to_reference (oid.in ());
      CORBA::String_var str = orb->object_to_string (messenger_obj.in());

      std::ofstream iorFile (ACE_TEXT_ALWAYS_CHAR(ior_output_file));
      iorFile << str.in () << std::endl;
      iorFile.close ();
      std::cout << "IOR written to file " << ior_output_file << std::endl;

      orb->run ();
      orb->destroy ();
    }

  catch(const CORBA::Exception& ex)
  {
      std::cerr << "Caught exception: " << ex << std::endl;
      return 1;
  }

  return 0;
}
Exemple #7
0
Broker::Logger_ptr
manager_i::getLogger()
{
    PortableServer::POA_var poa = ::adbroker::manager_i::instance()->poa();
    if ( CORBA::is_nil( poa ) )
        return 0;

    if ( ! logger_i_ ) {
        logger_i_.reset( new broker::logger_i( poa ) );
        PortableServer::ObjectId * oid = poa->activate_object( logger_i_.get() );
        logger_i_->oid( *oid );
    }

    CORBA::Object_var obj = poa->servant_to_reference( logger_i_.get() );
    try {
        return Broker::Logger::_narrow( obj );
    } catch ( CORBA::Exception& ) {
        return 0;
    }
}
Exemple #8
0
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  try
    {
      CORBA::ORB_var orb = CORBA::ORB_init (argc, argv);

      if (parse_args (argc, argv) != 0)
        return 1;

      MessageFactory::register_new_factory(* orb.in());

      CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
      PortableServer::POA_var poa = PortableServer::POA::_narrow(obj.in());

      PortableServer::POAManager_var poaman = poa->the_POAManager();

      PortableServer::Servant_var<Messenger_i> svt = new Messenger_i;

      PortableServer::ObjectId_var id = poa->activate_object(svt.in());
      obj = poa->id_to_reference(id.in());
      CORBA::String_var ior = orb->object_to_string(obj.in());
      write_ior(ior.in());

      std::cout << "Starting server." << std::endl;

      poaman->activate();

      orb->run();

      poa->destroy(true, true);
      orb->destroy();
    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception ("Exception caught:");
      return 1;
    }

  return 0;
}
int main(int argc, char* argv[])
{
  CORBA::ORB_var orb = CORBA::ORB_init(argc, argv, "");

  assert(argc > 1);

  std::string ior;
  {
    std::ifstream ifs(argv[1]);
    std::getline(ifs, ior);
  }

  CORBA::Object_var poa_obj = orb->resolve_initial_references ("RootPOA");
  PortableServer::POA_var poa = PortableServer::POA::_narrow (poa_obj);
  PortableServer::POAManager_var poa_manager = poa->the_POAManager();

  some_interface_impl some_interface(orb);
  PortableServer::ObjectId_var oid = poa->activate_object (&some_interface);
  CORBA::Object_var some_interface_obj_ref = poa->id_to_reference (oid.in());
  some_interface_ptr some_interface_ref = some_interface::_narrow(some_interface_obj_ref);

  CORBA::Object_var obj = orb->string_to_object (ior.c_str());
  some_other_interface_var some_other_interface_ = some_other_interface::_narrow (obj);

  poa_manager->activate();

  boost::thread orb_thread(boost::bind(&run_orb, orb));
  
  some_other_interface_->foo1(some_interface_ref);
  some_other_interface_->foo2(some_interface_ref);
  some_other_interface_->foo3(some_interface_ref);
  some_interface_ref = some_other_interface_->foo4();

  std::cout << "All functions called" << std::endl;

  orb_thread.join();

  assert(some_interface.foo_ == 4);

  std::cout << "Finished" << std::endl;
}
Exemple #10
0
void OmniORBThread::run()
{
  try {
    CORBA::ORB_var orb = CORBA::ORB_init(_argc, _argv);

    CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
    PortableServer::POA_var poa = PortableServer::POA::_narrow(obj);

    Echo_i* myecho = new Echo_i();
      
    PortableServer::ObjectId_var myechoid = poa->activate_object(myecho);

    // Obtain a reference to the object, and print it out as a
    // stringified IOR.
    obj = myecho->_this();
    CORBA::String_var sior(orb->object_to_string(obj));
    cout << (char*)sior << endl;

    myecho->_remove_ref();

    PortableServer::POAManager_var pman = poa->the_POAManager();
    pman->activate();

    orb->run();
  }
  catch(CORBA::SystemException& ex) {
    cerr << "Caught CORBA::" << ex._name() << endl;
  }
  catch(CORBA::Exception& ex) {
    cerr << "Caught CORBA::Exception: " << ex._name() << endl;
  }
  catch(omniORB::fatalException& fe) {
    cerr << "Caught omniORB::fatalException:" << endl;
    cerr << "  file: " << fe.file() << endl;
    cerr << "  line: " << fe.line() << endl;
    cerr << "  mesg: " << fe.errmsg() << endl;
  }

  //emit finished();
}
Exemple #11
0
CORBA::Object_ptr
TAO_Monitor_Init::create_object (CORBA::ORB_ptr orb,
                                 int,
                                 ACE_TCHAR *[])
{
  try
    {
      CORBA::Object_var obj =
        orb->resolve_initial_references ("RootPOA");

      PortableServer::POA_var poa =
        PortableServer::POA::_narrow (obj.in ());

      PortableServer::POAManager_var mgr =
        poa->the_POAManager ();

      mgr->activate ();

      Monitor_Impl *servant = 0;
      ACE_NEW_RETURN (servant,
                      Monitor_Impl (orb),
                      CORBA::Object::_nil ());

      PortableServer::ObjectId_var id =
        poa->activate_object (servant);

      PortableServer::ServantBase_var safe_servant = servant;
      obj = servant->_this ();

      return obj._retn ();
    }
  catch (const CORBA::Exception&)
    {
    }

  return CORBA::Object::_nil ();
}
    int
    run() override final
    {
        OrbHelper orb(executable_name_);

        CORBA::Object_var obj = orb.orb()->resolve_initial_references("RootPOA");

        PortableServer::POA_var poa = PortableServer::POA::_narrow(obj);

        POA_youtils_test::corba_test_tie<CorbaYoutilsServant>
        corba_youtils_servant(new CorbaYoutilsServant(orb));

        PortableServer::ObjectId_var corba_youtils_servant_id =
            poa->activate_object(&corba_youtils_servant);

        CORBA::Object_var obj1;

        obj1  = corba_youtils_servant._this();
        orb.bindObjectToName(obj1,
                             "context_name",
                             "context_kind",
                             "object_name",
                             "object_kind");


        PortableServer::POAManager_var pman = poa->the_POAManager();
        pman->activate();


        omni_thread::sleep(1);
        orb.orb()->run();

        poa->deactivate_object(corba_youtils_servant_id);

        return 0;
    }
Exemple #13
0
int TestTask::svc()
{

  try {
    // Start the Naming Service tasks
    namingServiceA_.activate();
    // Wait for the Naming Service initialized.
    namingServiceA_.waitInit();

    namingServiceB_.activate();
    // Wait for the Naming Service initialized.
    namingServiceB_.waitInit();

    FILE *output_file= ACE_OS::fopen (ior_output_file, "w");
    if (output_file == 0)
      ACE_ERROR_RETURN ((LM_ERROR,
                          "Cannot open output file for writing IOR: ns.ior\n"),
                          1);
    ACE_OS::fprintf (output_file, "%s", namingServiceA_.ior ());
    ACE_OS::fclose (output_file);

    // Get reference to Root POA
    CORBA::Object_var obj = orb_->resolve_initial_references("RootPOA");
    PortableServer::POA_var poa = PortableServer::POA::_narrow(obj.in());

    // Activate POA Manager
    PortableServer::POAManager_var mgr = poa->the_POAManager();
    mgr->activate();

    // Find the Naming Service
    obj = orb_->string_to_object (namingServiceB_.ior ());
    CosNaming::NamingContext_var root =
      CosNaming::NamingContext::_narrow(obj.in());

    if (CORBA::is_nil(root.in())) {
      ACE_ERROR ((LM_ERROR, "Error, Nil Naming Context reference\n"));
      return 1;
    }
    // Bind the example Naming Context, if necessary
    CosNaming::NamingContext_var example_nc;
    CosNaming::Name name;
    name.length(1);
    name[0].id = CORBA::string_dup("example");
    try
    {
      obj = root->resolve(name);
      example_nc = CosNaming::NamingContext::_narrow(obj.in());
    }
    catch (const CosNaming::NamingContext::NotFound&)
    {
      example_nc = root->bind_new_context(name);
    }

    // Bind the Test object
    name.length(2);
    name[1].id = CORBA::string_dup("Hello");

    // Create an object
    Hello servant(orb_.in ());
    PortableServer::ObjectId_var oid = poa->activate_object(&servant);
    obj = poa->id_to_reference(oid.in());
    root->rebind(name, obj.in());

    ACE_DEBUG ((LM_INFO, "Hello object bound in Naming Service B\n"));

    name.length(1);
    obj = orb_->string_to_object (namingServiceA_.ior ());
    root = CosNaming::NamingContext::_narrow(obj.in());
    root->bind_context (name, example_nc.in ());

    ACE_DEBUG ((LM_INFO, "'example' context of NS B bound in Naming Service A\n"));

    if (shutdown_ns_)
    {
      namingServiceB_.end();

      ACE_DEBUG ((LM_INFO, "Naming Service B shut down\n"));
    }

    // Create shutdown server
    NsShutdown shutdown_servant(orb_.in ());
    PortableServer::ObjectId_var shutdown_oid = poa->activate_object(&shutdown_servant);
    obj = poa->id_to_reference(shutdown_oid.in());
    CORBA::String_var ior = orb_->object_to_string (obj.in ());

    output_file= ACE_OS::fopen (ior_shutdown_file, "w");
    if (output_file == 0)
      ACE_ERROR_RETURN ((LM_ERROR,
                          "Cannot open output file %s for writing IOR: %C\n",
                          ior_shutdown_file,
                          ior.in ()),
                          1);
    ACE_OS::fprintf (output_file, "%s", ior.in ());
    ACE_OS::fclose (output_file);

    // Normally we run the orb and the orb is shutdown by
    // calling TestTask::end().
    // Accept requests
    orb_->run();
    orb_->destroy();

    // Shutdown the Naming Services.
    namingServiceA_.end();
    if (!shutdown_ns_)
      {
        namingServiceB_.end();
      }

    return 0;
  }
  catch (CORBA::Exception& ex)
  {
    ex._tao_print_exception ("CORBA exception: ");
  }

  return -1;
}
Exemple #14
0
int main(int argc, char *argv[])
{
    int wsize=0;
    double maxEdgeLen=0.0;
    bool useDefaultLights=true;
    float bgColor[3]={0,0,0};
    
    for (int i=1; i<argc; i++){
        if (strcmp(argv[i], "-size")==0){
            wsize = atoi(argv[++i]);
        }else if(strcmp(argv[i], "-max-edge-length")==0){
            maxEdgeLen = atof(argv[++i]);
        }else if(strcmp(argv[i], "-no-default-lights")==0){
            useDefaultLights=false;
        }else if(strcmp(argv[i], "-bg")==0){
            bgColor[0] = atof(argv[++i]);
            bgColor[1] = atof(argv[++i]);
            bgColor[2] = atof(argv[++i]);
        }else if(strcmp(argv[i], "-h")==0 || strcmp(argv[i], "--help")==0){
            print_usage(argv[0]);
            return 1;
        }
    }
    
    CORBA::ORB_var orb = CORBA::ORB::_nil();
    
    try {
        
        orb = CORBA::ORB_init(argc, argv);
        
        CORBA::Object_var obj;
        
        obj = orb->resolve_initial_references("RootPOA");
        PortableServer::POA_var poa = PortableServer::POA::_narrow(obj);
        if(CORBA::is_nil(poa)){
            throw std::string("error: failed to narrow root POA.");
        }
        
        PortableServer::POAManager_var poaManager = poa->the_POAManager();
        if(CORBA::is_nil(poaManager)){
            throw std::string("error: failed to narrow root POA manager.");
        }
        
        LogManager<OpenHRP::WorldState> log;
        GLscene scene(&log);
        scene.setBackGroundColor(bgColor);
        scene.maxEdgeLen(maxEdgeLen);
        
        OnlineViewer_impl* OnlineViewerImpl 
            = new OnlineViewer_impl(orb, poa, &scene, &log);
        poa->activate_object(OnlineViewerImpl);
        OnlineViewer_var OnlineViewer = OnlineViewerImpl->_this();
        OnlineViewerImpl->_remove_ref();
        
        obj = orb->resolve_initial_references("NameService");
        CosNaming::NamingContext_var namingContext = CosNaming::NamingContext::_narrow(obj);
        if(CORBA::is_nil(namingContext)){
            throw std::string("error: failed to narrow naming context.");
        }
        
        CosNaming::Name name;
        name.length(1);
        name[0].id = CORBA::string_dup("OnlineViewer");
        name[0].kind = CORBA::string_dup("");
        namingContext->rebind(name, OnlineViewer);

        poaManager->activate();
        
        if (argc >= 2 && argv[1][0] != '-'){
            OpenHRP::ModelLoader_var ml = hrp::getModelLoader(namingContext);
            if (CORBA::is_nil(ml)){
                std::cerr << "openhrp-model-loader is not running" << std::endl;
                return 1;
            }
            OpenHRP::ModelLoader::ModelLoadOption opt;
            opt.readImage = true;
            opt.AABBdata.length(0);
            opt.AABBtype = OpenHRP::ModelLoader::AABB_NUM;
            GLbody *glbody = new GLbody();
            std::string url = argv[1];
            if (argv[1][0] != '/'){
                char buf[MAXPATHLEN];
                std::string cwd = getcwd(buf, MAXPATHLEN);
                url = cwd + '/' + url;
            }
            hrp::BodyPtr body(glbody);
            body->setName("model");
            OpenHRP::BodyInfo_var binfo = ml->getBodyInfoEx(url.c_str(), opt);
            hrp::loadBodyFromBodyInfo(body, binfo, false, GLlinkFactory);
            loadShapeFromBodyInfo(glbody, binfo);
            scene.addBody(body);
        }
        
        GLlink::useAbsTransformToDraw();
        GLbody::useAbsTransformToDraw();

        SDLwindow window(&scene, &log);
        window.init(wsize, wsize);
        if (!useDefaultLights) scene.defaultLights(false);
        
        while(window.oneStep());
        
    }
    catch(OpenHRP::ModelLoader::ModelLoaderException ex){
        std::cerr << ex.description << std::endl;
    }
    catch (CORBA::SystemException& ex) {
        std::cerr << ex._rep_id() << std::endl;
    }
    catch (const std::string& error){
        std::cerr << error << std::endl;
    }
    
    try {
        orb->destroy();
    }
    catch(...){
        
    }
    
    return 0;
}
Exemple #15
0
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  try
  {
    // Initialize the ORB.
    CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);

    const ACE_TCHAR *ecname = ACE_TEXT ("EventService");
    for (int i = 0; argv[i] != 0; i++) {
      if (ACE_OS::strcmp(argv[i], ACE_TEXT("-ecname")) == 0) {
        if (argv[i+1] != 0) {
          ecname = argv[i+1];
        } else {
          std::cerr << "Missing Event channel name" << std::endl;
        }
      }
    }

    // Find the Naming Service.
    CORBA::Object_var obj = orb->resolve_initial_references("NameService");
    CosNaming::NamingContextExt_var root_context
      = CosNaming::NamingContextExt::_narrow(obj.in());

    // Find the EchoEventChannel.
    obj = root_context->resolve_str (ACE_TEXT_ALWAYS_CHAR (ecname));

    // Downcast the object reference to an EventChannel reference.
    RtecEventChannelAdmin::EventChannel_var ec =
      RtecEventChannelAdmin::EventChannel::_narrow(obj.in());
    if (CORBA::is_nil(ec.in())) {
      std::cerr << "Could not narrow EchoEventChannel." << std::endl;
      return 1;
    }
    std::cout << "EchoEventConsumerMain.cpp: Found the EchoEventChannel." << std::endl;

    // Obtain a reference to the consumer administration object.
    RtecEventChannelAdmin::ConsumerAdmin_var admin = ec->for_consumers();

    // Obtain a reference to the push supplier proxy.
    RtecEventChannelAdmin::ProxyPushSupplier_var supplier =
      admin->obtain_push_supplier();

    // Get the RootPOA.
    obj = orb->resolve_initial_references("RootPOA");
    PortableServer::POA_var poa = PortableServer::POA::_narrow(obj.in());

    // Instantiate an EchoEventConsumer_i servant and register it
    // with the RootPOA
    PortableServer::Servant_var<EchoEventConsumer_i> servant =
      new EchoEventConsumer_i(orb.in(), supplier.in(), EVENT_LIMIT);
    PortableServer::ObjectId_var oid = poa->activate_object(servant.in());
    CORBA::Object_var consumer_obj = poa->id_to_reference(oid.in());
    RtecEventComm::PushConsumer_var consumer =
      RtecEventComm::PushConsumer::_narrow(consumer_obj.in());

    // Connect as a consumer.
    ACE_ConsumerQOS_Factory qos;
    qos.start_disjunction_group ();
    qos.insert (MY_SOURCE_ID,   // Source ID
                MY_EVENT_TYPE,  // Event Type
                0);             // handle to the rt_info
    supplier->connect_push_consumer (consumer.in (),
                                     qos.get_ConsumerQOS ());

    // Activate the POA via its POAManager.
    PortableServer::POAManager_var poa_manager = poa->the_POAManager();
    poa_manager->activate();

    std::cout << "EchoEventConsumerMain.cpp: Ready to receive events..." << std::endl;

    // Enter the ORB event loop.
    orb->run();

    // If we have reached this, we must be shutting down...
    // Disconnect the ProxyPushSupplier.
    orb->destroy();

    std::cout << "Test completed." << std::endl;

    return 0;
  }
  catch(const CORBA::Exception& exc)
  {
    std::cerr << "Caught CORBA::Exception" << std::endl << exc << std::endl;
  }
  return 1;
}
Exemple #16
0
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  try
  {
    // Initialize the EC Factory so we can customize the EC
    TAO_EC_Default_Factory::init_svcs ();

    // Initialize the ORB.
    CORBA::ORB_var orb = CORBA::ORB_init (argc, argv);

    const ACE_TCHAR *ecname = ACE_TEXT ("EventService");
    const ACE_TCHAR *address = ACE_TEXT ("localhost");
    const ACE_TCHAR *iorfile = 0;
    u_short port = 12345;
    u_short listenport = 12345;

    int mcast = 1;

    for (int i = 0; argv[i] != 0; i++)
      {
        if (ACE_OS::strcasecmp(argv[i], ACE_TEXT ("-ecname")) == 0)
          {
            if (argv[i+1] != 0)
                ecname = argv[++i];
            else
              ACE_ERROR_RETURN ((LM_ERROR,  "Missing Event channel name\n"),0);
          }
        else if (ACE_OS::strcasecmp(argv[i], ACE_TEXT ("-address")) == 0)
          {
            if (argv[i+1] != 0)
              address = argv[++i];
            else
              ACE_ERROR_RETURN ((LM_ERROR, "Missing address\n"),0);
          }
        else if (ACE_OS::strcasecmp(argv[i], ACE_TEXT ("-port")) == 0)
          {
            if (argv[i+1] != 0)
              port = ACE_OS::atoi(argv[++i]);
            else
              ACE_ERROR_RETURN ((LM_ERROR, "Missing port\n"),0);
          }
        else if (ACE_OS::strcasecmp(argv[i], ACE_TEXT ("-listenport")) == 0)
          {
            if (argv[i+1] != 0)
              listenport = ACE_OS::atoi(argv[++i]);
            else
              ACE_ERROR_RETURN ((LM_ERROR, "Missing port\n"), 0);
          }
        else if (ACE_OS::strcasecmp(argv[i], ACE_TEXT ("-iorfile")) == 0)
          {
            if (argv[i+1] != 0)
              iorfile = argv[++i];
             else
              ACE_ERROR_RETURN ((LM_ERROR, "Missing ior file\n"), 0);
          }
        else if (ACE_OS::strcasecmp(argv[i], ACE_TEXT ("-udp")) == 0)
          mcast = 0;
      }

    // Get the POA
    CORBA::Object_var tmpobj = orb->resolve_initial_references ("RootPOA");
    PortableServer::POA_var poa = PortableServer::POA::_narrow (tmpobj.in ());
    PortableServer::POAManager_var poa_manager = poa->the_POAManager ();
    poa_manager->activate ();

    // Create a local event channel and register it
    TAO_EC_Event_Channel_Attributes attributes (poa.in (), poa.in ());
    TAO_EC_Event_Channel ec_impl (attributes);
    ec_impl.activate ();
    PortableServer::ObjectId_var oid = poa->activate_object(&ec_impl);
    tmpobj = poa->id_to_reference(oid.in());
    RtecEventChannelAdmin::EventChannel_var ec =
      RtecEventChannelAdmin::EventChannel::_narrow(tmpobj.in());

    // Find the Naming Service.
    tmpobj = orb->resolve_initial_references("NameService");
    CosNaming::NamingContextExt_var root_context =
      CosNaming::NamingContextExt::_narrow(tmpobj.in());

    // Bind the Event Channel using Naming Services
    CosNaming::Name_var name =
      root_context->to_name (ACE_TEXT_ALWAYS_CHAR (ecname));
    root_context->rebind(name.in(), ec.in());

    // Get a proxy push consumer from the EventChannel.
    RtecEventChannelAdmin::SupplierAdmin_var admin = ec->for_suppliers();
    RtecEventChannelAdmin::ProxyPushConsumer_var consumer =
      admin->obtain_push_consumer();

    // Instantiate an EchoEventSupplier_i servant.
    EchoEventSupplier_i servant(orb.in());

    // Register it with the RootPOA.
    oid = poa->activate_object(&servant);
    tmpobj = poa->id_to_reference(oid.in());
    RtecEventComm::PushSupplier_var supplier =
      RtecEventComm::PushSupplier::_narrow(tmpobj.in());

    // Connect to the EC.
    ACE_SupplierQOS_Factory qos;
    qos.insert (MY_SOURCE_ID, MY_EVENT_TYPE, 0, 1);
    consumer->connect_push_supplier (supplier.in (), qos.get_SupplierQOS ());

    // Initialize the address server with the desired address. This will
    // be used by the sender object and the multicast receiver only if
    // one is not otherwise available via the naming service.
    ACE_INET_Addr send_addr (port, address);
    SimpleAddressServer addr_srv_impl (send_addr);

    // Create an instance of the addr server for local use

    PortableServer::ObjectId_var addr_srv_oid =
      poa->activate_object(&addr_srv_impl);
    tmpobj =
      poa->id_to_reference(addr_srv_oid.in());

    RtecUDPAdmin::AddrServer_var addr_srv =
      RtecUDPAdmin::AddrServer::_narrow(tmpobj.in());

    // Create and initialize the sender object
    PortableServer::Servant_var<TAO_ECG_UDP_Sender> sender =
                                TAO_ECG_UDP_Sender::create();
    TAO_ECG_UDP_Out_Endpoint endpoint;
    // need to be explicit about the address type when built with
    // IPv6 support, otherwise SOCK_DGram::open defaults to ipv6 when
    // given a sap_any address. This causes trouble on at least solaris
    // and windows, or at most on not-linux.
    if (endpoint.dgram ().open (ACE_Addr::sap_any,
                                send_addr.get_type()) == -1)
      {
        ACE_ERROR_RETURN ((LM_ERROR,
                           "Cannot open send endpoint\n"),
                          1);
      }

   // TAO_ECG_UDP_Sender::init() takes a TAO_ECG_Refcounted_Endpoint.
    // If we don't clone our endpoint and pass &endpoint, the sender will
    // attempt to delete endpoint during shutdown.
    TAO_ECG_Refcounted_Endpoint clone (new TAO_ECG_UDP_Out_Endpoint (endpoint));
    sender->init (ec.in (), addr_srv.in (), clone);

    // Setup the subscription and connect to the EC
    ACE_ConsumerQOS_Factory cons_qos_fact;
    cons_qos_fact.start_disjunction_group ();
    cons_qos_fact.insert (ACE_ES_EVENT_SOURCE_ANY, ACE_ES_EVENT_ANY, 0);
    RtecEventChannelAdmin::ConsumerQOS sub = cons_qos_fact.get_ConsumerQOS ();
    sender->connect (sub);

    // Create and initialize the receiver
    PortableServer::Servant_var<TAO_ECG_UDP_Receiver> receiver =
                                      TAO_ECG_UDP_Receiver::create();

    // TAO_ECG_UDP_Receiver::init() takes a TAO_ECG_Refcounted_Endpoint.
    // If we don't clone our endpoint and pass &endpoint, the receiver will
    // attempt to delete endpoint during shutdown.
    TAO_ECG_Refcounted_Endpoint clone2 (new TAO_ECG_UDP_Out_Endpoint (endpoint));
    receiver->init (ec.in (), clone2, addr_srv.in ());

    // Setup the registration and connect to the event channel
    ACE_SupplierQOS_Factory supp_qos_fact;
    supp_qos_fact.insert (MY_SOURCE_ID, MY_EVENT_TYPE, 0, 1);
    RtecEventChannelAdmin::SupplierQOS pub = supp_qos_fact.get_SupplierQOS ();
    receiver->connect (pub);

    // Create the appropriate event handler and register it with the reactor
    auto_ptr<ACE_Event_Handler> eh;
    if (mcast) {
      auto_ptr<TAO_ECG_Mcast_EH> mcast_eh(new TAO_ECG_Mcast_EH (receiver.in()));
      mcast_eh->reactor (orb->orb_core ()->reactor ());
      mcast_eh->open (ec.in());
      ACE_auto_ptr_reset(eh,mcast_eh.release());
      //eh.reset(mcast_eh.release());
    } else {
      auto_ptr<TAO_ECG_UDP_EH> udp_eh (new TAO_ECG_UDP_EH (receiver.in()));
      udp_eh->reactor (orb->orb_core ()->reactor ());
      ACE_INET_Addr local_addr (listenport);
      if (udp_eh->open (local_addr) == -1)
        ACE_ERROR ((LM_ERROR,"Cannot open EH\n"));

      ACE_auto_ptr_reset(eh,udp_eh.release());
      //eh.reset(udp_eh.release());
    }

    // Create an event (just a string in this case).

    // Create an event set for one event
    RtecEventComm::EventSet event (1);
    event.length (1);

    // Initialize event header.
    event[0].header.source = MY_SOURCE_ID;
    event[0].header.ttl = 1;
    event[0].header.type = MY_EVENT_TYPE;

#if !defined (TAO_LACKS_EVENT_CHANNEL_ANY)
    // Initialize data fields in event.
    const CORBA::String_var eventData =
      CORBA::string_dup (ACE_TEXT_ALWAYS_CHAR (ecname));

    event[0].data.any_value <<= eventData;
#else
    // Use the octet sequence payload instead
    char *tmpstr = const_cast<char *>(ACE_TEXT_ALWAYS_CHAR (ecname));
    size_t len = ACE_OS::strlen(tmpstr) +1;
    event[0].data.payload.replace (
      len,
      len,
      reinterpret_cast<CORBA::Octet *> (tmpstr));
#endif  /* !TAO_LACKS_EVENT_CHANNEL_ANY */

    if (iorfile != 0) {
      CORBA::String_var str = orb->object_to_string( ec.in() );
      std::ofstream iorFile( ACE_TEXT_ALWAYS_CHAR(iorfile) );
      iorFile << str.in() << std::endl;
      iorFile.close();
    }
    ACE_DEBUG ((LM_DEBUG,
    "Starting main loop\n"));

    const int EVENT_DELAY_MS = 1000;

    while (1) {
      consumer->push (event);

      ACE_Time_Value tv(0, 1000 * EVENT_DELAY_MS);
      orb->run(tv);
    }

    orb->destroy();
    return 0;
  }
  catch (const CORBA::Exception& exc)
  {
    ACE_ERROR ((LM_ERROR,
    "Caught CORBA::Exception\n%C (%C)\n",
    exc._name (),
    exc._rep_id () ));
  }
  return 1;
}
Exemple #17
0
int ACE_TMAIN (int argc, ACE_TCHAR* argv[])
{
  try
    {
      // First initialize the ORB, that will remove some arguments...
      CORBA::ORB_var orb =
        CORBA::ORB_init (argc, argv);

      if (argc < 2)
        {
          ACE_DEBUG ((LM_DEBUG, "\nUsage:\n  %s [NAME to insert in Naming Service]\n", argv[0]));
          return -1;
        }
      // Get a reference to the RootPOA
      CORBA::Object_var poa_object =
        orb->resolve_initial_references ("RootPOA");

      // narrow down to the correct reference
      PortableServer::POA_var poa =
        PortableServer::POA::_narrow (poa_object.in ());

      // Set a POA Manager
      PortableServer::POAManager_var poa_manager =
        poa->the_POAManager ();

      // Activate the POA Manager
      poa_manager->activate ();

      // Create the servant
      corbaloc_Status_i status_i;
      status_i.set_name (ACE_TEXT_ALWAYS_CHAR (argv[1]));
      // Activate it to obtain the reference
      PortableServer::ObjectId_var id =
        poa->activate_object (&status_i);

      CORBA::Object_var object = poa->id_to_reference (id.in ());

      corbaloc::Status_var status =
        corbaloc::Status::_narrow (object.in ());

      // Get a reference to Naming Context
      CORBA::Object_var naming_context_object =
        orb->resolve_initial_references ("NameService");

      // Narrow down the reference
      CosNaming::NamingContext_var naming_context =
        CosNaming::NamingContext::_narrow (naming_context_object.in ());

      // Bind Iterator_Factory to the Naming Context
      CosNaming::Name name (1);
      name.length (1);
      name[0].id = CORBA::string_dup (ACE_TEXT_ALWAYS_CHAR (argv[1]));

      naming_context->rebind (name, status.in ());

      // Run the orb
      orb->run ();

      // Destroy the POA, waiting until the destruction terminates
      poa->destroy (1, 1);
      orb->destroy ();
    }
  catch (const CORBA::SystemException& ex){
    ex._tao_print_exception ("CORBA exception raised! ");
  }
  catch (const CORBA::Exception& ex){
    ex._tao_print_exception ("Exception caught in server");
  }

  return 0;
}
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
    try {
        // Initialize the ORB.
        CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);

        // Create a MessengerServer object.
        MessengerServer * server = new MessengerServer (orb.in());
        ACE_Auto_Ptr<MessengerServer> safe_ptr (server);

        // Parse arguments to determine how we should shutdown.
        if (server->parse_args (argc, argv) != 0)
            return 1;

        //Get reference to the RootPOA.
        CORBA::Object_var obj = orb->resolve_initial_references( "RootPOA" );
        PortableServer::POA_var poa = PortableServer::POA::_narrow( obj.in() );

        // Activate the POAManager.
        PortableServer::POAManager_var mgr = poa->the_POAManager();
        mgr->activate();

        // Create a servant.
        Messenger_i messenger_servant (orb.in());

        // Register the servant with the RootPOA, obtain its object
        // reference, stringify it, and write it to a file.
        PortableServer::ObjectId_var oid =
            poa->activate_object( &messenger_servant );
        CORBA::Object_var messenger_obj = poa->id_to_reference( oid.in() );
        CORBA::String_var str = orb->object_to_string( messenger_obj.in() );
        std::ofstream iorFile(ACE_TEXT_ALWAYS_CHAR (ior_output_file.c_str ()));
        iorFile << str.in() << std::endl;
        iorFile.close();
        std::cout << "IOR written to file " <<
                  ACE_TEXT_ALWAYS_CHAR (ior_output_file.c_str ()) << std::endl;

        switch (s_method)
        {
        // shutdown on client invocation
        case MessengerServer::s_client_call:
            std::cout << "Will shutdown on client invocation." << std::endl;
            server->run ();
            break;

        // shutdown after some iterations through loop
        case MessengerServer::s_polling_loop:
            server->poll (loop_iterations);
            break;

        // schedule a timer to shutdown
        case MessengerServer::s_timer:
            server->schedule_shutdown_timer (timeout);
            server->run ();
            break;

        // shutdown on console input
        case MessengerServer::s_console_input:
            server->shutdown_on_console_input ();
            server->run ();
            break;

        // use CORBA::ORB::run() with time value
        case MessengerServer::s_run_time_value:
            server->run (timeout);
            break;
        }
    }
    catch(const CORBA::Exception& ex) {
        std::cerr << "CORBA exception: " << ex << std::endl;
        return 1;
    }

    return 0;
}
int main(int argc, char **argv)
{
    // Removes ORB related arguments
    CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);

    // Program options
    std::string register_servant;
    std::string proxy_reference;

    _po::options_description _desc("Proxy Server options");
    _desc.add_options()
        ("help,h", "produce help message")
        ("register-servant,r", _po::value< std::string >(&register_servant),
         "register the servant into the name service")
        ("proxy-reference,p", _po::value< std::string >(&proxy_reference),
         "forward received calls to another servant");

    _po::variables_map _vm;
    _po::store(_po::parse_command_line(argc, argv, _desc), _vm);
    _po::notify(_vm);

    if (_vm.count("help"))
    {
        std::cout << _desc << std::endl;
        return 0;
    }

    bool reference_is_ns_entry = false;
    // TODO

    // Name Service
    CosNaming::NamingContextExt_var nc;

    if (reference_is_ns_entry || !register_servant.empty())
    {
        try {
            CORBA::Object_var ncObj = orb->resolve_initial_references("NameService");

            nc = CosNaming::NamingContextExt::_narrow(ncObj);
        } catch(...) {
        }

        if (CORBA::is_nil(nc))
            std::cerr << "Name service unavailable!" << std::endl;
    }

    // Proxy reference
    prueba::Iface_var reference;

    if (!proxy_reference.empty())
    {
        CORBA::Object_var refObj;

        if (reference_is_ns_entry && !CORBA::is_nil(nc))
            refObj = nc->resolve_str(proxy_reference.c_str());
        else
            refObj = orb->string_to_object(proxy_reference.c_str());

        reference = prueba::Iface::_narrow(refObj);
    }

    // Servant
    prueba_Iface_impl _impl(reference.in());

    CORBA::Object_var rootPOAObj =
            orb->resolve_initial_references("RootPOA");

    PortableServer::POA_var rootPOA =
            PortableServer::POA::_narrow(rootPOAObj.in());

    PortableServer::POAManager_var manager = rootPOA->the_POAManager();

    PortableServer::ObjectId_var myObjID =
                rootPOA->activate_object(&_impl);

    CORBA::Object_var obj = rootPOA->servant_to_reference(&_impl);

    // Displaying reference
    CORBA::String_var ref = orb->object_to_string(obj);
    std::cout << ref << std::endl;

    // Registring servant
    CosNaming::Name_var name;

    if (!register_servant.empty() && !CORBA::is_nil(nc))
    {
        name = nc->to_name(register_servant.c_str());

        nc->rebind(name, obj);
    }

    /*PROTECTED REGION ID(prueba_Iface_impl_server::___main) ENABLED START*/
    /*PROTECTED REGION END*/

    // Running
    manager->activate();
    orb->run();

    // Unbinding servant
    if (!CORBA::is_nil(nc) && name)
        nc->unbind(name);

    return 0;
}
Exemple #20
0
int main(int argc, char* argv[])
{
    
    CORBA::ORB_var orb = CORBA::ORB::_nil();
  
    try {

	orb = CORBA::ORB_init(argc, argv);
	
	CORBA::Object_var obj;
	
	obj = orb->resolve_initial_references("RootPOA");
	PortableServer::POA_var poa = PortableServer::POA::_narrow(obj);
	if(CORBA::is_nil(poa)){
	    throw string("error: failed to narrow root POA.");
	}
	
	PortableServer::POAManager_var poaManager = poa->the_POAManager();
	if(CORBA::is_nil(poaManager)){
	    throw string("error: failed to narrow root POA manager.");
	}
	
	ModelLoader_impl* modelLoaderImpl = new ModelLoader_impl(orb, poa);
	poa->activate_object(modelLoaderImpl);
	ModelLoader_var modelLoader = modelLoaderImpl->_this();
	modelLoaderImpl->_remove_ref();

	obj = orb->resolve_initial_references("NameService");
	CosNaming::NamingContext_var namingContext = CosNaming::NamingContext::_narrow(obj);
	if(CORBA::is_nil(namingContext)){
	    throw string("error: failed to narrow naming context.");
	}
	
	CosNaming::Name name;
	name.length(1);
	name[0].id = CORBA::string_dup("ModelLoader");
	name[0].kind = CORBA::string_dup("");
	namingContext->rebind(name, modelLoader);

	poaManager->activate();
	
	cout << "ready" << endl;

	orb->run();

    }
    catch (CORBA::SystemException& ex) {
	cerr << ex._rep_id() << endl;
    }
    catch (const string& error){
	cerr << error << endl;
    }

    try {
	orb->destroy();
    }
    catch(...){

    }
    
    return 0;
}
int main (int argc, char* argv[])
{
  try
  {
    // Initialize the ORB.
    CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);

    // Find the Naming Service.
    CORBA::Object_var obj = orb->resolve_initial_references("NameService");
    CosNaming::NamingContextExt_var naming_client = CosNaming::NamingContextExt::_narrow(obj.in());

    // Get the Event Channel using Naming Services
    obj = naming_client->resolve_str("EventService");

    // Downcast the object reference to an EventChannel reference.
    RtecEventChannelAdmin::EventChannel_var ec =
      RtecEventChannelAdmin::EventChannel::_narrow(obj.in());
    if (CORBA::is_nil(ec.in())) {
      cerr << "Could not resolve EchoEventChannel." << endl;
      return 1;
    }

    // Get a SupplierAdmin object from the EventChannel.
    RtecEventChannelAdmin::SupplierAdmin_var admin = ec->for_suppliers();

    // Get a ProxyPushConsumer from the SupplierAdmin.
    RtecEventChannelAdmin::ProxyPushConsumer_var consumer =
                                        admin->obtain_push_consumer();

    // Get the RootPOA.
    obj = orb->resolve_initial_references("RootPOA");
    PortableServer::POA_var poa = PortableServer::POA::_narrow(obj.in());

    // Instantiate an EchoEventConsumer_i servant.
    EchoEventSupplier_i servant(orb.in());

    // Register it with the RootPOA.
    PortableServer::ObjectId_var oid = poa->activate_object(&servant);
    CORBA::Object_var supplier_obj = poa->id_to_reference(oid.in());
    RtecEventComm::PushSupplier_var supplier =
      RtecEventComm::PushSupplier::_narrow(supplier_obj.in());

    // Publish the events the supplier provides.
    ACE_SupplierQOS_Factory qos;
    qos.insert (MY_SOURCE_ID,      // Supplier's unique id
                MY_EVENT_TYPE,     // Event type
                0,                 // handle to the rt_info structure
                1);                // number of calls

    // Connect as a supplier of the published events.
    consumer->connect_push_supplier (supplier.in (),
                                     qos.get_SupplierQOS ());

    // Activate the POA via its POAManager.
    PortableServer::POAManager_var poa_manager = poa->the_POAManager();
    poa_manager->activate();

    // Create an event (just a string in this case).
    const CORBA::String_var eventData = CORBA::string_dup("Hello, world.");

    // Create an event set for one event
    RtecEventComm::EventSet events (1);
    events.length (1);

    // Initialize event header.
    events[0].header.source = MY_SOURCE_ID;
    events[0].header.type = MY_EVENT_TYPE;

    // Initialize data fields in event.
    events[0].data.any_value <<= eventData;
    
    cout << "Supplier starting sending of events" << endl;

    while (1) {
      consumer->push (events);
      ACE_Time_Value tv(0, 1000 * EVENT_DELAY_MS);
      orb->run(tv);
    }

    orb->destroy();

    return 0;
  }
  catch (CORBA::Exception& ex) 
  {
    cerr << "Supplier::main() Caught CORBA::Exception" << endl << ex << endl;
  }

  return 1;
}
Exemple #22
0
int
create_POA_and_register_servant (CORBA::Policy_ptr threadpool_policy,
                                 const char *poa_name,
                                 PortableServer::POAManager_ptr poa_manager,
                                 PortableServer::POA_ptr root_poa,
                                 CORBA::ORB_ptr orb,
                                 RTCORBA::RTORB_ptr rt_orb)
{
  // Policies for the firstPOA to be created.
  CORBA::PolicyList policies (3); policies.length (3);

  // Implicit_activation policy.
  policies[0] =
    root_poa->create_implicit_activation_policy
    (PortableServer::IMPLICIT_ACTIVATION);

  // Thread pool policy.
  policies[1] =
    CORBA::Policy::_duplicate (threadpool_policy);

  // Priority Model policy.
  policies[2] =
    rt_orb->create_priority_model_policy (RTCORBA::CLIENT_PROPAGATED,
                                          0);

  // Create the POA under the RootPOA.
  PortableServer::POA_var poa =
    root_poa->create_POA (poa_name,
                          poa_manager,
                          policies);

  // Creation of POAs is over. Destroy the Policy objects.
  for (CORBA::ULong i = 0;
       i < policies.length ();
       ++i)
    {
      policies[i]->destroy ();
    }

  test_i *servant =
    new test_i (orb,
                poa.in (),
                nap_time);

  PortableServer::ServantBase_var safe_servant (servant);
  ACE_UNUSED_ARG (safe_servant);

  PortableServer::ObjectId_var id =
    poa->activate_object (servant);

  CORBA::Object_var object = poa->id_to_reference (id.in ());

  test_var test =
    test::_narrow (object.in ());

  int result =
    write_ior_to_file (orb,
                       test.in ());

  return result;
}
Exemple #23
0
int TestTask::svc()
{

  try {
    // Get reference to Root POA
    CORBA::Object_var obj = orb_->resolve_initial_references ("RootPOA");

    PortableServer::POA_var poa = PortableServer::POA::_narrow (obj.in ());

    // Activate POA Manager
    PortableServer::POAManager_var mgr = poa->the_POAManager ();
    mgr->activate ();

    // Find the Naming Service
    obj = orb_->string_to_object (
      "corbaloc:iiop:1.2@localhost:9932/NameService");

    CosNaming::NamingContext_var rootB =
      CosNaming::NamingContext::_narrow (obj.in ());

    if (CORBA::is_nil (rootB.in ())) {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Error, Nil Naming Context reference\n")));
      return 1;
    }
    // Bind the example Naming Context, if necessary
    CosNaming::NamingContext_var example_nc;
    CosNaming::Name name;
    name.length(1);
    name[0].id = CORBA::string_dup( "example");
    try
    {
      obj = rootB->resolve (name);
      example_nc =
        CosNaming::NamingContext::_narrow (obj.in ());
    }
    catch (const CosNaming::NamingContext::NotFound&)
    {
      example_nc = rootB->bind_new_context (name);
    }

    // Bind the Test object
    name.length (2);
    name[1].id = CORBA::string_dup ("Hello");

    // Create an object
    Hello servant (orb_.in ());
    PortableServer::ObjectId_var oid = poa->activate_object (&servant);
    obj = poa->id_to_reference (oid.in ());
    rootB->rebind (name, obj.in ());

    ACE_DEBUG ((LM_INFO,
                ACE_TEXT ("Hello object bound in Naming Service B\n")));

    name.length (1);
    name[0].id = CORBA::string_dup ("nsB");

    obj = orb_->string_to_object (
      "corbaloc:iiop:1.2@localhost:9931/NameService");

    CosNaming::NamingContext_var rootA =
      CosNaming::NamingContext::_narrow (obj.in ());

    rootA->bind_context (name, rootB.in ());

    ACE_DEBUG ((LM_INFO,
                ACE_TEXT ("Root context of NS B bound in Naming Service A ")
                ACE_TEXT ("under name 'nsB'\n")));

    CORBA::String_var ior =
      orb_->object_to_string (obj.in ());

    // Output the IOR to the <ior_output_file>
    FILE *output_file= ACE_OS::fopen (ior_output_file, "w");
    if (output_file == 0)
      ACE_ERROR_RETURN ((LM_ERROR,
                         ACE_TEXT ("Cannot open output file %s for writing ")
                         ACE_TEXT ("IOR: %C\n"),
                         ior_output_file,
                         ior.in ()),
                         1);
    ACE_OS::fprintf (output_file, ACE_TEXT ("%s"), ior.in ());
    ACE_OS::fclose (output_file);

    ACE_DEBUG ((LM_INFO,
                ACE_TEXT ("Wrote IOR file\n")));

    // Normally we run the orb and the orb is shutdown by
    // calling TestTask::end().
    // Accept requests
    orb_->run();
    orb_->destroy();

    return 0;
  }
  catch (CORBA::Exception& ex)
  {
    ex._tao_print_exception (ACE_TEXT ("CORBA exception: "));
  }

  return -1;
}
Exemple #24
0
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  try
  {
    CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);

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

    // Create a bidirectional POA
    CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
    PortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj.in());
    PortableServer::POAManager_var poa_manager = root_poa->the_POAManager();
    // Policies for the childPOA to be created.
    CORBA::PolicyList policies(1);
    policies.length(1);
    CORBA::Any pol;
    pol <<= BiDirPolicy::BOTH;
    policies[0] =
      orb->create_policy(BiDirPolicy::BIDIRECTIONAL_POLICY_TYPE, pol);
    // Create POA as child of RootPOA with the above policies.  This POA
    // will receive request in the same connection in which it sent
    // the request
    PortableServer::POA_var poa = root_poa->create_POA("bidirPOA", poa_manager.in(), policies);
    // Creation of bidirPOA is over. Destroy the Policy objects.
    for (CORBA::ULong i = 0; i < policies.length (); ++i) {
      policies[i]->destroy ();
    }
    poa_manager->activate ();

    PortableServer::Servant_var<Simple_i> svt = new Simple_i(orb.in(), callback_count);

    // Register and activate Simple servant
    PortableServer::ObjectId_var id = poa->activate_object(svt.in());
    obj = poa->id_to_reference(id.in());
    Simple_var server = Simple::_narrow(obj.in());

    CORBA::String_var ior = orb->object_to_string(server.in());
    if (ior_output_file != ACE_TEXT("")) {
      std::ofstream outfile(ACE_TEXT_ALWAYS_CHAR(ior_output_file.c_str()));
      outfile << ior.in();
    }
    std::cout << "Activated as " << ior.in() << std::endl;

    // Our own special orb->run() that knows how to callback clients
    while (true) {

      // returns 1 as soon as it has successfully called back.
      if (svt->call_client()) {
        break;
      }

      // We don't want to check for work pending, because we really want
      // to simulate a normal orb->run() while adding the ability to call
      // our routine which calls back to the client.
      orb->perform_work();
    }

    std::cout << "Event loop finished." << std::endl;

    CORBA::Boolean etherealize = true, wait = true;
    poa->destroy(etherealize, wait);
    orb->destroy();

    return 0;
  }
  catch(const CORBA::Exception& ex) {
    std::cerr << "Caught CORBA::Exception: " << std::endl << ex << std::endl;
  }

  return 1;
}
Exemple #25
0
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  try
  {
    // Initialize the EC Factory so we can customize the EC
    TAO_EC_Default_Factory::init_svcs ();

    // Initialize the ORB.
    CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);

    const ACE_TCHAR* ecname = ACE_TEXT ("EventService");
    const ACE_TCHAR* remote_ecname = 0;
    const ACE_TCHAR* iorfile = 0;
    for (int i = 0; argv[i] != 0; i++) {
      if (ACE_OS::strcmp(argv[i], ACE_TEXT("-ecname")) == 0) {
        if (argv[i+1] != 0) {
          i++;
          ecname = argv[i];
        } else {
          std::cerr << "Missing Event channel name" << std::endl;
        }
      }
      if (ACE_OS::strcmp(argv[i], ACE_TEXT("-gateway")) == 0) {
        if (argv[i+1] != 0) {
          i++;
          remote_ecname = argv[i];
        } else {
          std::cerr << "Missing Event channel name" << std::endl;
        }
      }
      if (ACE_OS::strcmp(argv[i], ACE_TEXT("-iorfile")) == 0) {
        if (argv[i+1] != 0) {
          i++;
          iorfile = argv[i];
        }
      }
    }

    // Get the POA
    CORBA::Object_var object = orb->resolve_initial_references ("RootPOA");
    PortableServer::POA_var poa = PortableServer::POA::_narrow (object.in ());
    PortableServer::POAManager_var poa_manager = poa->the_POAManager ();
    poa_manager->activate ();

    // Spawn a thread for the orb
    ACE_Thread_Manager *thread_mgr = ACE_Thread_Manager::instance();
    thread_mgr->spawn(orb_thread, orb.in());

    // Create a local event channel and register it with the RootPOA.
    TAO_EC_Event_Channel_Attributes attributes (poa.in (), poa.in ());
    PortableServer::Servant_var<TAO_EC_Event_Channel> ec_impl =
      new TAO_EC_Event_Channel(attributes);
    ec_impl->activate ();
    PortableServer::ObjectId_var oid = poa->activate_object(ec_impl.in());
    CORBA::Object_var ec_obj = poa->id_to_reference(oid.in());
    RtecEventChannelAdmin::EventChannel_var ec =
      RtecEventChannelAdmin::EventChannel::_narrow(ec_obj.in());

    // Find the Naming Service.
    object = orb->resolve_initial_references("NameService");
    CosNaming::NamingContextExt_var root_context = CosNaming::NamingContextExt::_narrow(object.in());
    CosNaming::Name_var name = root_context->to_name (ACE_TEXT_ALWAYS_CHAR (ecname));
    root_context->rebind(name.in(), ec.in());

    // Get a SupplierAdmin object from the EventChannel.
    RtecEventChannelAdmin::SupplierAdmin_var admin = ec->for_suppliers();

    // Get a ProxyPushConsumer from the SupplierAdmin.
    RtecEventChannelAdmin::ProxyPushConsumer_var consumer =
                                        admin->obtain_push_consumer();

    // Instantiate an EchoEventSupplier_i servant.
    PortableServer::Servant_var<EchoEventSupplier_i> servant =
      new EchoEventSupplier_i(orb.in());

    // Register it with the RootPOA.
    oid = poa->activate_object(servant.in());
    CORBA::Object_var supplier_obj = poa->id_to_reference(oid.in());
    RtecEventComm::PushSupplier_var supplier =
      RtecEventComm::PushSupplier::_narrow(supplier_obj.in());

    // Publish the events the supplier provides.
    ACE_SupplierQOS_Factory qos;
    qos.insert (MY_SOURCE_ID,      // Supplier's unique id
                MY_EVENT_TYPE,     // Event type
                0,                 // handle to the rt_info structure
                1);                // number of calls

    // Connect as a supplier of the published events.
    consumer->connect_push_supplier (supplier.in (),
                                     qos.get_SupplierQOS ());

    // Create an event (just a string in this case).
    const CORBA::String_var eventData = CORBA::string_dup (ACE_TEXT_ALWAYS_CHAR (ecname));

    // Create an event set for one event
    RtecEventComm::EventSet event (1);
    event.length (1);
    // Initialize event header.
    event[0].header.source = MY_SOURCE_ID;
    event[0].header.ttl = 1;
    event[0].header.type = MY_EVENT_TYPE;
    // Initialize data fields in event.
    event[0].data.any_value <<= eventData;

    PortableServer::Servant_var<TAO_EC_Gateway_IIOP> gateway =
      new TAO_EC_Gateway_IIOP;
    int gateway_initialized = 0;

    std::cout << "Supplier starting sending of events.\n";

    while (1) {

      consumer->push (event);
      ACE_Time_Value tv(0, 1000 * EVENT_DELAY_MS);
      orb->run(tv);

      if ((remote_ecname != 0)  && (!gateway_initialized)) {

        try {
          // Get the remote event channel object
          CORBA::Object_var obj = root_context->resolve_str (ACE_TEXT_ALWAYS_CHAR (remote_ecname));
          RtecEventChannelAdmin::EventChannel_var remote_ec =
            RtecEventChannelAdmin::EventChannel::_narrow(obj.in());

          int ok = 0;
          if (!CORBA::is_nil(remote_ec.in())) {
            // Now check if we can talk to it...
            try {
              RtecEventChannelAdmin::SupplierAdmin_var adm =
                remote_ec->for_suppliers();
              ok = 1;
            } catch(const CORBA::UserException&) {
              // What is the correct exception(s) to catch here?
            }
          }

          // There is a good remote event channel so initialize the
          // gateway.
          if (ok) {
            gateway->init(remote_ec.in(), ec.in());

            PortableServer::ObjectId_var gateway_oid =
              poa->activate_object(gateway.in());
            CORBA::Object_var gateway_obj =
              poa->id_to_reference(gateway_oid.in());
            RtecEventChannelAdmin::Observer_var obs =
              RtecEventChannelAdmin::Observer::_narrow(gateway_obj.in());
            RtecEventChannelAdmin::Observer_Handle local_ec_obs_handle =
              ec->append_observer (obs.in ());
            ACE_UNUSED_ARG (local_ec_obs_handle);
            gateway_initialized = 1;
            std::cout << "Gateway initialized\n";
            if (iorfile != 0) {
              CORBA::String_var str = orb->object_to_string( ec.in() );
              std::ofstream iorFile( ACE_TEXT_ALWAYS_CHAR(iorfile) );
              iorFile << str.in() << std::endl;
              iorFile.close();
            }
          }
        } catch(const CosNaming::NamingContext::NotFound&) {
          // Try again later...
        }
      }
    }

    orb->destroy();

    return 0;
  }
  catch(const CORBA::Exception& exc)
  {
    std::cerr << "Caught CORBA::Exception" << std::endl << exc << std::endl;
  }

  return 1;
}
Exemple #26
0
Messenger_i::Messenger_i (CORBA::ORB_ptr orb)
  : orb_ (CORBA::ORB::_duplicate (orb))
{

  CORBA::Object_var naming_obj =
    orb_->resolve_initial_references ("NameService");

  CosNaming::NamingContext_var naming_context =
    CosNaming::NamingContext::_narrow (naming_obj.in());

  CosNaming::Name name;
  name.length (1);
  name[0].id = CORBA::string_dup ("NotifyEventChannelFactory");

  CORBA::Object_var obj = naming_context->resolve (name);

  CosNotifyChannelAdmin::EventChannelFactory_var notify_factory =
    CosNotifyChannelAdmin::EventChannelFactory::_narrow (obj.in ());

  CosNotifyChannelAdmin::ChannelID id;
  CosNotification::QoSProperties initial_qos;
  CosNotification::AdminProperties initial_admin;

  CosNotifyChannelAdmin::EventChannel_var ec =
    notify_factory->create_channel (initial_qos,
                                    initial_admin,
                                    id);

  name[0].id = CORBA::string_dup ("MyEventChannel");

  naming_context->rebind (name, ec.in());

  CosNotifyChannelAdmin::AdminID adminid;
  CosNotifyChannelAdmin::InterFilterGroupOperator ifgop =
    CosNotifyChannelAdmin::OR_OP;

  CosNotifyChannelAdmin::SupplierAdmin_var supplier_admin =
    ec->new_for_suppliers (ifgop, adminid);

  CosNotifyChannelAdmin::ProxyID supplieradmin_proxy_id;

  CosNotifyChannelAdmin::ProxyConsumer_var proxy_consumer =
    supplier_admin->obtain_notification_push_consumer(
                                 CosNotifyChannelAdmin::STRUCTURED_EVENT,
                                 supplieradmin_proxy_id);

  StructuredEventSupplier_i *servant =
    new StructuredEventSupplier_i(orb_.in());

  CORBA::Object_var poa_obj = orb_->resolve_initial_references ("RootPOA");
  PortableServer::POA_var poa = PortableServer::POA::_narrow (poa_obj.in ());
  PortableServer::POAManager_var mgr = poa->the_POAManager ();

  mgr->activate ();
  PortableServer::ObjectId_var objectId = poa->activate_object (servant);

  CORBA::Object_var supplier_obj = poa->id_to_reference (objectId.in ());

  CosNotifyComm::StructuredPushSupplier_var supplier =
    CosNotifyComm::StructuredPushSupplier::_narrow (supplier_obj.in ());

  consumer_proxy_ =
    CosNotifyChannelAdmin::StructuredProxyPushConsumer::_narrow (proxy_consumer.in());

  consumer_proxy_->
    connect_structured_push_supplier (supplier.in());
}
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  CORBA::ORB_var orb;
  try
  {
    orb = CORBA::ORB_init (argc, argv);

    CORBA::Object_var root_poa_o =
      orb->resolve_initial_references ("RootPOA");

    PortableServer::POA_var rootPOA =
      PortableServer::POA::_narrow (root_poa_o.in ());

    if (CORBA::is_nil (rootPOA.in ()))
      {
        ACE_ERROR_RETURN ((LM_ERROR,
        " (%P|%t) Panic: nil RootPOA\n"), 1);
      }

    PortableServer::POAManager_var poaMgr = rootPOA->the_POAManager ();

    poaMgr->activate ();

    CORBA::PolicyList policies;
    policies.length (3);
    policies[0] = rootPOA->create_id_assignment_policy (
      PortableServer::SYSTEM_ID);
    policies[1] = rootPOA->create_implicit_activation_policy (
      PortableServer::NO_IMPLICIT_ACTIVATION);
    policies[2] = rootPOA->create_lifespan_policy (
      PortableServer::TRANSIENT);

    PortableServer::POA_var fooPoa = rootPOA->create_POA (
      "FOO_POA", poaMgr.in (), policies );

    for (CORBA::ULong i = 0; i < policies.length (); ++i)
    {
      policies[i]->destroy ();
    }

    Foo_i servant;
    PortableServer::ObjectId_var oid = fooPoa->activate_object( &servant );

    CORBA::Object_var obj = fooPoa->id_to_reference (oid.in ());

    foo_var client = foo::_narrow (obj.in());

    client->check();

    if (vc_check(client.in()))
    {
      orb->destroy();
      return 1;
    }

    fooPoa->deactivate_object (oid.in () );  //servant is gone

    if (vc_check(client.in(), false))  //exception expected
    {
      orb->destroy();
      return 2;
    }
  }
  catch(...)
  {
    return 3;
  }
  return 0;
}
Exemple #28
0
int main(int argc, char* argv[])
{
  try
  {
    po::options_description desc("Allowed options");
    desc.add_options()
      ("help", "produce help message")
      ("node-id", po::value<unsigned int>(), "set node identifier")
      ("node-registry", po::value<string>(), "ior of node registry");

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help"))
    {
      cout << desc << endl;
      return 0;
    }
    if (vm.count("node-id"))
    {
      cout << "node-id = " << vm["node-id"].as<unsigned int>() << endl;
      if (vm.count("node-registry"))
      {
        try
        {
          CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);
          {
            CORBA::Object_var poaObj = orb->resolve_initial_references("RootPOA");
            PortableServer::POA_var poa = PortableServer::POA::_narrow(poaObj);
            PortableServer::POAManager_var pman = poa->the_POAManager();
            pman->activate();


            cout << "node-registry = " << vm["node-registry"].as<string>() << endl;
            CORBA::Object_var nodeRegObj = orb->string_to_object(vm["node-registry"].as<string>().c_str());
            lmp_node_registry::NodeRegistry_var nodeRegistry = lmp_node_registry::NodeRegistry::_narrow(nodeRegObj);

            if( CORBA::is_nil(nodeRegistry) )
            {
              cerr << "nodeRegistry: The peer reference is nil!" << endl;
            }
            else
            {
              cout << "registerNode(nodeObj)" << endl;
              lmp_node::Node_i* myNode = new lmp_node::Node_i(orb, poa, vm["node-id"].as<unsigned int>(), nodeRegistry);

              cout << "activate object" << endl;
              PortableServer::ObjectId_var myNodeId = poa->activate_object(myNode);
              cout << "object activated" << endl;

              lmp_node::Node_var nodeObj = myNode->_this();
              myNode->_remove_ref();
              cout << "call registerNode(nodeObj)" << endl;
              nodeRegistry->registerNode(nodeObj);

              CORBA::String_var sior(orb->object_to_string(nodeObj));
              cout << sior << endl;
            }

            orb->run();
          }
          cout << "returned from orb->run()." << endl;
          orb->destroy();
        }
        catch(CORBA::SystemException& ex)
        {
          cerr << "Caught CORBA::" << ex._name() << endl;
        }
        catch(CORBA::Exception& ex)
        {
          cerr << "Caught CORBA::Exception: " << ex._name() << endl;
        }
        catch(omniORB::fatalException& fe)
        {
          cerr << "Caught omniORB::fatalException:" << endl;
          cerr << "  file: " << fe.file() << endl;
          cerr << "  line: " << fe.line() << endl;
          cerr << "  mesg: " << fe.errmsg() << endl;
        }
      }
    }
    else
    {
      cout << "node identifier was not set." << endl;
      return 1;
    }
  }
  catch(exception& e)
  {
    cerr << "error: " << e.what() << endl;
    return 1;
  }
  catch(...)
  {
    cerr << "Exception of unknown type!\n";
  }

  return 0;
}
Exemple #29
0
void
PubDriver::initialize(int& argc, char *argv[])
{
  ::DDS::DomainParticipantFactory_var dpf = TheParticipantFactoryWithArgs(argc, argv);

  // Activate the PubDriver servant and write its ior to a file.

  PortableServer::POA_var poa = TheServiceParticipant->the_poa ();
  CORBA::ORB_var orb = TheServiceParticipant->get_ORB ();

  PortableServer::ObjectId_var id = poa->activate_object(this);

  CORBA::Object_var object = poa->id_to_reference(id.in());

  CORBA::String_var ior_string = orb->object_to_string (object.in ());

  //
  // Write the IOR to a file.
  //
  FILE *output_file= ACE_OS::fopen (pub_driver_ior_.c_str (), "w");
  if (output_file == 0)
  {
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT("Cannot open output file for writing IOR\n")));
  }
  ACE_OS::fprintf (output_file, "%s", ior_string.in ());
  ACE_OS::fclose (output_file);

  ::DDS::ReturnCode_t ret = ::DDS::RETCODE_OK;

  ::Xyz::FooTypeSupport_var fts (new ::Xyz::FooTypeSupportImpl);

  participant_ =
    dpf->create_participant(MY_DOMAIN,
                            PARTICIPANT_QOS_DEFAULT,
                            ::DDS::DomainParticipantListener::_nil());
  TEST_CHECK (! CORBA::is_nil (participant_.in ()));

  if (::DDS::RETCODE_OK != fts->register_type(participant_.in (), MY_TYPE))
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Failed to register the FooTypeSupport.")));
    }


  ::DDS::TopicQos default_topic_qos;
  participant_->get_default_topic_qos(default_topic_qos);

  ::DDS::TopicQos new_topic_qos = default_topic_qos;
  new_topic_qos.reliability.kind  = ::DDS::RELIABLE_RELIABILITY_QOS;

  //The SunOS compiler had problem resolving operator in a namespace.
  //To resolve the compilation errors, the operator is called explicitly.
  TEST_CHECK (! (new_topic_qos == default_topic_qos));

  participant_->set_default_topic_qos(new_topic_qos);

  topic_ = participant_->create_topic (MY_TOPIC,
                                       MY_TYPE,
                                       TOPIC_QOS_DEFAULT,
                                       ::DDS::TopicListener::_nil());
  TEST_CHECK (! CORBA::is_nil (topic_.in ()));

  publisher_ =
    participant_->create_publisher(PUBLISHER_QOS_DEFAULT,
                                   ::DDS::PublisherListener::_nil());
  TEST_CHECK (! CORBA::is_nil (publisher_.in ()));

  publisher_servant_
    = dynamic_cast<OpenDDS::DCPS::PublisherImpl*>
    (publisher_.in ());

  attach_to_transport ();

  ::DDS::PublisherQos pub_qos_got;
  publisher_->get_qos (pub_qos_got);

  ::DDS::PublisherQos default_pub_qos;
  participant_->get_default_publisher_qos (default_pub_qos);
  TEST_CHECK (pub_qos_got == default_pub_qos);

  ::DDS::PublisherQos new_pub_qos = pub_qos_got;
  // This qos is not supported, so it's invalid qos.
  new_pub_qos.presentation.access_scope = ::DDS::GROUP_PRESENTATION_QOS;

  TEST_CHECK (! (new_pub_qos == default_pub_qos));

  ret = publisher_->set_qos (new_pub_qos);
  TEST_CHECK (ret == ::DDS::RETCODE_INCONSISTENT_POLICY);

  ::DDS::DomainParticipant_var participant
    = publisher_->get_participant ();

  TEST_CHECK (participant.in () == participant_.in ());

  ::DDS::DataWriterQos default_dw_qos;
  publisher_->get_default_datawriter_qos (default_dw_qos);

  ::DDS::DataWriterQos new_default_dw_qos = default_dw_qos;
  new_default_dw_qos.reliability.kind  = ::DDS::RELIABLE_RELIABILITY_QOS;

  TEST_CHECK (! (new_default_dw_qos == default_dw_qos));
  TEST_CHECK (publisher_->set_default_datawriter_qos (new_default_dw_qos)
              == ::DDS::RETCODE_OK);

  // Create datawriter to test copy_from_topic_qos.
  datawriter_
    = publisher_->create_datawriter(topic_.in (),
                                    DATAWRITER_QOS_USE_TOPIC_QOS,
                                    ::DDS::DataWriterListener::_nil());
  TEST_CHECK (! CORBA::is_nil (datawriter_.in ()));

  ::DDS::DataWriterQos dw_qos_use_topic_qos;
  datawriter_->get_qos (dw_qos_use_topic_qos);

  ::DDS::DataWriterQos copied_from_topic = default_dw_qos;
  ret = publisher_->copy_from_topic_qos (copied_from_topic, new_topic_qos);
  TEST_CHECK (ret == ::DDS::RETCODE_OK);

  TEST_CHECK (dw_qos_use_topic_qos == copied_from_topic);

  // Delete the datawriter.
  publisher_->delete_datawriter (datawriter_.in ());

  // Create datawriter to test DATAWRITER_QOS_DEFAULT/get_publisher
  // get_qos/set_qos/get_default_datawriter_qos.
  datawriter_
    = publisher_->create_datawriter(topic_.in (),
                                    DATAWRITER_QOS_DEFAULT,
                                    ::DDS::DataWriterListener::_nil());
  TEST_CHECK (! CORBA::is_nil (datawriter_.in ()));

  ::DDS::Topic_var topic_got
    = datawriter_->get_topic ();

  // the topics should point to the same servant
  // but not the same Object Reference.
  TopicImpl* topic_got_servant
    = dynamic_cast<TopicImpl*> (topic_got.in ());
  TopicImpl* topic_servant
    = dynamic_cast<TopicImpl*> (topic_.in ());

  TEST_CHECK (topic_got_servant == topic_servant);

  ::DDS::Publisher_var pub_got
    = datawriter_->get_publisher ();

  TEST_CHECK (pub_got.in () == publisher_.in ());

  ::DDS::DataWriterQos dw_qos_got;
  datawriter_->get_qos (dw_qos_got);

  TEST_CHECK (dw_qos_got == new_default_dw_qos);

  ::DDS::DataWriterQos new_dw_qos = dw_qos_got;

  new_dw_qos.reliability.kind  = ::DDS::RELIABLE_RELIABILITY_QOS;
  new_dw_qos.resource_limits.max_samples_per_instance = 2;
  new_dw_qos.history.kind  = ::DDS::KEEP_ALL_HISTORY_QOS;

  TEST_CHECK (! (dw_qos_got == new_dw_qos));

  ret = datawriter_->set_qos (new_dw_qos);

  TEST_CHECK (ret == ::DDS::RETCODE_IMMUTABLE_POLICY);

  // Delete the datawriter.
  publisher_->delete_datawriter (datawriter_.in ());

  // Create datawriter to test register/unregister/dispose and etc.
  ::DDS::DataWriterQos dw_qos;
  publisher_->get_default_datawriter_qos (dw_qos);

  dw_qos.history.depth = history_depth_;

  if (test_to_run_ == LIVELINESS_TEST)
  {
    dw_qos.liveliness.lease_duration.sec = lease_duration_sec;
    dw_qos.liveliness.lease_duration.nanosec = 0;
  }

  datawriter_
    = publisher_->create_datawriter(topic_.in (),
                                    dw_qos,
                                    ::DDS::DataWriterListener::_nil());
  TEST_CHECK (! CORBA::is_nil (datawriter_.in ()));

  datawriter_servant_
    = dynamic_cast<OpenDDS::DCPS::DataWriterImpl*> (datawriter_.in ());

  foo_datawriter_
    = ::Xyz::FooDataWriter::_narrow(datawriter_.in ());

  TEST_CHECK (! CORBA::is_nil (foo_datawriter_.in ()));

  foo_datawriter_servant_
    = dynamic_cast<Xyz::FooDataWriterImpl*>
    (foo_datawriter_.in ());

  TEST_CHECK (foo_datawriter_servant_ != 0);
}
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  try
  {
    // Initialize the EC Factory so we can customize the EC
    TAO_EC_Default_Factory::init_svcs ();

    // Initialize the ORB.
    CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);

    const ACE_TCHAR* ecname = ACE_TEXT ("EventService");
    const ACE_TCHAR* address = ACE_TEXT ("localhost");
    const ACE_TCHAR* iorfile = 0;
    u_short port = 12345;
    u_short listenport = 12345;
    int mcast = 1;

    for (int i = 0; argv[i] != 0; i++) {
      if (ACE_OS::strcmp(argv[i], ACE_TEXT("-ecname")) == 0) {
        if (argv[i+1] != 0) {
          i++;
          ecname = argv[i];
        } else {
          std::cerr << "Missing Event channel name" << std::endl;
        }
      } else if (ACE_OS::strcmp(argv[i], ACE_TEXT("-address")) == 0) {
        if (argv[i+1] != 0) {
          i++;
          address = argv[i];
        } else {
          std::cerr << "Missing address" << std::endl;
        }
      } else if (ACE_OS::strcmp(argv[i], ACE_TEXT("-port")) == 0) {
        if (argv[i+1] != 0) {
          i++;
          port = ACE_OS::atoi(argv[i]);
        } else {
          std::cerr << "Missing port" << std::endl;
        }
      } else if (ACE_OS::strcmp(argv[i], ACE_TEXT("-listenport")) == 0) {
        if (argv[i+1] != 0) {
          i++;
          listenport = ACE_OS::atoi(argv[i]);
        } else {
          std::cerr << "Missing port" << std::endl;
        }
      } else if (ACE_OS::strcmp(argv[i], ACE_TEXT("-iorfile")) == 0) {
        if (argv[i+1] != 0) {
          i++;
          iorfile = argv[i];
        }
      } else if (ACE_OS::strcmp(argv[i], ACE_TEXT("-udp")) == 0) {
        mcast = 0;
      }
    }

    // Get the POA
    CORBA::Object_var object = orb->resolve_initial_references ("RootPOA");
    PortableServer::POA_var poa = PortableServer::POA::_narrow (object.in ());
    PortableServer::POAManager_var poa_manager = poa->the_POAManager ();
    poa_manager->activate ();

    // Create a local event channel and register it
    TAO_EC_Event_Channel_Attributes attributes (poa.in (), poa.in ());
    PortableServer::Servant_var<TAO_EC_Event_Channel> ec_impl =
      new TAO_EC_Event_Channel(attributes);
    ec_impl->activate ();
    PortableServer::ObjectId_var oid = poa->activate_object(ec_impl.in());
    CORBA::Object_var ec_obj = poa->id_to_reference(oid.in());
    RtecEventChannelAdmin::EventChannel_var ec =
      RtecEventChannelAdmin::EventChannel::_narrow(ec_obj.in());

    // Find the Naming Service.
    CORBA::Object_var obj = orb->resolve_initial_references("NameService");
    CosNaming::NamingContextExt_var root_context = CosNaming::NamingContextExt::_narrow(obj.in());

    // Bind the Event Channel using Naming Services
    CosNaming::Name_var name = root_context->to_name (ACE_TEXT_ALWAYS_CHAR (ecname));
    root_context->rebind(name.in(), ec.in());

    // Get a proxy push consumer from the EventChannel.
    RtecEventChannelAdmin::SupplierAdmin_var admin = ec->for_suppliers();
    RtecEventChannelAdmin::ProxyPushConsumer_var consumer =
      admin->obtain_push_consumer();

    // Instantiate an EchoEventSupplier_i servant.
    PortableServer::Servant_var<EchoEventSupplier_i> servant =
      new EchoEventSupplier_i(orb.in());

    // Register it with the RootPOA.
    oid = poa->activate_object(servant.in());
    CORBA::Object_var supplier_obj = poa->id_to_reference(oid.in());
    RtecEventComm::PushSupplier_var supplier =
      RtecEventComm::PushSupplier::_narrow(supplier_obj.in());

    // Connect to the EC.
    ACE_SupplierQOS_Factory qos;
    qos.insert (MY_SOURCE_ID, MY_EVENT_TYPE, 0, 1);
    consumer->connect_push_supplier (supplier.in (), qos.get_SupplierQOS ());

    // Initialize the address server with the desired address.
    // This will be used by the sender object and the multicast
    // receiver.
    ACE_INET_Addr send_addr (port, address);
    PortableServer::Servant_var<SimpleAddressServer> addr_srv_impl =
      new SimpleAddressServer(send_addr);

    PortableServer::ObjectId_var addr_srv_oid =
      poa->activate_object(addr_srv_impl.in());
    CORBA::Object_var addr_srv_obj = poa->id_to_reference(addr_srv_oid.in());
    RtecUDPAdmin::AddrServer_var addr_srv =
      RtecUDPAdmin::AddrServer::_narrow(addr_srv_obj.in());

    // Create and initialize the sender object
    PortableServer::Servant_var<TAO_ECG_UDP_Sender> sender =
                                TAO_ECG_UDP_Sender::create();
    TAO_ECG_UDP_Out_Endpoint endpoint;
    if (endpoint.dgram ().open (ACE_Addr::sap_any) == -1) {
      std::cerr << "Cannot open send endpoint" << std::endl;
      return 1;
    }

    // TAO_ECG_UDP_Sender::init() takes a TAO_ECG_Refcounted_Endpoint.
    // If we don't clone our endpoint and pass &endpoint, the sender will
    // attempt to delete endpoint during shutdown.
    TAO_ECG_Refcounted_Endpoint clone (new TAO_ECG_UDP_Out_Endpoint (endpoint));
    sender->init (ec.in (), addr_srv.in (), clone);

    // Setup the subscription and connect to the EC
    ACE_ConsumerQOS_Factory cons_qos_fact;
    cons_qos_fact.start_disjunction_group ();
    cons_qos_fact.insert (ACE_ES_EVENT_SOURCE_ANY, ACE_ES_EVENT_ANY, 0);
    RtecEventChannelAdmin::ConsumerQOS sub = cons_qos_fact.get_ConsumerQOS ();
    sender->connect (sub);

    // Create and initialize the receiver
    PortableServer::Servant_var<TAO_ECG_UDP_Receiver> receiver =
                                      TAO_ECG_UDP_Receiver::create();

    // TAO_ECG_UDP_Receiver::init() takes a TAO_ECG_Refcounted_Endpoint.
    // If we don't clone our endpoint and pass &endpoint, the receiver will
    // attempt to delete endpoint during shutdown.
    TAO_ECG_Refcounted_Endpoint clone2 (new TAO_ECG_UDP_Out_Endpoint (endpoint));
    receiver->init (ec.in (), clone2, addr_srv.in ());

    // Setup the registration and connect to the event channel
    ACE_SupplierQOS_Factory supp_qos_fact;
    supp_qos_fact.insert (MY_SOURCE_ID, MY_EVENT_TYPE, 0, 1);
    RtecEventChannelAdmin::SupplierQOS pub = supp_qos_fact.get_SupplierQOS ();
    receiver->connect (pub);

    // Create the appropriate event handler and register it with the reactor
    auto_ptr<ACE_Event_Handler> eh;
    if (mcast) {
      auto_ptr<TAO_ECG_Mcast_EH> mcast_eh(new TAO_ECG_Mcast_EH (receiver.in()));
      mcast_eh->reactor (orb->orb_core ()->reactor ());
      mcast_eh->open (ec.in());
      ACE_auto_ptr_reset(eh,mcast_eh.release());
      //eh.reset(mcast_eh.release());
    } else {
      auto_ptr<TAO_ECG_UDP_EH> udp_eh (new TAO_ECG_UDP_EH (receiver.in()));
      udp_eh->reactor (orb->orb_core ()->reactor ());
      ACE_INET_Addr local_addr (listenport);
      if (udp_eh->open (local_addr) == -1) {
        std::cerr << "Cannot open EH" << std::endl;
      }
      ACE_auto_ptr_reset(eh,udp_eh.release());
      //eh.reset(udp_eh.release());
    }

    // Create an event (just a string in this case).
    const CORBA::String_var eventData = CORBA::string_dup (ACE_TEXT_ALWAYS_CHAR (ecname));

    // Create an event set for one event
    RtecEventComm::EventSet event (1);
    event.length (1);

    // Initialize event header.
    event[0].header.source = MY_SOURCE_ID;
    event[0].header.ttl = 1;
    event[0].header.type = MY_EVENT_TYPE;

    // Initialize data fields in event.
    event[0].data.any_value <<= eventData;

    if (iorfile != 0) {
      CORBA::String_var str = orb->object_to_string( ec.in() );
      std::ofstream iorFile( ACE_TEXT_ALWAYS_CHAR(iorfile) );
      iorFile << str.in() << std::endl;
      iorFile.close();
    }
    std::cout << "Starting main loop" << std::endl;

    const int EVENT_DELAY_MS = 10;

    while (1) {
      consumer->push (event);

      ACE_Time_Value tv(0, 1000 * EVENT_DELAY_MS);
      orb->run(tv);
    }

    orb->destroy();
    return 0;
  }
  catch(const CORBA::Exception& exc)
  {
    std::cerr << "Caught CORBA::Exception" << std::endl << exc << std::endl;
  }
  return 1;
}