Example #1
0
int JoystickPublishFalcon::run(int argc, char* argv[])
{
	QCoreApplication a(argc, argv);  // NON-GUI application
	int status=EXIT_SUCCESS;

	JoystickAdapterPrx joystickadapter_proxy;

	string proxy, tmp;
	initialize();


	IceStorm::TopicManagerPrx topicManager = IceStorm::TopicManagerPrx::checkedCast(communicator()->propertyToProxy("TopicManager.Proxy"));



	IceStorm::TopicPrx joystickadapter_topic;
	while (!joystickadapter_topic)
	{
		try
		{
			joystickadapter_topic = topicManager->retrieve("JoystickAdapter");
		}
		catch (const IceStorm::NoSuchTopic&)
		{
			try
			{
				joystickadapter_topic = topicManager->create("JoystickAdapter");
			}
			catch (const IceStorm::TopicExists&){
				// Another client created the topic.
			}
		}
	}
	Ice::ObjectPrx joystickadapter_pub = joystickadapter_topic->getPublisher()->ice_oneway();
	JoystickAdapterPrx joystickadapter = JoystickAdapterPrx::uncheckedCast(joystickadapter_pub);
	mprx["JoystickAdapterPub"] = (::IceProxy::Ice::Object*)(&joystickadapter);



	GenericWorker *worker = new SpecificWorker(mprx);
	//Monitor thread
	GenericMonitor *monitor = new SpecificMonitor(worker,communicator());
	QObject::connect(monitor,SIGNAL(kill()),&a,SLOT(quit()));
	QObject::connect(worker,SIGNAL(kill()),&a,SLOT(quit()));
	monitor->start();

	if ( !monitor->isRunning() )
		return status;
	try
	{
		// Server adapter creation and publication
		Ice::ObjectAdapterPtr adapterCommonBehavior = communicator()->createObjectAdapter("CommonBehavior");
		CommonBehaviorI *commonbehaviorI = new CommonBehaviorI(monitor );
		adapterCommonBehavior->add(commonbehaviorI, communicator()->stringToIdentity("commonbehavior"));
		adapterCommonBehavior->activate();





		// Server adapter creation and publication
		cout << SERVER_FULL_NAME " started" << endl;

		// User defined QtGui elements ( main window, dialogs, etc )

#ifdef USE_QTGUI
		//ignoreInterrupt(); // Uncomment if you want the component to ignore console SIGINT signal (ctrl+c).
		a.setQuitOnLastWindowClosed( true );
#endif
		// Run QT Application Event Loop
		a.exec();
		status = EXIT_SUCCESS;
	}
	catch(const Ice::Exception& ex)
	{
		status = EXIT_FAILURE;

		cout << "[" << PROGRAM_NAME << "]: Exception raised on main thread: " << endl;
		cout << ex;

#ifdef USE_QTGUI
		a.quit();
#endif
		monitor->exit(0);
}

	return status;
}
int prosilicaComp::run(int argc, char* argv[])
{
#ifdef USE_QTGUI
	QApplication a(argc, argv);  // GUI application
#else
	QCoreApplication a(argc, argv);  // NON-GUI application
#endif
	int status=EXIT_SUCCESS;

	// Remote server proxy access example
	// RemoteComponentPrx remotecomponent_proxy;
	DifferentialRobotPrx differentialrobot_proxy;
	JointMotorPrx jointmotor_proxy;


	string proxy;

	// User variables


	initialize();

	// Remote server proxy creation example
	// try
	// {
	// 	// Load the remote server proxy
	//	proxy = getProxyString("RemoteProxy");
	//	remotecomponent_proxy = RemotePrx::uncheckedCast( communicator()->stringToProxy( proxy ) );
	//	if( !remotecomponent_proxy )
	//	{
	//		rInfo(QString("Error loading proxy!"));
	//		return EXIT_FAILURE;
	//	}
	//catch(const Ice::Exception& ex)
	//{
	//	cout << "[" << PROGRAM_NAME << "]: Exception: " << ex << endl;
	//	return EXIT_FAILURE;
	//}
	//rInfo("RemoteProxy initialized Ok!");
	// 	// Now you can use remote server proxy (remotecomponent_proxy) as local object


	try
	{
		// Load the remote server proxy
		proxy = getProxyString("DifferentialRobotProxy");
		differentialrobot_proxy = DifferentialRobotPrx::uncheckedCast( communicator()->stringToProxy( proxy ) );
		if( !differentialrobot_proxy )
		{
			rInfo(QString("Error loading proxy!"));
			return EXIT_FAILURE;
		}
	}
	catch(const Ice::Exception& ex)
	{
		cout << "[" << PROGRAM_NAME << "]: Exception: " << ex << endl;
		return EXIT_FAILURE;
	}
	rInfo("DifferentialRobotProxy initialized Ok!");


	try
	{
		// Load the remote server proxy
		proxy = getProxyString("JointMotorProxy");
		jointmotor_proxy = JointMotorPrx::uncheckedCast( communicator()->stringToProxy( proxy ) );
		if( !jointmotor_proxy )
		{
			rInfo(QString("Error loading proxy!"));
			return EXIT_FAILURE;
		}
	}
	catch(const Ice::Exception& ex)
	{
		cout << "[" << PROGRAM_NAME << "]: Exception: " << ex << endl;
		return EXIT_FAILURE;
	}
	rInfo("JointMotorProxy initialized Ok!");



	Worker *worker = new Worker(differentialrobot_proxy, jointmotor_proxy);
	//Monitor thread
	Monitor *monitor = new Monitor(worker,communicator());
	QObject::connect(monitor,SIGNAL(kill()),&a,SLOT(quit()));
	QObject::connect(worker,SIGNAL(kill()),&a,SLOT(quit()));
	monitor->start();
	
	if ( !monitor->isRunning() )
		return status;
	try
	{
		// Server adapter creation and publication
		Ice::ObjectAdapterPtr adapterCommonBehavior = communicator()->createObjectAdapter("CommonBehavior");
		CommonBehaviorI *commonbehaviorI = new CommonBehaviorI(monitor );
		adapterCommonBehavior->add(commonbehaviorI, communicator()->stringToIdentity("commonbehavior"));
		adapterCommonBehavior->activate();
		
		// Server adapter creation and publication
		Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("prosilicaComp");
		CameraBusI *camerabusI = new CameraBusI(worker );
		adapter->add(camerabusI, communicator()->stringToIdentity("camerabus"));

		adapter->activate();

		cout << SERVER_FULL_NAME " started" << endl;

		// User defined QtGui elements ( main window, dialogs, etc )

#ifdef USE_QTGUI
		//ignoreInterrupt(); // Uncomment if you want the component to ignore console SIGINT signal (ctrl+c).
		a.setQuitOnLastWindowClosed( true );
#endif
		// Run QT Application Event Loop
		a.exec();
		status = EXIT_SUCCESS;
	}
	catch(const Ice::Exception& ex)
	{
		status = EXIT_FAILURE;

		cout << "[" << PROGRAM_NAME << "]: Exception raised on main thread: " << endl;
		cout << ex;

#ifdef USE_QTGUI
		a.quit();
#endif
	}

	return status;
}
Example #3
0
void
allTests(const Ice::CommunicatorPtr& communicator)
{
    {
        cout << "Testing Glacier2 stub... " << flush;
        char** argv = 0;
        int argc = 0;
        SessionHelperClient client;
        client.run(argc, argv);
        cout << "ok" << endl;
    }

    {
        cout << "Testing IceStorm stub... " << flush;
        IceStorm::TopicManagerPrxPtr manager =
                    ICE_UNCHECKED_CAST(IceStorm::TopicManagerPrx, communicator->stringToProxy("test:default -p 12010"));

        IceStorm::QoS qos;
        IceStorm::TopicPrxPtr topic;
        string topicName = "time";

        try
        {
            topic = manager->retrieve(topicName);
            test(false);
        }
        catch(const IceStorm::NoSuchTopic&)
        {
            test(false);
        }
        catch(const Ice::LocalException&)
        {
        }

        Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("subscriber" ,"tcp");
        Ice::ObjectPrxPtr subscriber = adapter->addWithUUID(ICE_MAKE_SHARED(ClockI));
        adapter->activate();
#ifdef ICE_CPP11_MAPPING
        assert(!topic);
#else
        try
        {
            topic->subscribeAndGetPublisher(qos, subscriber);
            test(false);
        }
        catch(const IceStorm::AlreadySubscribed&)
        {
            test(false);
        }
        catch(const IceUtil::NullHandleException&)
        {
        }
#endif
        cout << "ok" << endl;
    }

    {
        cout << "Testing IceGrid stub... " << flush;

        Ice::ObjectPrxPtr base = communicator->stringToProxy("test:default -p 12010");
        IceGrid::RegistryPrxPtr registry = ICE_UNCHECKED_CAST(IceGrid::RegistryPrx, base);
        IceGrid::AdminSessionPrxPtr session;
        IceGrid::AdminPrxPtr admin;
        try
        {
            session = registry->createAdminSession("username", "password");
            test(false);
        }
        catch(const IceGrid::PermissionDeniedException&)
        {
            test(false);
        }
        catch(const Ice::LocalException&)
        {
        }
#ifdef ICE_CPP11_MAPPING
        assert(!admin);
#else
        try
        {
            admin = session->getAdmin();
            test(false);
        }
        catch(const IceUtil::NullHandleException&)
        {
        }
#endif
        cout << "ok" << endl;
    }
}
Example #4
0
GPrx
allTests(const Ice::CommunicatorPtr& communicator)
{
    tprintf("testing facet registration exceptions... ");
    Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("FacetExceptionTestAdapter");
    Ice::ObjectPtr obj = new EmptyI;
    adapter->add(obj, communicator->stringToIdentity("d"));
    adapter->addFacet(obj, communicator->stringToIdentity("d"), "facetABCD");
    try
    {
        adapter->addFacet(obj, communicator->stringToIdentity("d"), "facetABCD");
        test(false);
    }
    catch(Ice::AlreadyRegisteredException&)
    {
    }
    adapter->removeFacet(communicator->stringToIdentity("d"), "facetABCD");
    try
    {
        adapter->removeFacet(communicator->stringToIdentity("d"), "facetABCD");
        test(false);
    }
    catch(Ice::NotRegisteredException&)
    {
    }
    tprintf("ok\n");

    tprintf("testing removeAllFacets... ");
    Ice::ObjectPtr obj1 = new EmptyI;
    Ice::ObjectPtr obj2 = new EmptyI;
    adapter->addFacet(obj1, communicator->stringToIdentity("id1"), "f1");
    adapter->addFacet(obj2, communicator->stringToIdentity("id1"), "f2");
    Ice::ObjectPtr obj3 = new EmptyI;
    adapter->addFacet(obj1, communicator->stringToIdentity("id2"), "f1");
    adapter->addFacet(obj2, communicator->stringToIdentity("id2"), "f2");
    adapter->addFacet(obj3, communicator->stringToIdentity("id2"), "");
    Ice::FacetMap fm = adapter->removeAllFacets(communicator->stringToIdentity("id1"));
    test(fm.size() == 2);
    test(fm["f1"] == obj1);
    test(fm["f2"] == obj2);
    try
    {
        adapter->removeAllFacets(communicator->stringToIdentity("id1"));
        test(false);
    }
    catch(Ice::NotRegisteredException&)
    {
    }
    fm = adapter->removeAllFacets(communicator->stringToIdentity("id2"));
    test(fm.size() == 3);
    test(fm["f1"] == obj1);
    test(fm["f2"] == obj2);
    test(fm[""] == obj3);
    tprintf("ok\n");

    adapter->deactivate();

    tprintf("testing stringToProxy... ");
    string ref = communicator->getProperties()->getPropertyWithDefault("Facets.Proxy", "d:default -p 12010 -t 10000");
    Ice::ObjectPrx db = communicator->stringToProxy(ref);
    test(db);
    tprintf("ok\n");

    tprintf("testing unchecked cast... ");
    Ice::ObjectPrx prx = Ice::ObjectPrx::uncheckedCast(db);
    test(prx->ice_getFacet().empty());
    prx = Ice::ObjectPrx::uncheckedCast(db, "facetABCD");
    test(prx->ice_getFacet() == "facetABCD");
    Ice::ObjectPrx prx2 = Ice::ObjectPrx::uncheckedCast(prx);
    test(prx2->ice_getFacet() == "facetABCD");
    Ice::ObjectPrx prx3 = Ice::ObjectPrx::uncheckedCast(prx, "");
    test(prx3->ice_getFacet().empty());
    DPrx d = Test::DPrx::uncheckedCast(db);
    test(d->ice_getFacet().empty());
    DPrx df = Test::DPrx::uncheckedCast(db, "facetABCD");
    test(df->ice_getFacet() == "facetABCD");
    DPrx df2 = Test::DPrx::uncheckedCast(df);
    test(df2->ice_getFacet() == "facetABCD");
    DPrx df3 = Test::DPrx::uncheckedCast(df, "");
    test(df3->ice_getFacet().empty());
    tprintf("ok\n");

    tprintf("testing checked cast... ");
    prx = Ice::ObjectPrx::checkedCast(db);
    test(prx->ice_getFacet().empty());
    prx = Ice::ObjectPrx::checkedCast(db, "facetABCD");
    test(prx->ice_getFacet() == "facetABCD");
    prx2 = Ice::ObjectPrx::checkedCast(prx);
    test(prx2->ice_getFacet() == "facetABCD");
    prx3 = Ice::ObjectPrx::checkedCast(prx, "");
    test(prx3->ice_getFacet().empty());
    d = Test::DPrx::checkedCast(db);
    test(d->ice_getFacet().empty());
    df = Test::DPrx::checkedCast(db, "facetABCD");
    test(df->ice_getFacet() == "facetABCD");
    df2 = Test::DPrx::checkedCast(df);
    test(df2->ice_getFacet() == "facetABCD");
    df3 = Test::DPrx::checkedCast(df, "");
    test(df3->ice_getFacet().empty());
    tprintf("ok\n");

    tprintf("testing non-facets A, B, C, and D... ");
    d = DPrx::checkedCast(db);
    test(d);
    test(d == db);
    test(d->callA() == "A");
    test(d->callB() == "B");
    test(d->callC() == "C");
    test(d->callD() == "D");
    tprintf("ok\n");

    tprintf("testing facets A, B, C, and D... ");
    df = DPrx::checkedCast(d, "facetABCD");
    test(df);
    test(df->callA() == "A");
    test(df->callB() == "B");
    test(df->callC() == "C");
    test(df->callD() == "D");
    tprintf("ok\n");

    tprintf("testing facets E and F... ");
    FPrx ff = FPrx::checkedCast(d, "facetEF");
    test(ff);
    test(ff->callE() == "E");
    test(ff->callF() == "F");
    tprintf("ok\n");

    tprintf("testing facet G... ");
    GPrx gf = GPrx::checkedCast(ff, "facetGH");
    test(gf);
    test(gf->callG() == "G");
    tprintf("ok\n");

    tprintf("testing whether casting preserves the facet... ");
    HPrx hf = HPrx::checkedCast(gf);
    test(hf);
    test(hf->callG() == "G");
    test(hf->callH() == "H");
    tprintf("ok\n");

    return gf;
}
int stormServerComp::run(int argc, char* argv[])
{
#ifdef USE_QTGUI
	QApplication a(argc, argv);  // GUI application
#else
	QCoreApplication a(argc, argv);  // NON-GUI application
#endif
	int status=EXIT_SUCCESS;

	// Remote server proxy access example
	// RemoteComponentPrx remotecomponent_proxy;
	SendTopicPrx sendtopic_proxy;


	string proxy;

	// User variables


	initialize();

	// Remote server proxy creation example
	// try
	// {
	// 	// Load the remote server proxy
	//	proxy = getProxyString("RemoteProxy");
	//	remotecomponent_proxy = RemotePrx::uncheckedCast( communicator()->stringToProxy( proxy ) );
	//	if( !remotecomponent_proxy )
	//	{
	//		rInfo(QString("Error loading proxy!"));
	//		return EXIT_FAILURE;
	//	}
	//catch(const Ice::Exception& ex)
	//{
	//	cout << "[" << PROGRAM_NAME << "]: Exception: " << ex << endl;
	//	return EXIT_FAILURE;
	//}
	//rInfo("RemoteProxy initialized Ok!");
	// 	// Now you can use remote server proxy (remotecomponent_proxy) as local object
	
	IceStorm::TopicManagerPrx topicManager = IceStorm::TopicManagerPrx::checkedCast(communicator()->propertyToProxy("TopicManager.Proxy"));
	
	IceStorm::TopicPrx sendtopic_topic;
    while(!sendtopic_topic){
		try {
			sendtopic_topic = topicManager->retrieve("SendTopic");
		}catch (const IceStorm::NoSuchTopic&){
			try{
				sendtopic_topic = topicManager->create("SendTopic");
			}catch (const IceStorm::TopicExists&){
				// Another client created the topic.
			}
		}
	}
	Ice::ObjectPrx sendtopic_pub = sendtopic_topic->getPublisher()->ice_oneway();
	SendTopicPrx sendtopic = SendTopicPrx::uncheckedCast(sendtopic_pub);
	mprx["SendTopicPub"] = (::IceProxy::Ice::Object*)(&sendtopic);
	
	
	GenericWorker *worker = new SpecificWorker(mprx);
	//Monitor thread
	GenericMonitor *monitor = new SpecificMonitor(worker,communicator());
	QObject::connect(monitor,SIGNAL(kill()),&a,SLOT(quit()));
	QObject::connect(worker,SIGNAL(kill()),&a,SLOT(quit()));
	monitor->start();
	
	if ( !monitor->isRunning() )
		return status;
	try
	{
		// Server adapter creation and publication
		Ice::ObjectAdapterPtr adapterCommonBehavior = communicator()->createObjectAdapter("CommonBehavior");
		CommonBehaviorI *commonbehaviorI = new CommonBehaviorI(monitor );
		adapterCommonBehavior->add(commonbehaviorI, communicator()->stringToIdentity("commonbehavior"));
		adapterCommonBehavior->activate();
		// Server adapter creation and publication
		Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("stormServerComp");
				
		adapter->activate();

		cout << SERVER_FULL_NAME " started" << endl;

		// User defined QtGui elements ( main window, dialogs, etc )

#ifdef USE_QTGUI
		//ignoreInterrupt(); // Uncomment if you want the component to ignore console SIGINT signal (ctrl+c).
		a.setQuitOnLastWindowClosed( true );
#endif
		// Run QT Application Event Loop
		a.exec();
		status = EXIT_SUCCESS;
	}
	catch(const Ice::Exception& ex)
	{
		status = EXIT_FAILURE;

		cout << "[" << PROGRAM_NAME << "]: Exception raised on main thread: " << endl;
		cout << ex;

#ifdef USE_QTGUI
		a.quit();
#endif
	}

	return status;
}
Example #6
0
ThrowerPrxPtr
allTests(const Ice::CommunicatorPtr& communicator)
{
    cout << "testing ice_print()/what()... " << flush;
    {
        A a;
        string aMsg = "::Test::A";

        Ice::UnknownLocalException ule("thisFile", 99);
        string uleMsg = "thisFile:99: ::Ice::UnknownLocalException:\nunknown local exception";

        //
        // Test ice_print().
        //
        {
            stringstream str;
            a.ice_print(str);
            test(str.str() == aMsg);
        }
        {
            stringstream str;
            ule.ice_print(str);
            test(str.str() == uleMsg);
        }

        //
        // Test operator<<().
        //
        {
            stringstream str;
            str << a;
            test(str.str() == aMsg);
        }
        {
            stringstream str;
            str << ule;
            test(str.str() == uleMsg);
        }

        //
        // Test what(). (Called twice because of lazy initialization in what().)
        //
        test(aMsg == a.what());
        test(aMsg == a.what());

        test(uleMsg == ule.what());
        test(uleMsg == ule.what());

        {
            E ex("E");
            ostringstream os;
            ex.ice_print(os);
            test(os.str() == "::Test::E");
            test(ex.data == "E");
        }

        //
        // Test custom ice_print
        //
        {
            F ex("F");
            ostringstream os;
            ex.ice_print(os);
            test(os.str() == "::Test::F data:'F'");
            test(ex.data == "F");
        }

        {
            G ex(__FILE__, __LINE__, "G");
            ostringstream os;
            ex.ice_print(os);
            test(endsWith(os.str(), "Test::G"));
            test(ex.data == "G");
        }

        {
            H ex(__FILE__, __LINE__, "H");
            ostringstream os;
            ex.ice_print(os);
            test(endsWith(os.str(), "Test::H data:'H'"));
            test(ex.data == "H");
        }

    }
    cout << "ok" << endl;

    string localOAEndpoint;
    {
        ostringstream ostr;
        if(communicator->getProperties()->getProperty("Ice.Default.Protocol") == "bt")
        {
            ostr << "default -a *";
        }
        else
        {
            ostr << "default -h *";
        }
        localOAEndpoint = ostr.str();
    }

    cout << "testing object adapter registration exceptions... " << flush;
    {
        Ice::ObjectAdapterPtr first;
        try
        {
            first = communicator->createObjectAdapter("TestAdapter0");
            test(false);
        }
        catch(const Ice::InitializationException& ex)
        {
            if(printException)
            {
                Ice::Print printer(communicator->getLogger());
                printer << ex;
            }
            // Expected
        }

        communicator->getProperties()->setProperty("TestAdapter0.Endpoints", localOAEndpoint);
        first = communicator->createObjectAdapter("TestAdapter0");
        try
        {
            Ice::ObjectAdapterPtr second = communicator->createObjectAdapter("TestAdapter0");
            test(false);
        }
        catch(const Ice::AlreadyRegisteredException& ex)
        {
            if(printException)
            {
                Ice::Print printer(communicator->getLogger());
                printer << ex;
            }

            // Expected
        }

        try
        {
            Ice::ObjectAdapterPtr second =
                communicator->createObjectAdapterWithEndpoints("TestAdapter0", "ssl -h foo -p 12011");
            test(false);
        }
        catch(const Ice::AlreadyRegisteredException& ex)
        {
            if(printException)
            {
                Ice::Print printer(communicator->getLogger());
                printer << ex;
            }

            // Expected.
        }
        first->deactivate();
    }
    cout << "ok" << endl;

    cout << "testing servant registration exceptions... " << flush;
    {
        communicator->getProperties()->setProperty("TestAdapter1.Endpoints", localOAEndpoint);
        Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("TestAdapter1");
        Ice::ObjectPtr obj = ICE_MAKE_SHARED(EmptyI);
        adapter->add(obj, Ice::stringToIdentity("x"));
        try
        {
            adapter->add(obj, Ice::stringToIdentity("x"));
            test(false);
        }
        catch(const Ice::AlreadyRegisteredException& ex)
        {
            if(printException)
            {
                Ice::Print printer(communicator->getLogger());
                printer << ex;
            }
        }

        try
        {
            adapter->add(obj, Ice::stringToIdentity(""));
        }
        catch(const Ice::IllegalIdentityException& ex)
        {
            test(ex.id.name == "");
            if(printException)
            {
                Ice::Print printer(communicator->getLogger());
                printer << ex;
            }
        }

        try
        {
            adapter->add(0, Ice::stringToIdentity("x"));
        }
        catch(const Ice::IllegalServantException& ex)
        {
            if(printException)
            {
                Ice::Print printer(communicator->getLogger());
                printer << ex;
            }
        }

        adapter->remove(Ice::stringToIdentity("x"));
        try
        {
            adapter->remove(Ice::stringToIdentity("x"));
            test(false);
        }
        catch(const Ice::NotRegisteredException& ex)
        {
            if(printException)
            {
                Ice::Print printer(communicator->getLogger());
                printer << ex;
            }
        }

        adapter->deactivate();
    }
    cout << "ok" << endl;

    cout << "testing servant locator registrations exceptions... " << flush;
    {
        communicator->getProperties()->setProperty("TestAdapter2.Endpoints", localOAEndpoint);
        Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("TestAdapter2");
        Ice::ServantLocatorPtr loc = ICE_MAKE_SHARED(ServantLocatorI);
        adapter->addServantLocator(loc, "x");
        try
        {
            adapter->addServantLocator(loc, "x");
            test(false);
        }
        catch(const Ice::AlreadyRegisteredException&)
        {
        }

        adapter->deactivate();
    }
    cout << "ok" << endl;

    cout << "testing value factory registration exception... " << flush;
    {
#ifdef ICE_CPP11_MAPPING
        communicator->getValueFactoryManager()->add(
            [](const std::string&)
            {
                return nullptr;
            },
            "x");
        try
        {
            communicator->getValueFactoryManager()->add(
                [](const std::string&)
                {
                    return nullptr;
                },
                "x");
            test(false);
        }
        catch(const Ice::AlreadyRegisteredException&)
        {
        }
#else
        Ice::ValueFactoryPtr vf = new ValueFactoryI;
        communicator->getValueFactoryManager()->add(vf, "x");
        try
        {
            communicator->getValueFactoryManager()->add(vf, "x");
            test(false);
        }
        catch(const Ice::AlreadyRegisteredException&)
        {
        }
#endif
    }
    cout << "ok" << endl;

    cout << "testing stringToProxy... " << flush;
    string ref = "thrower:" + getTestEndpoint(communicator, 0);
    Ice::ObjectPrxPtr base = communicator->stringToProxy(ref);
    test(base);
    cout << "ok" << endl;

    cout << "testing checked cast... " << flush;
    ThrowerPrxPtr thrower = ICE_CHECKED_CAST(ThrowerPrx, base);
    test(thrower);
#ifdef ICE_CPP11_MAPPING
    test(Ice::targetEqualTo(thrower, base));
#else
    test(thrower == base);
#endif
    cout << "ok" << endl;

    cout << "catching exact types... " << flush;

    try
    {
        thrower->throwAasA(1);
        test(false);
    }
    catch(const A& ex)
    {
        test(ex.aMem == 1);
    }
    catch(const Ice::Exception& ex)
    {
        cout << ex << endl;
        test(false);
    }
    catch(...)
    {
        test(false);
    }

    try
    {
        thrower->throwAorDasAorD(1);
        test(false);
    }
    catch(const A& ex)
    {
        test(ex.aMem == 1);
    }
    catch(...)
    {
        test(false);
    }

    try
    {
        thrower->throwAorDasAorD(-1);
        test(false);
    }
    catch(const D& ex)
    {
        test(ex.dMem == -1);
    }
    catch(...)
    {
        test(false);
    }

    try
    {
        thrower->throwBasB(1, 2);
        test(false);
    }
    catch(const B& ex)
    {
        test(ex.aMem == 1);
        test(ex.bMem == 2);
    }
    catch(...)
    {
        test(false);
    }

    try
    {
        thrower->throwCasC(1, 2, 3);
        test(false);
    }
    catch(const C& ex)
    {
        test(ex.aMem == 1);
        test(ex.bMem == 2);
        test(ex.cMem == 3);
    }
    catch(...)
    {
        test(false);
    }

    try
    {
        thrower->throwModA(1, 2);
        test(false);
    }
    catch(const Mod::A& ex)
    {
        test(ex.aMem == 1);
        test(ex.a2Mem == 2);
    }
    catch(const Ice::OperationNotExistException&)
    {
        //
        // This operation is not supported in Java.
        //
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "catching base types... " << flush;

    try
    {
        thrower->throwBasB(1, 2);
        test(false);
    }
    catch(const A& ex)
    {
        test(ex.aMem == 1);
    }
    catch(...)
    {
        test(false);
    }

    try
    {
        thrower->throwCasC(1, 2, 3);
        test(false);
    }
    catch(const B& ex)
    {
        test(ex.aMem == 1);
        test(ex.bMem == 2);
    }
    catch(...)
    {
        test(false);
    }

    try
    {
        thrower->throwModA(1, 2);
        test(false);
    }
    catch(const A& ex)
    {
        test(ex.aMem == 1);
    }
    catch(const Ice::OperationNotExistException&)
    {
        //
        // This operation is not supported in Java.
        //
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "catching derived types... " << flush;

    try
    {
        thrower->throwBasA(1, 2);
        test(false);
    }
    catch(const B& ex)
    {
        test(ex.aMem == 1);
        test(ex.bMem == 2);
    }
    catch(...)
    {
        test(false);
    }

    try
    {
        thrower->throwCasA(1, 2, 3);
        test(false);
    }
    catch(const C& ex)
    {
        test(ex.aMem == 1);
        test(ex.bMem == 2);
        test(ex.cMem == 3);
    }
    catch(...)
    {
        test(false);
    }

    try
    {
        thrower->throwCasB(1, 2, 3);
        test(false);
    }
    catch(const C& ex)
    {
        test(ex.aMem == 1);
        test(ex.bMem == 2);
        test(ex.cMem == 3);
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    if(thrower->supportsUndeclaredExceptions())
    {
        cout << "catching unknown user exception... " << flush;

        try
        {
            thrower->throwUndeclaredA(1);
            test(false);
        }
        catch(const Ice::UnknownUserException&)
        {
        }
        catch(const Ice::Exception& ex)
        {
            cout << ex << endl;
            cout << ex.ice_stackTrace() << endl;
            test(false);
        }
        catch(...)
        {
            test(false);
        }

        try
        {
            thrower->throwUndeclaredB(1, 2);
            test(false);
        }
        catch(const Ice::UnknownUserException&)
        {
        }
        catch(...)
        {
            test(false);
        }

        try
        {
            thrower->throwUndeclaredC(1, 2, 3);
            test(false);
        }
        catch(const Ice::UnknownUserException&)
        {
        }
        catch(...)
        {
            test(false);
        }

        cout << "ok" << endl;
    }

    if(thrower->ice_getConnection())
    {
        cout << "testing memory limit marshal exception..." << flush;
        try
        {
            thrower->throwMemoryLimitException(Ice::ByteSeq());
            test(false);
        }
        catch(const Ice::MemoryLimitException&)
        {
        }
        catch(...)
        {
            test(false);
        }

        try
        {
            thrower->throwMemoryLimitException(Ice::ByteSeq(20 * 1024)); // 20KB
            test(false);
        }
        catch(const Ice::ConnectionLostException&)
        {
        }
        catch(const Ice::LocalException& ex)
        {
            cerr << ex << endl;
            test(false);
        }

        ThrowerPrxPtr thrower2 =
            ICE_UNCHECKED_CAST(ThrowerPrx, communicator->stringToProxy("thrower:" + getTestEndpoint(communicator, 1)));
        try
        {
            thrower2->throwMemoryLimitException(Ice::ByteSeq(2 * 1024 * 1024)); // 2MB (no limits)
        }
        catch(const Ice::MemoryLimitException&)
        {
        }
        ThrowerPrxPtr thrower3 =
            ICE_UNCHECKED_CAST(ThrowerPrx, communicator->stringToProxy("thrower:" + getTestEndpoint(communicator, 2)));
        try
        {
            thrower3->throwMemoryLimitException(Ice::ByteSeq(1024)); // 1KB limit
            test(false);
        }
        catch(const Ice::ConnectionLostException&)
        {
        }

        cout << "ok" << endl;
    }

    cout << "catching object not exist exception... " << flush;

    Ice::Identity id = Ice::stringToIdentity("does not exist");
    try
    {
        ThrowerPrxPtr thrower2 = ICE_UNCHECKED_CAST(ThrowerPrx, thrower->ice_identity(id));
        thrower2->throwAasA(1);
//      thrower2->ice_ping();
        test(false);
    }
    catch(const Ice::ObjectNotExistException& ex)
    {
        test(ex.id == id);
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "catching facet not exist exception... " << flush;

    try
    {
#ifdef ICE_CPP11_MAPPING
        ThrowerPrxPtr thrower2 = Ice::uncheckedCast<ThrowerPrx>(thrower, "no such facet");
#else
        ThrowerPrxPtr thrower2 = ThrowerPrx::uncheckedCast(thrower, "no such facet");
#endif
        try
        {
            thrower2->ice_ping();
            test(false);
        }
        catch(const Ice::FacetNotExistException& ex)
        {
            test(ex.facet == "no such facet");
        }
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "catching operation not exist exception... " << flush;

    try
    {
        WrongOperationPrxPtr thrower2 = ICE_UNCHECKED_CAST(WrongOperationPrx, thrower);
        thrower2->noSuchOperation();
        test(false);
    }
    catch(const Ice::OperationNotExistException& ex)
    {
        test(ex.operation == "noSuchOperation");
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "catching unknown local exception... " << flush;

    try
    {
        thrower->throwLocalException();
        test(false);
    }
    catch(const Ice::UnknownLocalException&)
    {
    }
    catch(...)
    {
        test(false);
    }
    try
    {
        thrower->throwLocalExceptionIdempotent();
        test(false);
    }
    catch(const Ice::UnknownLocalException&)
    {
    }
    catch(const Ice::OperationNotExistException&)
    {
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "catching unknown non-Ice exception... " << flush;

    try
    {
        thrower->throwNonIceException();
        test(false);
    }
    catch(const Ice::UnknownException&)
    {
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "testing asynchronous exceptions... " << flush;

    try
    {
        thrower->throwAfterResponse();
    }
    catch(...)
    {
        test(false);
    }

    try
    {
        thrower->throwAfterException();
    }
    catch(const A&)
    {
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "catching exact types with new AMI mapping... " << flush;
#ifdef ICE_CPP11_MAPPING
    {
        auto f = thrower->throwAasAAsync(1);
        try
        {
            f.get();
            test(false);
        }
        catch(const A& ex)
        {
            test(ex.aMem == 1);
        }
        catch(const Ice::Exception&)
        {
            test(false);
        }
        catch(...)
        {
            test(false);
        }
    }
    
    {
        auto f = thrower->throwAorDasAorDAsync(1);
        try
        {
            f.get();
            test(false);
        }
        catch(const A& ex)
        {
            test(ex.aMem == 1);
        }
        catch(...)
        {
            test(false);
        }
    }
    
    {
        auto f = thrower->throwAorDasAorDAsync(-1);
        try
        {
            f.get();
            test(false);
        }
        catch(const D& ex)
        {
            test(ex.dMem == -1);
        }
        catch(...)
        {
            test(false);
        }
    }
    {
        auto f = thrower->throwBasBAsync(1, 2);
        try
        {
            f.get();
            test(false);
        }
        catch(const B& ex)
        {
            test(ex.aMem == 1);
            test(ex.bMem == 2);
        }
        catch(...)
        {
            test(false);
        }
    }
    {
        auto f = thrower->throwCasCAsync(1, 2, 3);
        try
        {
            f.get();
            test(false);
        }
        catch(const C& ex)
        {
            test(ex.aMem == 1);
            test(ex.bMem == 2);
            test(ex.cMem == 3);
        }
        catch(...)
        {
            test(false);
        }
    }
    {
        auto f = thrower->throwModAAsync(1, 2);
        try
        {
            f.get();
        }
        catch(const A& ex)
        {
            test(ex.aMem == 1);
        }
        catch(const Ice::OperationNotExistException&)
        {
            //
            // This operation is not supported in Java.
            //
        }
        catch(...)
        {
            test(false);
        }
    }
    
    //
    // repeat with callback API and no exception callback
    //
    {
        promise<bool> sent;
        thrower->throwAasAAsync(1,
            []()
            {
                test(false);
            },
            nullptr,
            [&](bool value)
            {
                sent.set_value(value);
            });
        sent.get_future().get(); // Wait for sent
    }
    
    {
        promise<bool> sent;
        thrower->throwAorDasAorDAsync(1,
            []()
            {
                test(false);
            },
            nullptr,
            [&](bool value)
            {
                sent.set_value(value);
            });
        sent.get_future().get(); // Wait for sent
    }
    
    {
        promise<bool> sent;
        thrower->throwAorDasAorDAsync(-1,
            []()
            {
                test(false);
            },
            nullptr,
            [&](bool value)
            {
                sent.set_value(value);
            });
        sent.get_future().get(); // Wait for sent
    }

    {
        promise<bool> sent;
        thrower->throwBasBAsync(1, 2,
            []()
            {
                test(false);
            },
            nullptr,
            [&](bool value)
            {
                sent.set_value(value);
            });
        sent.get_future().get(); // Wait for sent
    }

    {
        promise<bool> sent;
        thrower->throwCasCAsync(1, 2, 3,
            []()
            {
                test(false);
            },
            nullptr,
            [&](bool value)
            {
                sent.set_value(value);
            });
        sent.get_future().get(); // Wait for sent
    }

    {
        promise<bool> sent;
        thrower->throwModAAsync(1, 2,
            []()
            {
                test(false);
            },
            nullptr,
            [&](bool value)
            {
                sent.set_value(value);
            });
        sent.get_future().get(); // Wait for sent
    }
#else
    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwAasAPtr callback =
            newCallback_Thrower_throwAasA(cb, &Callback::response, &Callback::exception_AasA);
        thrower->begin_throwAasA(1, callback);
        cb->check();
    }
    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwAorDasAorDPtr callback =
            newCallback_Thrower_throwAorDasAorD(cb, &Callback::response, &Callback::exception_AorDasAorD);
        thrower->begin_throwAorDasAorD(1, callback);
        cb->check();
    }
    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwAorDasAorDPtr callback =
            newCallback_Thrower_throwAorDasAorD(cb, &Callback::response, &Callback::exception_AorDasAorD);
        thrower->begin_throwAorDasAorD(-1, callback);
        cb->check();
    }
    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwBasBPtr callback =
            newCallback_Thrower_throwBasB(cb, &Callback::response, &Callback::exception_BasB);
        thrower->begin_throwBasB(1, 2, callback);
        cb->check();
    }
    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwCasCPtr callback =
            newCallback_Thrower_throwCasC(cb, &Callback::response, &Callback::exception_CasC);
        thrower->begin_throwCasC(1, 2, 3, callback);
        cb->check();
    }
    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwModAPtr callback =
            newCallback_Thrower_throwModA(cb, &Callback::response, &Callback::exception_ModA);
        thrower->begin_throwModA(1, 2, callback);
        cb->check();
    }
#endif
    cout << "ok" << endl;

    cout << "catching derived types with new AMI mapping... " << flush;
#ifdef ICE_CPP11_MAPPING
    {
        auto f = thrower->throwBasAAsync(1, 2);
        try
        {
            f.get();
        }
        catch(const B& ex)
        {
            test(ex.aMem == 1);
            test(ex.bMem == 2);
        }
        catch(...)
        {
            test(false);
        }
    }

    {
        auto f = thrower->throwCasAAsync(1, 2, 3);
        try
        {
            f.get();
        }
        catch(const C& ex)
        {
            test(ex.aMem == 1);
            test(ex.bMem == 2);
            test(ex.cMem == 3);
        }
        catch(...)
        {
            test(false);
        }
    }

    {
        auto f = thrower->throwCasBAsync(1, 2, 3);
        try
        {
            f.get();
        }
        catch(const C& ex)
        {
            test(ex.aMem == 1);
            test(ex.bMem == 2);
            test(ex.cMem == 3);
        }
        catch(...)
        {
            test(false);
        }
    }
#else
    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwBasAPtr callback =
            newCallback_Thrower_throwBasA(cb, &Callback::response, &Callback::exception_BasA);
        thrower->begin_throwBasA(1, 2, callback);
        cb->check();
    }

    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwCasAPtr callback =
            newCallback_Thrower_throwCasA(cb, &Callback::response, &Callback::exception_CasA);
        thrower->begin_throwCasA(1, 2, 3, callback);
        cb->check();
    }

    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwCasBPtr callback =
            newCallback_Thrower_throwCasB(cb, &Callback::response, &Callback::exception_CasB);
        thrower->begin_throwCasB(1, 2, 3, callback);
        cb->check();
    }
#endif
    cout << "ok" << endl;

    if(thrower->supportsUndeclaredExceptions())
    {
        cout << "catching unknown user exception with new AMI mapping... " << flush;
#ifdef ICE_CPP11_MAPPING
        {
            auto f = thrower->throwUndeclaredAAsync(1);
            try
            {
                f.get();
                test(false);
            }
            catch(const Ice::UnknownUserException&)
            {
            }
            catch(const Ice::Exception& ex)
            {
                cout << ex << endl;
                cout << ex.ice_stackTrace() << endl;
                test(false);
            }
            catch(...)
            {
                test(false);
            }
        }

        {
            auto f = thrower->throwUndeclaredBAsync(1, 2);
            try
            {
                f.get();
                test(false);
            }
            catch(const Ice::UnknownUserException&)
            {
            }
            catch(...)
            {
                test(false);
            }
        }

        {
            auto f = thrower->throwUndeclaredCAsync(1, 2, 3);
            try
            {
                f.get();
            }
            catch(const Ice::UnknownUserException&)
            {
            }
            catch(...)
            {
                test(false);
            }
        }
#else
        {
            CallbackPtr cb = new Callback;
            Callback_Thrower_throwUndeclaredAPtr callback =
                newCallback_Thrower_throwUndeclaredA(cb, &Callback::response, &Callback::exception_UndeclaredA);
            thrower->begin_throwUndeclaredA(1, callback);
            cb->check();
        }

        {
            CallbackPtr cb = new Callback;
            Callback_Thrower_throwUndeclaredBPtr callback =
                newCallback_Thrower_throwUndeclaredB(cb, &Callback::response, &Callback::exception_UndeclaredB);
            thrower->begin_throwUndeclaredB(1, 2, callback);
            cb->check();
        }

        {
            CallbackPtr cb = new Callback;
            Callback_Thrower_throwUndeclaredCPtr callback =
                newCallback_Thrower_throwUndeclaredC(cb, &Callback::response, &Callback::exception_UndeclaredC);
            thrower->begin_throwUndeclaredC(1, 2, 3, callback);
            cb->check();
        }
#endif
        cout << "ok" << endl;
    }

    cout << "catching object not exist exception with new AMI mapping... " << flush;

    {
#ifdef ICE_CPP11_MAPPING
        id = Ice::stringToIdentity("does not exist");
        shared_ptr<ThrowerPrx> thrower2 = Ice::uncheckedCast<ThrowerPrx>(thrower->ice_identity(id));
        auto f = thrower2->throwAasAAsync(1);
        try
        {
            f.get();
        }
        catch(const Ice::ObjectNotExistException& ex)
        {
            test(ex.id == id);
        }
        catch(...)
        {
            test(false);
        }
#else
        id = Ice::stringToIdentity("does not exist");
        ThrowerPrx thrower2 = ThrowerPrx::uncheckedCast(thrower->ice_identity(id));
        CallbackPtr cb = new Callback(communicator);
        Callback_Thrower_throwAasAPtr callback =
            newCallback_Thrower_throwAasA(cb, &Callback::response, &Callback::exception_AasAObjectNotExist);
        thrower2->begin_throwAasA(1, callback);
        cb->check();
#endif
    }

    cout << "ok" << endl;

    cout << "catching facet not exist exception with new AMI mapping... " << flush;

    {
#ifdef ICE_CPP11_MAPPING
        shared_ptr<ThrowerPrx> thrower2 = Ice::uncheckedCast<ThrowerPrx>(thrower, "no such facet");
        auto f = thrower2->throwAasAAsync(1);
        try
        {
            f.get();
        }
        catch(const Ice::FacetNotExistException& ex)
        {
            test(ex.facet == "no such facet");
        }
#else
        ThrowerPrx thrower2 = ThrowerPrx::uncheckedCast(thrower, "no such facet");
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwAasAPtr callback =
            newCallback_Thrower_throwAasA(cb, &Callback::response, &Callback::exception_AasAFacetNotExist);
        thrower2->begin_throwAasA(1, callback);
        cb->check();
#endif
    }

    cout << "ok" << endl;

    cout << "catching operation not exist exception with new AMI mapping... " << flush;

    {
#ifdef ICE_CPP11_MAPPING
        shared_ptr<WrongOperationPrx> thrower4 = Ice::uncheckedCast<WrongOperationPrx>(thrower);
        auto f = thrower4->noSuchOperationAsync();
        try
        {
            f.get();
        }
        catch(const Ice::OperationNotExistException& ex)
        {
            test(ex.operation == "noSuchOperation");
        }
        catch(...)
        {
            test(false);
        }
#else
        CallbackPtr cb = new Callback;
        Callback_WrongOperation_noSuchOperationPtr callback =
            newCallback_WrongOperation_noSuchOperation(cb, &Callback::response,
                                                       &Callback::exception_noSuchOperation);
        WrongOperationPrx thrower4 = WrongOperationPrx::uncheckedCast(thrower);
        thrower4->begin_noSuchOperation(callback);
        cb->check();
#endif
    }

    cout << "ok" << endl;

    cout << "catching unknown local exception with new AMI mapping... " << flush;
#ifdef ICE_CPP11_MAPPING
    {
        auto f = thrower->throwLocalExceptionAsync();
        try
        {
            f.get();
            test(false);
        }
        catch(const Ice::UnknownLocalException&)
        {
        }
        catch(...)
        {
            test(false);
        }
    }

    {
        auto f = thrower->throwLocalExceptionIdempotentAsync();
        try
        {
            f.get();
            test(false);
        }
        catch(const Ice::UnknownLocalException&)
        {
        }
        catch(const Ice::OperationNotExistException&)
        {
        }
        catch(...)
        {
            test(false);
        }
    }
#else
    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwLocalExceptionPtr callback =
            newCallback_Thrower_throwLocalException(cb, &Callback::response, &Callback::exception_LocalException);
        thrower->begin_throwLocalException(callback);
        cb->check();
    }

    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwLocalExceptionIdempotentPtr callback =
            newCallback_Thrower_throwLocalExceptionIdempotent(cb, &Callback::response,
                                                              &Callback::exception_LocalException);
        thrower->begin_throwLocalExceptionIdempotent(callback);
        cb->check();
    }
#endif
    cout << "ok" << endl;

    cout << "catching unknown non-Ice exception with new AMI mapping... " << flush;

    {
#ifdef ICE_CPP11_MAPPING
        auto f = thrower->throwNonIceExceptionAsync();
        try
        {
            f.get();
            test(false);
        }
        catch(const Ice::UnknownException&)
        {
        }
        catch(...)
        {
            test(false);
        }

#else
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwNonIceExceptionPtr callback =
            newCallback_Thrower_throwNonIceException(cb, &Callback::response, &Callback::exception_NonIceException);
        thrower->begin_throwNonIceException(callback);
        cb->check();
#endif
    }

    cout << "ok" << endl;

    return thrower;
}
Example #7
0
void
allTests(const Ice::CommunicatorPtr& communicator)
{
    string ref = "communicator:" + getTestEndpoint(communicator, 0);
    RemoteCommunicatorPrxPtr com = ICE_UNCHECKED_CAST(RemoteCommunicatorPrx, communicator->stringToProxy(ref));

    RandomNumberGenerator rng;

    cout << "testing binding with single endpoint... " << flush;
    {
        RemoteObjectAdapterPrxPtr adapter = com->createObjectAdapter("Adapter", "default");

        TestIntfPrxPtr test1 = adapter->getTestIntf();
        TestIntfPrxPtr test2 = adapter->getTestIntf();
        test(test1->ice_getConnection() == test2->ice_getConnection());

        test1->ice_ping();
        test2->ice_ping();

        com->deactivateObjectAdapter(adapter);

        TestIntfPrxPtr test3 = ICE_UNCHECKED_CAST(TestIntfPrx, test1);
        test(test3->ice_getConnection() == test1->ice_getConnection());
        test(test3->ice_getConnection() == test2->ice_getConnection());

        try
        {
            test3->ice_ping();
            test(false);
        }
        catch(const Ice::ConnectFailedException&)
        {
        }
    }
    cout << "ok" << endl;

    cout << "testing binding with multiple endpoints... " << flush;
    {
        vector<RemoteObjectAdapterPrxPtr> adapters;
        adapters.push_back(com->createObjectAdapter("Adapter11", "default"));
        adapters.push_back(com->createObjectAdapter("Adapter12", "default"));
        adapters.push_back(com->createObjectAdapter("Adapter13", "default"));

        //
        // Ensure that when a connection is opened it's reused for new
        // proxies and that all endpoints are eventually tried.
        //
        set<string> names;
        names.insert("Adapter11");
        names.insert("Adapter12");
        names.insert("Adapter13");
        while(!names.empty())
        {
            vector<RemoteObjectAdapterPrxPtr> adpts = adapters;

            TestIntfPrxPtr test1 = createTestIntfPrx(adpts);
            random_shuffle(adpts.begin(), adpts.end(), rng);
            TestIntfPrxPtr test2 = createTestIntfPrx(adpts);
            random_shuffle(adpts.begin(), adpts.end(), rng);
            TestIntfPrxPtr test3 = createTestIntfPrx(adpts);

            test(test1->ice_getConnection() == test2->ice_getConnection());
            test(test2->ice_getConnection() == test3->ice_getConnection());

            names.erase(test1->getAdapterName());
            test1->ice_getConnection()->close(false);
        }

        //
        // Ensure that the proxy correctly caches the connection (we
        // always send the request over the same connection.)
        //
        {
            for(vector<RemoteObjectAdapterPrxPtr>::const_iterator p = adapters.begin(); p != adapters.end(); ++p)
            {
                (*p)->getTestIntf()->ice_ping();
            }

            TestIntfPrxPtr test = createTestIntfPrx(adapters);
            string name = test->getAdapterName();
            const int nRetry = 10;
            int i;
            for(i = 0; i < nRetry &&  test->getAdapterName() == name; i++);
            test(i == nRetry);

            for(vector<RemoteObjectAdapterPrxPtr>::const_iterator q = adapters.begin(); q != adapters.end(); ++q)
            {
                (*q)->getTestIntf()->ice_getConnection()->close(false);
            }
        }

        //
        // Deactivate an adapter and ensure that we can still
        // establish the connection to the remaining adapters.
        //
        com->deactivateObjectAdapter(adapters[0]);
        names.insert("Adapter12");
        names.insert("Adapter13");
        while(!names.empty())
        {
            vector<RemoteObjectAdapterPrxPtr> adpts = adapters;

            TestIntfPrxPtr test1 = createTestIntfPrx(adpts);
            random_shuffle(adpts.begin(), adpts.end(), rng);
            TestIntfPrxPtr test2 = createTestIntfPrx(adpts);
            random_shuffle(adpts.begin(), adpts.end(), rng);
            TestIntfPrxPtr test3 = createTestIntfPrx(adpts);

            test(test1->ice_getConnection() == test2->ice_getConnection());
            test(test2->ice_getConnection() == test3->ice_getConnection());

            names.erase(test1->getAdapterName());
            test1->ice_getConnection()->close(false);
        }

        //
        // Deactivate an adapter and ensure that we can still
        // establish the connection to the remaining adapter.
        //
        com->deactivateObjectAdapter(adapters[2]);
        TestIntfPrxPtr test = createTestIntfPrx(adapters);
        test(test->getAdapterName() == "Adapter12");

        deactivate(com, adapters);
    }
    cout << "ok" << endl;

    cout << "testing binding with multiple random endpoints... " << flush;
    {
        vector<RemoteObjectAdapterPrxPtr> adapters;
        adapters.push_back(com->createObjectAdapter("AdapterRandom11", "default"));
        adapters.push_back(com->createObjectAdapter("AdapterRandom12", "default"));
        adapters.push_back(com->createObjectAdapter("AdapterRandom13", "default"));
        adapters.push_back(com->createObjectAdapter("AdapterRandom14", "default"));
        adapters.push_back(com->createObjectAdapter("AdapterRandom15", "default"));

#ifdef _WIN32
        int count = 60;
#else
        int count = 20;
#endif
        int adapterCount = static_cast<int>(adapters.size());
        while(--count > 0)
        {
#ifdef _WIN32
            if(count == 10)
            {
                com->deactivateObjectAdapter(adapters[4]);
                --adapterCount;
            }
            vector<TestIntfPrxPtr> proxies;
            proxies.resize(10);
#else
            if(count < 60 && count % 10 == 0)
            {
                com->deactivateObjectAdapter(adapters[count / 10 - 1]);
                --adapterCount;
            }
            vector<TestIntfPrxPtr> proxies;
            proxies.resize(40);
#endif
            unsigned int i;
            for(i = 0; i < proxies.size(); ++i)
            {
                vector<RemoteObjectAdapterPrxPtr> adpts;
                adpts.resize(IceUtilInternal::random(static_cast<int>(adapters.size())));
                if(adpts.empty())
                {
                    adpts.resize(1);
                }
                for(vector<RemoteObjectAdapterPrxPtr>::iterator p = adpts.begin(); p != adpts.end(); ++p)
                {
                    *p = adapters[IceUtilInternal::random(static_cast<int>(adapters.size()))];
                }
                proxies[i] = createTestIntfPrx(adpts);
            }

            for(i = 0; i < proxies.size(); i++)
            {
#ifdef ICE_CPP11_MAPPING
                proxies[i]->getAdapterName_async();
#else
                proxies[i]->begin_getAdapterName();
#endif
            }
            for(i = 0; i < proxies.size(); i++)
            {
                try
                {
                    proxies[i]->ice_ping();
                }
                catch(const Ice::LocalException&)
                {
                }
            }
            set<Ice::ConnectionPtr> connections;
            for(i = 0; i < proxies.size(); i++)
            {
                if(proxies[i]->ice_getCachedConnection())
                {
                    connections.insert(proxies[i]->ice_getCachedConnection());
                }
            }
            test(static_cast<int>(connections.size()) <= adapterCount);

            for(vector<RemoteObjectAdapterPrxPtr>::const_iterator q = adapters.begin(); q != adapters.end(); ++q)
            {
                try
                {
                    (*q)->getTestIntf()->ice_getConnection()->close(false);
                }
                catch(const Ice::LocalException&)
                {
                    // Expected if adapter is down.
                }
            }
        }
    }
    cout << "ok" << endl;

    cout << "testing binding with multiple endpoints and AMI... " << flush;
    {
        vector<RemoteObjectAdapterPrxPtr> adapters;
        adapters.push_back(com->createObjectAdapter("AdapterAMI11", "default"));
        adapters.push_back(com->createObjectAdapter("AdapterAMI12", "default"));
        adapters.push_back(com->createObjectAdapter("AdapterAMI13", "default"));

        //
        // Ensure that when a connection is opened it's reused for new
        // proxies and that all endpoints are eventually tried.
        //
        set<string> names;
        names.insert("AdapterAMI11");
        names.insert("AdapterAMI12");
        names.insert("AdapterAMI13");
        while(!names.empty())
        {
            vector<RemoteObjectAdapterPrxPtr> adpts = adapters;

            TestIntfPrxPtr test1 = createTestIntfPrx(adpts);
            random_shuffle(adpts.begin(), adpts.end(), rng);
            TestIntfPrxPtr test2 = createTestIntfPrx(adpts);
            random_shuffle(adpts.begin(), adpts.end(), rng);
            TestIntfPrxPtr test3 = createTestIntfPrx(adpts);

            test(test1->ice_getConnection() == test2->ice_getConnection());
            test(test2->ice_getConnection() == test3->ice_getConnection());

            names.erase(getAdapterNameWithAMI(test1));
            test1->ice_getConnection()->close(false);
        }

        //
        // Ensure that the proxy correctly caches the connection (we
        // always send the request over the same connection.)
        //
        {
            for(vector<RemoteObjectAdapterPrxPtr>::const_iterator p = adapters.begin(); p != adapters.end(); ++p)
            {
                (*p)->getTestIntf()->ice_ping();
            }

            TestIntfPrxPtr test = createTestIntfPrx(adapters);
            string name = getAdapterNameWithAMI(test);
            const int nRetry = 10;
            int i;
            for(i = 0; i < nRetry && getAdapterNameWithAMI(test) == name; i++);
            test(i == nRetry);

            for(vector<RemoteObjectAdapterPrxPtr>::const_iterator q = adapters.begin(); q != adapters.end(); ++q)
            {
                (*q)->getTestIntf()->ice_getConnection()->close(false);
            }
        }

        //
        // Deactivate an adapter and ensure that we can still
        // establish the connection to the remaining adapters.
        //
        com->deactivateObjectAdapter(adapters[0]);
        names.insert("AdapterAMI12");
        names.insert("AdapterAMI13");
        while(!names.empty())
        {
            vector<RemoteObjectAdapterPrxPtr> adpts = adapters;

            TestIntfPrxPtr test1 = createTestIntfPrx(adpts);
            random_shuffle(adpts.begin(), adpts.end(), rng);
            TestIntfPrxPtr test2 = createTestIntfPrx(adpts);
            random_shuffle(adpts.begin(), adpts.end(), rng);
            TestIntfPrxPtr test3 = createTestIntfPrx(adpts);

            test(test1->ice_getConnection() == test2->ice_getConnection());
            test(test2->ice_getConnection() == test3->ice_getConnection());

            names.erase(test1->getAdapterName());
            test1->ice_getConnection()->close(false);
        }

        //
        // Deactivate an adapter and ensure that we can still
        // establish the connection to the remaining adapter.
        //
        com->deactivateObjectAdapter(adapters[2]);
        TestIntfPrxPtr test = createTestIntfPrx(adapters);
        test(test->getAdapterName() == "AdapterAMI12");

        deactivate(com, adapters);
    }
    cout << "ok" << endl;

    cout << "testing random endpoint selection... " << flush;
    {
        vector<RemoteObjectAdapterPrxPtr> adapters;
        adapters.push_back(com->createObjectAdapter("Adapter21", "default"));
        adapters.push_back(com->createObjectAdapter("Adapter22", "default"));
        adapters.push_back(com->createObjectAdapter("Adapter23", "default"));

        TestIntfPrxPtr test = createTestIntfPrx(adapters);
        test(test->ice_getEndpointSelection() == Ice::Random);

        set<string> names;
        names.insert("Adapter21");
        names.insert("Adapter22");
        names.insert("Adapter23");
        while(!names.empty())
        {
            names.erase(test->getAdapterName());
            test->ice_getConnection()->close(false);
        }

        test = ICE_UNCHECKED_CAST(TestIntfPrx, test->ice_endpointSelection(Ice::Random));
        test(test->ice_getEndpointSelection() == Ice::Random);

        names.insert("Adapter21");
        names.insert("Adapter22");
        names.insert("Adapter23");
        while(!names.empty())
        {
            names.erase(test->getAdapterName());
            test->ice_getConnection()->close(false);
        }

        deactivate(com, adapters);
    }
    cout << "ok" << endl;

    cout << "testing ordered endpoint selection... " << flush;
    {
        vector<RemoteObjectAdapterPrxPtr> adapters;
        adapters.push_back(com->createObjectAdapter("Adapter31", "default"));
        adapters.push_back(com->createObjectAdapter("Adapter32", "default"));
        adapters.push_back(com->createObjectAdapter("Adapter33", "default"));

        TestIntfPrxPtr test = createTestIntfPrx(adapters);
        test = ICE_UNCHECKED_CAST(TestIntfPrx, test->ice_endpointSelection(Ice::Ordered));
        test(test->ice_getEndpointSelection() == Ice::Ordered);
        const int nRetry = 5;
        int i;

        //
        // Ensure that endpoints are tried in order by deactiving the adapters
        // one after the other.
        //
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter31"; i++);
#if TARGET_OS_IPHONE > 0
        if(i != nRetry)
        {
            test->ice_getConnection()->close(false);
            for(i = 0; i < nRetry && test->getAdapterName() == "Adapter31"; i++);
        }
#endif
        test(i == nRetry);
        com->deactivateObjectAdapter(adapters[0]);
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter32"; i++);
#if TARGET_OS_IPHONE > 0
        if(i != nRetry)
        {
            test->ice_getConnection()->close(false);
            for(i = 0; i < nRetry && test->getAdapterName() == "Adapter32"; i++);
        }
#endif
        test(i == nRetry);
        com->deactivateObjectAdapter(adapters[1]);
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter33"; i++);
#if TARGET_OS_IPHONE > 0
        if(i != nRetry)
        {
            test->ice_getConnection()->close(false);
            for(i = 0; i < nRetry && test->getAdapterName() == "Adapter33"; i++);
        }
#endif
        test(i == nRetry);
        com->deactivateObjectAdapter(adapters[2]);

        try
        {
            test->getAdapterName();
        }
        catch(const Ice::ConnectFailedException&)
        {
        }

        Ice::EndpointSeq endpoints = test->ice_getEndpoints();

        adapters.clear();

        //
        // Now, re-activate the adapters with the same endpoints in the opposite
        // order.
        //
        adapters.push_back(com->createObjectAdapter("Adapter36", endpoints[2]->toString()));
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter36"; i++);
#if TARGET_OS_IPHONE > 0
        if(i != nRetry)
        {
            test->ice_getConnection()->close(false);
            for(i = 0; i < nRetry && test->getAdapterName() == "Adapter36"; i++);
        }
#endif
        test(i == nRetry);
        test->ice_getConnection()->close(false);
        adapters.push_back(com->createObjectAdapter("Adapter35", endpoints[1]->toString()));
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter35"; i++);
#if TARGET_OS_IPHONE > 0
        if(i != nRetry)
        {
            test->ice_getConnection()->close(false);
            for(i = 0; i < nRetry && test->getAdapterName() == "Adapter35"; i++);
        }
#endif
        test(i == nRetry);
        test->ice_getConnection()->close(false);
        adapters.push_back(com->createObjectAdapter("Adapter34", endpoints[0]->toString()));
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter34"; i++);
#if TARGET_OS_IPHONE > 0
        if(i != nRetry)
        {
            test->ice_getConnection()->close(false);
            for(i = 0; i < nRetry && test->getAdapterName() == "Adapter34"; i++);
        }
#endif
        test(i == nRetry);

        deactivate(com, adapters);
    }
    cout << "ok" << endl;

    cout << "testing per request binding with single endpoint... " << flush;
    {
        RemoteObjectAdapterPrxPtr adapter = com->createObjectAdapter("Adapter41", "default");

        TestIntfPrxPtr test1 = ICE_UNCHECKED_CAST(TestIntfPrx, adapter->getTestIntf()->ice_connectionCached(false));
        TestIntfPrxPtr test2 = ICE_UNCHECKED_CAST(TestIntfPrx, adapter->getTestIntf()->ice_connectionCached(false));
        test(!test1->ice_isConnectionCached());
        test(!test2->ice_isConnectionCached());
        test(test1->ice_getConnection() == test2->ice_getConnection());

        test1->ice_ping();

        com->deactivateObjectAdapter(adapter);

        TestIntfPrxPtr test3 = ICE_UNCHECKED_CAST(TestIntfPrx, test1);
        try
        {
            test(test3->ice_getConnection() == test1->ice_getConnection());
            test(false);
        }
        catch(const Ice::ConnectFailedException&)
        {
        }
    }
    cout << "ok" << endl;

    cout << "testing per request binding with multiple endpoints... " << flush;
    {
        vector<RemoteObjectAdapterPrxPtr> adapters;
        adapters.push_back(com->createObjectAdapter("Adapter51", "default"));
        adapters.push_back(com->createObjectAdapter("Adapter52", "default"));
        adapters.push_back(com->createObjectAdapter("Adapter53", "default"));

        TestIntfPrxPtr test = ICE_UNCHECKED_CAST(TestIntfPrx, createTestIntfPrx(adapters)->ice_connectionCached(false));
        test(!test->ice_isConnectionCached());

        set<string> names;
        names.insert("Adapter51");
        names.insert("Adapter52");
        names.insert("Adapter53");
        while(!names.empty())
        {
            names.erase(test->getAdapterName());
        }

        com->deactivateObjectAdapter(adapters[0]);

        names.insert("Adapter52");
        names.insert("Adapter53");
        while(!names.empty())
        {
            names.erase(test->getAdapterName());
        }

        com->deactivateObjectAdapter(adapters[2]);

        test(test->getAdapterName() == "Adapter52");

        deactivate(com, adapters);
    }
    cout << "ok" << endl;

    cout << "testing per request binding with multiple endpoints and AMI... " << flush;
    {
        vector<RemoteObjectAdapterPrxPtr> adapters;
        adapters.push_back(com->createObjectAdapter("AdapterAMI51", "default"));
        adapters.push_back(com->createObjectAdapter("AdapterAMI52", "default"));
        adapters.push_back(com->createObjectAdapter("AdapterAMI53", "default"));

        TestIntfPrxPtr test = ICE_UNCHECKED_CAST(TestIntfPrx, createTestIntfPrx(adapters)->ice_connectionCached(false));
        test(!test->ice_isConnectionCached());

        set<string> names;
        names.insert("AdapterAMI51");
        names.insert("AdapterAMI52");
        names.insert("AdapterAMI53");
        while(!names.empty())
        {
            names.erase(getAdapterNameWithAMI(test));
        }

        com->deactivateObjectAdapter(adapters[0]);

        names.insert("AdapterAMI52");
        names.insert("AdapterAMI53");
        while(!names.empty())
        {
            names.erase(getAdapterNameWithAMI(test));
        }

        com->deactivateObjectAdapter(adapters[2]);

        test(test->getAdapterName() == "AdapterAMI52");

        deactivate(com, adapters);
    }
    cout << "ok" << endl;

    cout << "testing per request binding and ordered endpoint selection... " << flush;
    {
        vector<RemoteObjectAdapterPrxPtr> adapters;
        adapters.push_back(com->createObjectAdapter("Adapter61", "default"));
        adapters.push_back(com->createObjectAdapter("Adapter62", "default"));
        adapters.push_back(com->createObjectAdapter("Adapter63", "default"));

        TestIntfPrxPtr test = createTestIntfPrx(adapters);
        test = ICE_UNCHECKED_CAST(TestIntfPrx, test->ice_endpointSelection(Ice::Ordered));
        test(test->ice_getEndpointSelection() == Ice::Ordered);
        test = ICE_UNCHECKED_CAST(TestIntfPrx, test->ice_connectionCached(false));
        test(!test->ice_isConnectionCached());
        const int nRetry = 5;
        int i;

        //
        // Ensure that endpoints are tried in order by deactiving the adapters
        // one after the other.
        //
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter61"; i++);
#if TARGET_OS_IPHONE > 0
        test(i >= nRetry - 1); // WORKAROUND: for connection establishment hang.
#else
        test(i == nRetry);
#endif
        com->deactivateObjectAdapter(adapters[0]);
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter62"; i++);
#if TARGET_OS_IPHONE > 0
        test(i >= nRetry - 1); // WORKAROUND: for connection establishment hang.
#else
        test(i == nRetry);
#endif
        com->deactivateObjectAdapter(adapters[1]);
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter63"; i++);
#if TARGET_OS_IPHONE > 0
        test(i >= nRetry - 1); // WORKAROUND: for connection establishment hang.
#else
        test(i == nRetry);
#endif
        com->deactivateObjectAdapter(adapters[2]);

        try
        {
            test->getAdapterName();
        }
        catch(const Ice::ConnectFailedException&)
        {
        }

        Ice::EndpointSeq endpoints = test->ice_getEndpoints();

        adapters.clear();

        //
        // Now, re-activate the adapters with the same endpoints in the opposite
        // order.
        //
        adapters.push_back(com->createObjectAdapter("Adapter66", endpoints[2]->toString()));
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter66"; i++);
#if TARGET_OS_IPHONE > 0
        test(i >= nRetry - 1); // WORKAROUND: for connection establishment hang.
#else
        test(i == nRetry);
#endif
        adapters.push_back(com->createObjectAdapter("Adapter65", endpoints[1]->toString()));
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter65"; i++);
#if TARGET_OS_IPHONE > 0
        test(i >= nRetry - 1); // WORKAROUND: for connection establishment hang.
#else
        test(i == nRetry);
#endif
        adapters.push_back(com->createObjectAdapter("Adapter64", endpoints[0]->toString()));
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter64"; i++);
#if TARGET_OS_IPHONE > 0
        test(i >= nRetry - 1); // WORKAROUND: for connection establishment hang.
#else
        test(i == nRetry);
#endif

        deactivate(com, adapters);
    }
    cout << "ok" << endl;

    cout << "testing per request binding and ordered endpoint selection and AMI... " << flush;
    {
        vector<RemoteObjectAdapterPrxPtr> adapters;
        adapters.push_back(com->createObjectAdapter("AdapterAMI61", "default"));
        adapters.push_back(com->createObjectAdapter("AdapterAMI62", "default"));
        adapters.push_back(com->createObjectAdapter("AdapterAMI63", "default"));

        TestIntfPrxPtr test = createTestIntfPrx(adapters);
        test = ICE_UNCHECKED_CAST(TestIntfPrx, test->ice_endpointSelection(Ice::Ordered));
        test(test->ice_getEndpointSelection() == Ice::Ordered);
        test = ICE_UNCHECKED_CAST(TestIntfPrx, test->ice_connectionCached(false));
        test(!test->ice_isConnectionCached());
        const int nRetry = 5;
        int i;

        //
        // Ensure that endpoints are tried in order by deactiving the adapters
        // one after the other.
        //
        for(i = 0; i < nRetry && getAdapterNameWithAMI(test) == "AdapterAMI61"; i++);
#if TARGET_OS_IPHONE > 0
        test(i >= nRetry - 1); // WORKAROUND: for connection establishment hang.
#else
        test(i == nRetry);
#endif
        com->deactivateObjectAdapter(adapters[0]);
        for(i = 0; i < nRetry && getAdapterNameWithAMI(test) == "AdapterAMI62"; i++);
#if TARGET_OS_IPHONE > 0
        test(i >= nRetry - 1); // WORKAROUND: for connection establishment hang.
#else
        test(i == nRetry);
#endif
        com->deactivateObjectAdapter(adapters[1]);
        for(i = 0; i < nRetry && getAdapterNameWithAMI(test) == "AdapterAMI63"; i++);
#if TARGET_OS_IPHONE > 0
        test(i >= nRetry - 1); // WORKAROUND: for connection establishment hang.
#else
        test(i == nRetry);
#endif
        com->deactivateObjectAdapter(adapters[2]);

        try
        {
            test->getAdapterName();
        }
        catch(const Ice::ConnectFailedException&)
        {
        }

        Ice::EndpointSeq endpoints = test->ice_getEndpoints();

        adapters.clear();

        //
        // Now, re-activate the adapters with the same endpoints in the opposite
        // order.
        //
        adapters.push_back(com->createObjectAdapter("AdapterAMI66", endpoints[2]->toString()));
        for(i = 0; i < nRetry && getAdapterNameWithAMI(test) == "AdapterAMI66"; i++);
#if TARGET_OS_IPHONE > 0
        test(i >= nRetry - 1); // WORKAROUND: for connection establishment hang.
#else
        test(i == nRetry);
#endif
        adapters.push_back(com->createObjectAdapter("AdapterAMI65", endpoints[1]->toString()));
        for(i = 0; i < nRetry && getAdapterNameWithAMI(test) == "AdapterAMI65"; i++);
        test(i == nRetry);
        adapters.push_back(com->createObjectAdapter("AdapterAMI64", endpoints[0]->toString()));
        for(i = 0; i < nRetry && getAdapterNameWithAMI(test) == "AdapterAMI64"; i++);
        test(i == nRetry);

        deactivate(com, adapters);
    }
    cout << "ok" << endl;

    cout << "testing endpoint mode filtering... " << flush;
    {
        vector<RemoteObjectAdapterPrxPtr> adapters;
        adapters.push_back(com->createObjectAdapter("Adapter71", "default"));
        adapters.push_back(com->createObjectAdapter("Adapter72", "udp"));

        TestIntfPrxPtr test = createTestIntfPrx(adapters);
        test(test->getAdapterName() == "Adapter71");

        TestIntfPrxPtr testUDP = ICE_UNCHECKED_CAST(TestIntfPrx, test->ice_datagram());
        test(test->ice_getConnection() != testUDP->ice_getConnection());
        try
        {
            testUDP->getAdapterName();
        }
        catch(const Ice::TwowayOnlyException&)
        {
        }
        catch(const IceUtil::IllegalArgumentException&)
        {
        }
    }
    cout << "ok" << endl;

    if(!communicator->getProperties()->getProperty("Ice.Plugin.IceSSL").empty() &&
            communicator->getProperties()->getProperty("Ice.Default.Protocol") == "ssl")
    {
        cout << "testing unsecure vs. secure endpoints... " << flush;
        {
            vector<RemoteObjectAdapterPrxPtr> adapters;
            adapters.push_back(com->createObjectAdapter("Adapter81", "ssl"));
            adapters.push_back(com->createObjectAdapter("Adapter82", "tcp"));

            TestIntfPrxPtr test = createTestIntfPrx(adapters);
            int i;
            for(i = 0; i < 5; i++)
            {
                test(test->getAdapterName() == "Adapter82");
                test->ice_getConnection()->close(false);
            }

            TestIntfPrxPtr testSecure = ICE_UNCHECKED_CAST(TestIntfPrx, test->ice_secure(true));
            test(testSecure->ice_isSecure());
            testSecure = ICE_UNCHECKED_CAST(TestIntfPrx, test->ice_secure(false));
            test(!testSecure->ice_isSecure());
            testSecure = ICE_UNCHECKED_CAST(TestIntfPrx, test->ice_secure(true));
            test(testSecure->ice_isSecure());
            test(test->ice_getConnection() != testSecure->ice_getConnection());

            com->deactivateObjectAdapter(adapters[1]);

            for(i = 0; i < 5; i++)
            {
                test(test->getAdapterName() == "Adapter81");
                test->ice_getConnection()->close(false);
            }

            com->createObjectAdapter("Adapter83", (test->ice_getEndpoints()[1])->toString()); // Reactive tcp OA.

            for(i = 0; i < 5; i++)
            {
                test(test->getAdapterName() == "Adapter83");
                test->ice_getConnection()->close(false);
            }

            com->deactivateObjectAdapter(adapters[0]);
            try
            {
                testSecure->ice_ping();
                test(false);
            }
            catch(const Ice::ConnectFailedException&)
            {
            }

            deactivate(com, adapters);
        }
        cout << "ok" << endl;
    }

    {
        cout << "testing ipv4 & ipv6 connections... " << flush;

        Ice::PropertiesPtr ipv4 = Ice::createProperties();
        ipv4->setProperty("Ice.IPv4", "1");
        ipv4->setProperty("Ice.IPv6", "0");
        ipv4->setProperty("Adapter.Endpoints", "tcp -h localhost");

        Ice::PropertiesPtr ipv6 = Ice::createProperties();
        ipv6->setProperty("Ice.IPv4", "0");
        ipv6->setProperty("Ice.IPv6", "1");
        ipv6->setProperty("Adapter.Endpoints", "tcp -h localhost");

        Ice::PropertiesPtr bothPreferIPv4 = Ice::createProperties();
        bothPreferIPv4->setProperty("Ice.IPv4", "1");
        bothPreferIPv4->setProperty("Ice.IPv6", "1");
        bothPreferIPv4->setProperty("Ice.PreferIPv6Address", "0");
        bothPreferIPv4->setProperty("Adapter.Endpoints", "tcp -h localhost");

        Ice::PropertiesPtr bothPreferIPv6 = Ice::createProperties();
        bothPreferIPv6->setProperty("Ice.IPv4", "1");
        bothPreferIPv6->setProperty("Ice.IPv6", "1");
        bothPreferIPv6->setProperty("Ice.PreferIPv6Address", "1");
        bothPreferIPv6->setProperty("Adapter.Endpoints", "tcp -h localhost");

        vector<Ice::PropertiesPtr> clientProps;
        clientProps.push_back(ipv4);
        clientProps.push_back(ipv6);
        clientProps.push_back(bothPreferIPv4);
        clientProps.push_back(bothPreferIPv6);

        Ice::PropertiesPtr anyipv4 = ipv4->clone();
        anyipv4->setProperty("Adapter.Endpoints", "tcp -p 12012");
        anyipv4->setProperty("Adapter.PublishedEndpoints", "tcp -h 127.0.0.1 -p 12012");

        Ice::PropertiesPtr anyipv6 = ipv6->clone();
        anyipv6->setProperty("Adapter.Endpoints", "tcp -p 12012");
        anyipv6->setProperty("Adapter.PublishedEndpoints", "tcp -h \"::1\" -p 12012");

        Ice::PropertiesPtr anyboth = Ice::createProperties();
        anyboth->setProperty("Ice.IPv4", "1");
        anyboth->setProperty("Ice.IPv6", "1");
        anyboth->setProperty("Adapter.Endpoints", "tcp -p 12012");
        anyboth->setProperty("Adapter.PublishedEndpoints", "tcp -h \"::1\" -p 12012:tcp -h 127.0.0.1 -p 12012");

        Ice::PropertiesPtr localipv4 = ipv4->clone();
        localipv4->setProperty("Adapter.Endpoints", "tcp -h 127.0.0.1");

        Ice::PropertiesPtr localipv6 = ipv6->clone();
        localipv6->setProperty("Adapter.Endpoints", "tcp -h \"::1\"");

        vector<Ice::PropertiesPtr> serverProps = clientProps;
        serverProps.push_back(anyipv4);
        serverProps.push_back(anyipv6);
        serverProps.push_back(anyboth);
        serverProps.push_back(localipv4);
        serverProps.push_back(localipv6);

#if defined(_WIN32) && !defined(ICE_OS_WINRT)
        OSVERSIONINFO ver;
        ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
#  if defined(_MSC_VER) && _MSC_VER >= 1800
#    pragma warning (disable : 4996)
#  endif
        GetVersionEx(&ver);
#  if defined(_MSC_VER) && _MSC_VER >= 1800
#    pragma warning (default : 4996)
#  endif
        const bool dualStack = ver.dwMajorVersion >= 6; // Windows XP IPv6 doesn't support dual-stack
#else
        const bool dualStack = true;
#endif

        bool ipv6NotSupported = false;
        for(vector<Ice::PropertiesPtr>::const_iterator p = serverProps.begin(); p != serverProps.end(); ++p)
        {
            Ice::InitializationData serverInitData;
            serverInitData.properties = *p;
            Ice::CommunicatorPtr serverCommunicator = Ice::initialize(serverInitData);
            Ice::ObjectAdapterPtr oa;
            try
            {
                oa = serverCommunicator->createObjectAdapter("Adapter");
                oa->activate();
            }
            catch(const Ice::DNSException&)
            {
                serverCommunicator->destroy();
                continue; // IP version not supported.
            }
            catch(const Ice::SocketException&)
            {
                if(*p == ipv6)
                {
                    ipv6NotSupported = true;
                }
                serverCommunicator->destroy();
                continue; // IP version not supported.
            }

            // Ensure the published endpoints are actually valid. On
            // Fedora, binding to "localhost" with IPv6 only works but
            // resolving localhost don't return the IPv6 adress.
            Ice::ObjectPrxPtr prx = oa->createProxy(serverCommunicator->stringToIdentity("dummy"));
            try
            {
                prx->ice_collocationOptimized(false)->ice_ping();
            }
            catch(const Ice::LocalException&)
            {
                serverCommunicator->destroy();
                continue; // IP version not supported.
            }

            string strPrx = prx->ice_toString();
            for(vector<Ice::PropertiesPtr>::const_iterator q = clientProps.begin(); q != clientProps.end(); ++q)
            {
                Ice::InitializationData clientInitData;
                clientInitData.properties = *q;
                Ice::CommunicatorHolder clientCommunicator = Ice::initialize(clientInitData);
                Ice::ObjectPrxPtr prx = clientCommunicator->stringToProxy(strPrx);
                try
                {
                    prx->ice_ping();
                    test(false);
                }
                catch(const Ice::ObjectNotExistException&)
                {
                    // Expected, no object registered.
                }
                catch(const Ice::DNSException&)
                {
                    // Expected if no IPv4 or IPv6 address is
                    // associated to localhost or if trying to connect
                    // to an any endpoint with the wrong IP version,
                    // e.g.: resolving an IPv4 address when only IPv6
                    // is enabled fails with a DNS exception.
                }
                catch(const Ice::SocketException&)
                {
                    test((*p == ipv4 && *q == ipv6) || (*p == ipv6 && *q == ipv4) ||
                         (*p == bothPreferIPv4 && *q == ipv6) || (*p == bothPreferIPv6 && *q == ipv4) ||
                         (*p == bothPreferIPv6 && *q == ipv6 && ipv6NotSupported) ||
                         (*p == anyipv4 && *q == ipv6) || (*p == anyipv6 && *q == ipv4) ||
                         (*p == anyboth && *q == ipv4 && !dualStack) ||
                         (*p == localipv4 && *q == ipv6) || (*p == localipv6 && *q == ipv4) ||
                         (*p == ipv6 && *q == bothPreferIPv4) || (*p == ipv6 && *q == bothPreferIPv6) ||
                         (*p == bothPreferIPv6 && *q == ipv6));
                }
            }
            serverCommunicator->destroy();
        }

        cout << "ok" << endl;
    }

    com->shutdown();
}
Example #8
0
NodeObserverTopic::NodeObserverTopic(const IceStorm::TopicManagerPrx& topicManager, 
                                     const Ice::ObjectAdapterPtr& adapter) : 
    ObserverTopic(topicManager, "NodeObserver")
{
    _publishers = getPublishers<NodeObserverPrx>();
    try
    {
        const_cast<NodeObserverPrx&>(_externalPublisher) = NodeObserverPrx::uncheckedCast(adapter->addWithUUID(this));
    }
    catch(const Ice::LocalException&)
    {
    }
}
Example #9
0
void
allTests(const Ice::CommunicatorPtr& communicator)
{
    {
        cout << "Testing Glacier2 stub... " << flush;
        char** argv = 0;
        int argc = 0;
        SessionHelperClient client;
        client.run(argc, argv);
        cout << "ok" << endl;
    }

    {
        cout << "Testing IceStorm stub... " << flush;
        IceStorm::TopicManagerPrx manager =
                    IceStorm::TopicManagerPrx::uncheckedCast(communicator->stringToProxy("test:default -p 12010"));

        IceStorm::QoS qos;
        IceStorm::TopicPrx topic;
        string topicName = "time";

        try
        {
            topic = manager->retrieve(topicName);
            test(false);
        }
        catch(const IceStorm::NoSuchTopic&)
        {
            test(false);
        }
        catch(const Ice::LocalException&)
        {
        }

        Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("subscriber" ,"tcp");
        Ice::ObjectPrx subscriber = adapter->addWithUUID(new ClockI);
        adapter->activate();
        try
        {
            topic->subscribeAndGetPublisher(qos, subscriber);
            test(false);
        }
        catch(const IceStorm::AlreadySubscribed&)
        {
            test(false);
        }
        catch(const IceUtil::NullHandleException&)
        {
        }
        cout << "ok" << endl;
    }

    {
        cout << "Testing IceGrid stub... " << flush;

        Ice::ObjectPrx base = communicator->stringToProxy("test:default -p 12010");
        IceGrid::RegistryPrx registry = IceGrid::RegistryPrx::uncheckedCast(base);
        IceGrid::AdminSessionPrx session;
        IceGrid::AdminPrx admin;
        try
        {
            session = registry->createAdminSession("username", "password");
            test(false);
        }
        catch(const IceGrid::PermissionDeniedException&)
        {
            test(false);
        }
        catch(const Ice::LocalException&)
        {
        }

        try
        {
            admin = session->getAdmin();
            test(false);
        }
        catch(const IceUtil::NullHandleException&)
        {
        }
        cout << "ok" << endl;
    }
}
Example #10
0
int ::chocon::run(int argc, char* argv[])
{
	QCoreApplication a(argc, argv);  // NON-GUI application


	sigset_t sigs;
	sigemptyset(&sigs);
	sigaddset(&sigs, SIGHUP);
	sigaddset(&sigs, SIGINT);
	sigaddset(&sigs, SIGTERM);
	sigprocmask(SIG_UNBLOCK, &sigs, 0);



	int status=EXIT_SUCCESS;

	DifferentialRobotPrx differentialrobot_proxy;
	LaserPrx laser_proxy;

	string proxy, tmp;
	initialize();


	try
	{
		if (not GenericMonitor::configGetString(communicator(), prefix, "DifferentialRobotProxy", proxy, ""))
		{
			cout << "[" << PROGRAM_NAME << "]: Can't read configuration for proxy DifferentialRobotProxy\n";
		}
		differentialrobot_proxy = DifferentialRobotPrx::uncheckedCast( communicator()->stringToProxy( proxy ) );
	}
	catch(const Ice::Exception& ex)
	{
		cout << "[" << PROGRAM_NAME << "]: Exception: " << ex;
		return EXIT_FAILURE;
	}
	rInfo("DifferentialRobotProxy initialized Ok!");
	mprx["DifferentialRobotProxy"] = (::IceProxy::Ice::Object*)(&differentialrobot_proxy);//Remote server proxy creation example


	try
	{
		if (not GenericMonitor::configGetString(communicator(), prefix, "LaserProxy", proxy, ""))
		{
			cout << "[" << PROGRAM_NAME << "]: Can't read configuration for proxy LaserProxy\n";
		}
		laser_proxy = LaserPrx::uncheckedCast( communicator()->stringToProxy( proxy ) );
	}
	catch(const Ice::Exception& ex)
	{
		cout << "[" << PROGRAM_NAME << "]: Exception: " << ex;
		return EXIT_FAILURE;
	}
	rInfo("LaserProxy initialized Ok!");
	mprx["LaserProxy"] = (::IceProxy::Ice::Object*)(&laser_proxy);//Remote server proxy creation example

	IceStorm::TopicManagerPrx topicManager = IceStorm::TopicManagerPrx::checkedCast(communicator()->propertyToProxy("TopicManager.Proxy"));


	SpecificWorker *worker = new SpecificWorker(mprx);
	//Monitor thread
	SpecificMonitor *monitor = new SpecificMonitor(worker,communicator());
	QObject::connect(monitor, SIGNAL(kill()), &a, SLOT(quit()));
	QObject::connect(worker, SIGNAL(kill()), &a, SLOT(quit()));
	monitor->start();

	if ( !monitor->isRunning() )
		return status;
	
	while (!monitor->ready)
	{
		usleep(10000);
	}
	
	try
	{
		// Server adapter creation and publication
		if (not GenericMonitor::configGetString(communicator(), prefix, "CommonBehavior.Endpoints", tmp, ""))
		{
			cout << "[" << PROGRAM_NAME << "]: Can't read configuration for proxy CommonBehavior\n";
		}
		Ice::ObjectAdapterPtr adapterCommonBehavior = communicator()->createObjectAdapterWithEndpoints("commonbehavior", tmp);
		CommonBehaviorI *commonbehaviorI = new CommonBehaviorI(monitor );
		adapterCommonBehavior->add(commonbehaviorI, communicator()->stringToIdentity("commonbehavior"));
		adapterCommonBehavior->activate();




		// Server adapter creation and publication
		if (not GenericMonitor::configGetString(communicator(), prefix, "IrObjetivo.Endpoints", tmp, ""))
		{
			cout << "[" << PROGRAM_NAME << "]: Can't read configuration for proxy IrObjetivo";
		}
		Ice::ObjectAdapterPtr adapterIrObjetivo = communicator()->createObjectAdapterWithEndpoints("IrObjetivo", tmp);
		IrObjetivoI *irobjetivo = new IrObjetivoI(worker);
		adapterIrObjetivo->add(irobjetivo, communicator()->stringToIdentity("irobjetivo"));
		adapterIrObjetivo->activate();
		cout << "[" << PROGRAM_NAME << "]: IrObjetivo adapter created in port " << tmp << endl;





		// Server adapter creation and publication
		if (not GenericMonitor::configGetString(communicator(), prefix, "RCISMousePickerTopic.Endpoints", tmp, ""))
		{
			cout << "[" << PROGRAM_NAME << "]: Can't read configuration for proxy RCISMousePickerProxy";
		}
		Ice::ObjectAdapterPtr RCISMousePicker_adapter = communicator()->createObjectAdapterWithEndpoints("rcismousepicker", tmp);
		RCISMousePickerPtr rcismousepickerI_ = new RCISMousePickerI(worker);
		Ice::ObjectPrx rcismousepicker = RCISMousePicker_adapter->addWithUUID(rcismousepickerI_)->ice_oneway();
		IceStorm::TopicPrx rcismousepicker_topic;
		if(!rcismousepicker_topic){
		try {
			rcismousepicker_topic = topicManager->create("RCISMousePicker");
		}
		catch (const IceStorm::TopicExists&) {
		//Another client created the topic
		try{
			rcismousepicker_topic = topicManager->retrieve("RCISMousePicker");
		}
		catch(const IceStorm::NoSuchTopic&)
		{
			//Error. Topic does not exist
			}
		}
		IceStorm::QoS qos;
		rcismousepicker_topic->subscribeAndGetPublisher(qos, rcismousepicker);
		}
		RCISMousePicker_adapter->activate();

		// Server adapter creation and publication
		cout << SERVER_FULL_NAME " started" << endl;

		// User defined QtGui elements ( main window, dialogs, etc )

#ifdef USE_QTGUI
		//ignoreInterrupt(); // Uncomment if you want the component to ignore console SIGINT signal (ctrl+c).
		a.setQuitOnLastWindowClosed( true );
#endif
		// Run QT Application Event Loop
		a.exec();
		status = EXIT_SUCCESS;
	}
	catch(const Ice::Exception& ex)
	{
		status = EXIT_FAILURE;

		cout << "[" << PROGRAM_NAME << "]: Exception raised on main thread: " << endl;
		cout << ex;

#ifdef USE_QTGUI
		a.quit();
#endif
		monitor->exit(0);
}

	return status;
}
Example #11
0
int
CallbackClient::run(int argc, char*[])
{
    if(argc > 1)
    {
        cerr << appName() << ": too many arguments" << endl;
        return EXIT_FAILURE;
    }

    CallbackSenderPrx sender = CallbackSenderPrx::checkedCast(
        communicator()->propertyToProxy("CallbackSender.Proxy")->ice_twoway()->ice_timeout(-1)->ice_secure(false));
    if(!sender)
    {
        cerr << appName() << ": invalid proxy" << endl;
        return EXIT_FAILURE;
    }

    Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("Callback.Client");
    CallbackReceiverPtr cr = new CallbackReceiverI;
    adapter->add(cr, communicator()->stringToIdentity("callbackReceiver"));
    adapter->activate();

    CallbackReceiverPrx receiver = CallbackReceiverPrx::uncheckedCast(
        adapter->createProxy(communicator()->stringToIdentity("callbackReceiver")));

    menu();

    char c = 'x';
    do
    {
        try
        {
            cout << "==> ";
            cin >> c;
            if(c == 't')
            {
                sender->initiateCallback(receiver);
            }
            else if(c == 's')
            {
                sender->shutdown();
            }
            else if(c == 'x')
            {
                // Nothing to do
            }
            else if(c == '?')
            {
                menu();
            }
            else
            {
                cout << "unknown command `" << c << "'" << endl;
                menu();
            }
        }
        catch(const Ice::Exception& ex)
        {
            cerr << ex << endl;
        }
    }
    while(cin.good() && c != 'x');

    return EXIT_SUCCESS;
}
Example #12
0
    virtual int run(int, char*[])
    {
        //
        // Terminate cleanly on receipt of a signal
        //
        shutdownOnInterrupt();

        //
        // Create an object adapter.
        //
        Ice::ObjectAdapterPtr adapter =
            communicator()->createObjectAdapterWithEndpoints("SimpleFilesystem", "default -h localhost -p 10000");

        //
        // Create the root directory (with name "/" and no parent)
        //
        DirectoryIPtr root = new DirectoryI(communicator(), "/", 0);
        root->activate(adapter);

        //
        // Create a file called "README" in the root directory
        //
        FileIPtr file = new FileI(communicator(), "README", root);
        Lines text;
        text.push_back("This file system contains a collection of poetry.");
        file->write(text);
        file->activate(adapter);

        //
        // Create a directory called "Coleridge" in the root directory
        //
        DirectoryIPtr coleridge = new DirectoryI(communicator(), "Coleridge", root);
        coleridge->activate(adapter);

        //
        // Create a file called "Kubla_Khan" in the Coleridge directory
        //
        file = new FileI(communicator(), "Kubla_Khan", coleridge);
        text.erase(text.begin(), text.end());
        text.push_back("In Xanadu did Kubla Khan");
        text.push_back("A stately pleasure-dome decree:");
        text.push_back("Where Alph, the sacred river, ran");
        text.push_back("Through caverns measureless to man");
        text.push_back("Down to a sunless sea.");
        file->write(text);
        file->activate(adapter);

        //
        // All objects are created, allow client requests now
        //
        adapter->activate();

        //
        // Wait until we are done
        //
        communicator()->waitForShutdown();
        if(interrupted())
        {
            cerr << appName() << ": received signal, shutting down" << endl;
        }

        return 0;
    }
Example #13
0
void
ServiceI::start(
    const string& name,
    const CommunicatorPtr& communicator,
    const StringSeq& /*args*/)
{
    PropertiesPtr properties = communicator->getProperties();

    validateProperties(name, properties, communicator->getLogger());

    int id = properties->getPropertyAsIntWithDefault(name + ".NodeId", -1);

    // If we are using a replicated deployment and if the topic
    // manager thread pool max size is not set then ensure it is set
    // to some suitably high number. This ensures no deadlocks in the
    // replicated case due to call forwarding from replicas to
    // coordinators.
    if(id != -1 && properties->getProperty(name + ".TopicManager.ThreadPool.SizeMax").empty())
    {
        properties->setProperty(name + ".TopicManager.ThreadPool.SizeMax", "100");
    }

    Ice::ObjectAdapterPtr topicAdapter = communicator->createObjectAdapter(name + ".TopicManager");
    Ice::ObjectAdapterPtr publishAdapter = communicator->createObjectAdapter(name + ".Publish");

    //
    // We use the name of the service for the name of the database environment.
    //
    string instanceName = properties->getPropertyWithDefault(name + ".InstanceName", "IceStorm");
    Identity topicManagerId;
    topicManagerId.category = instanceName;
    topicManagerId.name = "TopicManager";

    if(properties->getPropertyAsIntWithDefault(name+ ".Transient", 0) > 0)
    {
        _instance = new Instance(instanceName, name, communicator, publishAdapter, topicAdapter, 0);
        try
        {
            TransientTopicManagerImplPtr manager = new TransientTopicManagerImpl(_instance);
            _managerProxy = TopicManagerPrx::uncheckedCast(topicAdapter->add(manager, topicManagerId));
        }
        catch(const Ice::Exception& ex)
        {
            _instance = 0;

            LoggerOutputBase s;
            s << "exception while starting IceStorm service " << name << ":\n";
            s << ex;

            IceBox::FailureException e(__FILE__, __LINE__);
            e.reason = s.str();
            throw e;
        }
        topicAdapter->activate();
        publishAdapter->activate();
        return;
    }

    if(id == -1) // No replication.
    {
        try
        {
            PersistentInstancePtr instance =
                new PersistentInstance(instanceName, name, communicator, publishAdapter, topicAdapter);
            _instance = instance;

            _manager = new TopicManagerImpl(instance);
            _managerProxy = TopicManagerPrx::uncheckedCast(topicAdapter->add(_manager->getServant(), topicManagerId));
        }
        catch(const IceUtil::Exception& ex)
        {
            _instance = 0;

            LoggerOutputBase s;
            s << "exception while starting IceStorm service " << name << ":\n";
            s << ex;

            IceBox::FailureException e(__FILE__, __LINE__);
            e.reason = s.str();
            throw e;
        }
    }
    else
    {
        // Here we want to create a map of id -> election node
        // proxies.
        map<int, NodePrx> nodes;

        string topicManagerAdapterId = properties->getProperty(name + ".TopicManager.AdapterId");

        // We support two possible deployments. The first is a manual
        // deployment, the second is IceGrid.
        //
        // Here we check for the manual deployment
        const string prefix = name + ".Nodes.";
        Ice::PropertyDict props = properties->getPropertiesForPrefix(prefix);
        if(!props.empty())
        {
            for(Ice::PropertyDict::const_iterator p = props.begin(); p != props.end(); ++p)
            {
                int nodeid = atoi(p->first.substr(prefix.size()).c_str());
                nodes[nodeid] = NodePrx::uncheckedCast(communicator->propertyToProxy(p->first));
            }
        }
        else
        {
            // If adapter id's are defined for the topic manager or
            // node adapters then we consider this an IceGrid based
            // deployment.
            string nodeAdapterId = properties->getProperty(name + ".Node.AdapterId");

            // Validate first that the adapter ids match for the node
            // and the topic manager otherwise some other deployment
            // is being used.
            const string suffix = ".TopicManager";
            if(topicManagerAdapterId.empty() || nodeAdapterId.empty() ||
                    topicManagerAdapterId.replace(
                        topicManagerAdapterId.find(suffix), suffix.size(), ".Node") != nodeAdapterId)
            {
                Ice::Error error(communicator->getLogger());
                error << "deployment error: `" << topicManagerAdapterId << "' prefix does not match `"
                      << nodeAdapterId << "'";
                throw IceBox::FailureException(__FILE__, __LINE__, "IceGrid deployment is incorrect");
            }

            // Determine the set of node id and node proxies.
            //
            // This is determined by locating all topic manager
            // replicas, and then working out the node for that
            // replica.
            //
            // We work out the node id by removing the instance
            // name. The node id must follow.
            //
            IceGrid::LocatorPrx locator = IceGrid::LocatorPrx::checkedCast(communicator->getDefaultLocator());
            assert(locator);
            IceGrid::QueryPrx query = locator->getLocalQuery();
            Ice::ObjectProxySeq replicas = query->findAllReplicas(
                                               communicator->stringToProxy(instanceName + "/TopicManager"));

            for(Ice::ObjectProxySeq::const_iterator p = replicas.begin(); p != replicas.end(); ++p)
            {
                string adapterid = (*p)->ice_getAdapterId();

                // Replace TopicManager with the node endpoint.
                adapterid = adapterid.replace(adapterid.find(suffix), suffix.size(), ".Node");

                // The adapter id must start with the instance name.
                if(adapterid.find(instanceName) != 0)
                {
                    Ice::Error error(communicator->getLogger());
                    error << "deployment error: `" << adapterid << "' does not start with `" << instanceName << "'";
                    throw IceBox::FailureException(__FILE__, __LINE__, "IceGrid deployment is incorrect");
                }

                // The node id follows. We find the first digit (the
                // start of the node id, and then the end of the
                // digits).
                string::size_type start = instanceName.size();
                while(start < adapterid.size() && !IceUtilInternal::isDigit(adapterid[start]))
                {
                    ++start;
                }
                string::size_type end = start;
                while(end < adapterid.size() && IceUtilInternal::isDigit(adapterid[end]))
                {
                    ++end;
                }
                if(start == end)
                {
                    // We must have at least one digit, otherwise there is
                    // some sort of deployment error.
                    Ice::Error error(communicator->getLogger());
                    error << "deployment error: node id does not follow instance name. instance name:"
                          << instanceName << " adapter id: " << adapterid;
                    throw IceBox::FailureException(__FILE__, __LINE__, "IceGrid deployment is incorrect");
                }

                int nodeid = atoi(adapterid.substr(start, end-start).c_str());
                ostringstream os;
                os << "node" << nodeid;
                Ice::Identity id;
                id.category = instanceName;
                id.name = os.str();

                nodes[nodeid] = NodePrx::uncheckedCast((*p)->ice_adapterId(adapterid)->ice_identity(id));
            }
        }

        if(nodes.size() < 3)
        {
            Ice::Error error(communicator->getLogger());
            error << "Replication requires at least 3 Nodes";
            throw IceBox::FailureException(__FILE__, __LINE__, "Replication requires at least 3 Nodes");
        }

        try
        {
            // If the node thread pool size is not set then initialize
            // to the number of nodes + 1 and disable thread pool size
            // warnings.
            if(properties->getProperty(name + ".Node.ThreadPool.Size").empty())
            {
                ostringstream os;
                os << nodes.size() + 1;
                properties->setProperty(name + ".Node.ThreadPool.Size", os.str());
                properties->setProperty(name + ".Node.ThreadPool.SizeWarn", "0");
            }
            if(properties->getProperty(name + ".Node.MessageSizeMax").empty())
            {
                properties->setProperty(name + ".Node.MessageSizeMax", "0"); // No limit on data exchanged internally
            }

            Ice::ObjectAdapterPtr nodeAdapter = communicator->createObjectAdapter(name + ".Node");

            PersistentInstancePtr instance =
                new PersistentInstance(instanceName, name, communicator, publishAdapter, topicAdapter,
                                       nodeAdapter, nodes[id]);
            _instance = instance;

            _instance->observers()->setMajority(static_cast<unsigned int>(nodes.size())/2);

            // Trace replication information.
            TraceLevelsPtr traceLevels = _instance->traceLevels();
            if(traceLevels->election > 0)
            {
                Ice::Trace out(traceLevels->logger, traceLevels->electionCat);
                out << "I am node " << id << "\n";
                for(map<int, NodePrx>::const_iterator p = nodes.begin(); p != nodes.end(); ++p)
                {
                    out << "\tnode: " << p->first << " proxy: " << p->second->ice_toString() << "\n";
                }
            }

            if(topicManagerAdapterId.empty())
            {
                // We're not using an IceGrid deployment. Here we need
                // a proxy which is used to create proxies to the
                // replicas later.
                _managerProxy = TopicManagerPrx::uncheckedCast(topicAdapter->createProxy(topicManagerId));
            }
            else
            {
                // If we're using IceGrid deployment we need to create
                // indirect proxies.
                _managerProxy = TopicManagerPrx::uncheckedCast(topicAdapter->createIndirectProxy(topicManagerId));
            }

            _manager = new TopicManagerImpl(instance);
            topicAdapter->add(_manager->getServant(), topicManagerId);

            ostringstream os; // The node object identity.
            os << "node" << id;
            Ice::Identity nodeid;
            nodeid.category = instanceName;
            nodeid.name = os.str();

            NodeIPtr node = new NodeI(_instance, _manager, _managerProxy, id, nodes);
            _instance->setNode(node);
            nodeAdapter->add(node, nodeid);
            nodeAdapter->activate();

            node->start();
        }
        catch(const IceUtil::Exception& ex)
        {
            _instance = 0;

            LoggerOutputBase s;
            s << "exception while starting IceStorm service " << name << ":\n";
            s << ex;

            IceBox::FailureException e(__FILE__, __LINE__);
            e.reason = s.str();
            throw e;
        }
    }

    topicAdapter->add(new FinderI(TopicManagerPrx::uncheckedCast(topicAdapter->createProxy(topicManagerId))),
                      communicator->stringToIdentity("IceStorm/Finder"));

    topicAdapter->activate();
    publishAdapter->activate();
}
Example #14
0
void
allTests(const Ice::CommunicatorPtr& communicator)
{
    cout << "testing stringToProxy... " << flush;
    Ice::ObjectPrx base = communicator->stringToProxy("test @ TestAdapter");
    test(base);
    cout << "ok" << endl;

    cout << "testing IceGrid.Locator is present... " << flush;
    IceGrid::LocatorPrx locator = IceGrid::LocatorPrx::uncheckedCast(base);
    test(locator);
    cout << "ok" << endl;

    cout << "testing checked cast... " << flush;
    TestIntfPrx obj = TestIntfPrx::checkedCast(base);
    test(obj);
    test(obj == base);
    cout << "ok" << endl;

    cout << "pinging server... " << flush;
    obj->ice_ping();
    cout << "ok" << endl;

    cout << "testing locator finder... " << flush;
    Ice::Identity finderId;
    finderId.category = "Ice";
    finderId.name = "LocatorFinder";
    Ice::LocatorFinderPrx finder = Ice::LocatorFinderPrx::checkedCast(
        communicator->getDefaultLocator()->ice_identity(finderId));
    test(finder->getLocator());
    cout << "ok" << endl;

    cout << "testing discovery... " << flush;
    {
        // Add test well-known object
        IceGrid::RegistryPrx registry = IceGrid::RegistryPrx::checkedCast(
            communicator->stringToProxy(communicator->getDefaultLocator()->ice_getIdentity().category + "/Registry"));
        test(registry);

        IceGrid::AdminSessionPrx session = registry->createAdminSession("foo", "bar");
        session->getAdmin()->addObjectWithType(base, "::Test");
        session->destroy();

        //
        // Ensure the IceGrid discovery locator can discover the
        // registries and make sure locator requests are forwarded.
        //
        Ice::InitializationData initData;
        initData.properties = communicator->getProperties()->clone();
        initData.properties->setProperty("Ice.Default.Locator", "");
        initData.properties->setProperty("Ice.Plugin.IceLocatorDiscovery", "IceLocatorDiscovery:createIceLocatorDiscovery");
#ifdef __APPLE__
        if(initData.properties->getPropertyAsInt("Ice.PreferIPv6Address") > 0)
        {
            initData.properties->setProperty("IceLocatorDiscovery.Interface", "::1");
        }
#endif
        initData.properties->setProperty("AdapterForDiscoveryTest.AdapterId", "discoveryAdapter");
        initData.properties->setProperty("AdapterForDiscoveryTest.Endpoints", "default");

        Ice::CommunicatorPtr com = Ice::initialize(initData);
        test(com->getDefaultLocator());
        com->stringToProxy("test @ TestAdapter")->ice_ping();
        com->stringToProxy("test")->ice_ping();

        test(com->getDefaultLocator()->getRegistry());
        test(IceGrid::LocatorPrx::checkedCast(com->getDefaultLocator()));
        test(IceGrid::LocatorPrx::uncheckedCast(com->getDefaultLocator())->getLocalRegistry());
        test(IceGrid::LocatorPrx::uncheckedCast(com->getDefaultLocator())->getLocalQuery());

        Ice::ObjectAdapterPtr adapter = com->createObjectAdapter("AdapterForDiscoveryTest");
        adapter->activate();
        adapter->deactivate();

        com->destroy();

        //
        // Now, ensure that the IceGrid discovery locator correctly
        // handles failure to find a locator. Also test
        // Ice::registerIceLocatorDiscovery()
        //
        Ice::registerIceLocatorDiscovery();
        initData.properties->setProperty("Ice.Plugin.IceLocatorDiscovery", "");
        initData.properties->setProperty("IceLocatorDiscovery.InstanceName", "unknown");
        initData.properties->setProperty("IceLocatorDiscovery.RetryCount", "1");
        initData.properties->setProperty("IceLocatorDiscovery.Timeout", "100");
        com = Ice::initialize(initData);
        test(com->getDefaultLocator());
        try
        {
            com->stringToProxy("test @ TestAdapter")->ice_ping();
        }
        catch(const Ice::NoEndpointException&)
        {
        }
        try
        {
            com->stringToProxy("test")->ice_ping();
        }
        catch(const Ice::NoEndpointException&)
        {
        }
        test(!com->getDefaultLocator()->getRegistry());
        test(!IceGrid::LocatorPrx::checkedCast(com->getDefaultLocator()));
        try
        {
            test(IceGrid::LocatorPrx::uncheckedCast(com->getDefaultLocator())->getLocalQuery());
        }
        catch(const Ice::OperationNotExistException&)
        {
        }

        adapter = com->createObjectAdapter("AdapterForDiscoveryTest");
        adapter->activate();
        adapter->deactivate();

        com->destroy();
    }
    cout << "ok" << endl;

    cout << "shutting down server... " << flush;
    obj->shutdown();
    cout << "ok" << endl;
}
Example #15
0
void
allTests(const CommunicatorPtr& communicator)
{
    communicator->getProperties()->setProperty("ReplyAdapter.Endpoints", "udp -p 12030");
    Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("ReplyAdapter");
    PingReplyIPtr replyI = new PingReplyI;
    PingReplyPrx reply = PingReplyPrx::uncheckedCast(adapter->addWithUUID(replyI))->ice_datagram();
    adapter->activate();

    cout << "testing udp... " << flush;
    ObjectPrx base = communicator->stringToProxy("test -d:udp -p 12010");
    TestIntfPrx obj = TestIntfPrx::uncheckedCast(base);

    int nRetry = 5;
    bool ret;
    while(nRetry-- > 0)
    {
        replyI->reset();
        obj->ping(reply);
        obj->ping(reply);
        obj->ping(reply);
        ret = replyI->waitReply(3, IceUtil::Time::seconds(2));
        if(ret)
        {
            break; // Success
        }

        // If the 3 datagrams were not received within the 2 seconds, we try again to
        // receive 3 new datagrams using a new object. We give up after 5 retries. 
        replyI = new PingReplyI;
        reply = PingReplyPrx::uncheckedCast(adapter->addWithUUID(replyI))->ice_datagram();
    }
    test(ret);

    if(communicator->getProperties()->getPropertyAsInt("Ice.Override.Compress") == 0)
    {
        //
        // Only run this test if compression is disabled, the test expect fixed message size
        // to be sent over the wire.
        //

        Test::ByteSeq seq;
        try
        {
            seq.resize(1024);
            while(true)
            {
                seq.resize(seq.size() * 2 + 10);
                replyI->reset();
                obj->sendByteSeq(seq, reply);
                replyI->waitReply(1, IceUtil::Time::seconds(10));
            }
        }
        catch(const DatagramLimitException&)
        {
            test(seq.size() > 16384);
        }
        obj->ice_getConnection()->close(false);
        communicator->getProperties()->setProperty("Ice.UDP.SndSize", "64000");
        seq.resize(50000);
        try
        {
            replyI->reset();
            obj->sendByteSeq(seq, reply);
            test(!replyI->waitReply(1, IceUtil::Time::milliSeconds(500)));
        }
        catch(const Ice::LocalException& ex)
        {
            cerr << ex << endl;
            test(false);
        }
    }

    cout << "ok" << endl;

    string endpoint;
    if(communicator->getProperties()->getProperty("Ice.IPv6") == "1")
    {
#ifdef __APPLE__
        endpoint = "udp -h \"ff15::1:1\" -p 12020 --interface \"::1\"";
#else
        endpoint = "udp -h \"ff15::1:1\" -p 12020";
#endif
    }
    else
    {
        endpoint = "udp -h 239.255.1.1 -p 12020";
    }
    base = communicator->stringToProxy("test -d:" + endpoint);
    TestIntfPrx objMcast = TestIntfPrx::uncheckedCast(base);
#if !defined(ICE_OS_WINRT) && (!defined(__APPLE__) || (defined(__APPLE__) && !TARGET_OS_IPHONE))
    cout << "testing udp multicast... " << flush;

    nRetry = 5;
    while(nRetry-- > 0)
    {
        replyI->reset();
        objMcast->ping(reply);
        ret = replyI->waitReply(5, IceUtil::Time::seconds(2));
        if(ret)
        {
            break; // Success
        }
        replyI = new PingReplyI;
        reply = PingReplyPrx::uncheckedCast(adapter->addWithUUID(replyI))->ice_datagram();
    }
    if(!ret)
    {
        cout << "failed (is a firewall enabled?)" << endl;
    }
    else
    {
        cout << "ok" << endl;
    }
#endif

    cout << "testing udp bi-dir connection... " << flush;    
    obj->ice_getConnection()->setAdapter(adapter);
    objMcast->ice_getConnection()->setAdapter(adapter);
    nRetry = 5;
    while(nRetry-- > 0)
    {
        replyI->reset();
        obj->pingBiDir(reply->ice_getIdentity());
        obj->pingBiDir(reply->ice_getIdentity());
        obj->pingBiDir(reply->ice_getIdentity());
        ret = replyI->waitReply(3, IceUtil::Time::seconds(2));
        if(ret)
        {
            break; // Success
        }

        // If the 3 datagrams were not received within the 2 seconds, we try again to
        // receive 3 new datagrams using a new object. We give up after 5 retries. 
        replyI = new PingReplyI;
        reply = PingReplyPrx::uncheckedCast(adapter->addWithUUID(replyI))->ice_datagram();
    }
    test(ret);
    cout << "ok" << endl;

    //
    // Sending the replies back on the multicast UDP connection doesn't work for most
    // platform (it works for OS X Leopard but not Snow Leopard, doesn't work on SLES,
    // Windows...). For Windows, see UdpTransceiver constructor for the details. So
    // we don't run this test.
    // 
//     cout << "testing udp bi-dir connection... " << flush;    
//     nRetry = 5;
//     while(nRetry-- > 0)
//     {
//         replyI->reset();
//         objMcast->pingBiDir(reply->ice_getIdentity());
//         ret = replyI->waitReply(5, IceUtil::Time::seconds(2));
//         if(ret)
//         {
//             break; // Success
//         }        
//         replyI = new PingReplyI;
//         reply = PingReplyPrx::uncheckedCast(adapter->addWithUUID(replyI))->ice_datagram();
//     }
//     if(!ret)
//     {
//         cout << "failed (is a firewall enabled?)" << endl;
//     }
//     else
//     {
//         cout << "ok" << endl;
//     }
}
Example #16
0
int
run(int argc, char* argv[], const Ice::CommunicatorPtr& communicator)
{
    if(argc > 1)
    {
        fprintf(stderr, "%s: too many arguments\n", argv[0]);
        return EXIT_FAILURE;
    }

    Ice::PropertiesPtr properties = communicator->getProperties();
    const char* proxyProperty = "CallbackSender.Proxy";
    string proxy = properties->getProperty(proxyProperty);
    if(proxy.empty())
    {
        fprintf(stderr, "%s: property `%s' not set\n", argv[0], proxyProperty);
        return EXIT_FAILURE;
    }

    Ice::ObjectPrx base = communicator->stringToProxy(proxy);
    CallbackSenderPrx twoway = CallbackSenderPrx::checkedCast(base->ice_twoway()->ice_timeout(-1));
    if(!twoway)
    {
        fprintf(stderr, "%s: invalid proxy\n", argv[0]);
        return EXIT_FAILURE;
    }
    CallbackSenderPrx oneway = twoway->ice_oneway();
#ifdef ICEE_HAS_BATCH
    CallbackSenderPrx batchOneway = twoway->ice_batchOneway();
#endif    
    Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("Callback.Client");
    CallbackReceiverPtr cr = new CallbackReceiverI;
    adapter->add(cr, communicator->stringToIdentity("callbackReceiver"));
    adapter->activate();

    CallbackReceiverPrx twowayR = CallbackReceiverPrx::uncheckedCast(
        adapter->createProxy(communicator->stringToIdentity("callbackReceiver")));
    CallbackReceiverPrx onewayR = twowayR->ice_oneway();

    menu();

    char c = EOF;
    do
    {
        try
        {
            printf("==> "); fflush(stdout);
            do
            {
               c = getchar();
            }
            while(c != EOF && c == '\n');
            if(c == 't')
            {
                twoway->initiateCallback(twowayR);
            }
            else if(c == 'o')
            {
                oneway->initiateCallback(onewayR);
            }
#ifdef ICEE_HAS_BATCH
            else if(c == 'O')
            {
                batchOneway->initiateCallback(onewayR);
            }
            else if(c == 'f')
            {
                batchOneway->ice_flushBatchRequests();
            }
#endif
            else if(c == 's')
            {
                twoway->shutdown();
            }
            else if(c == 'x')
            {
                // Nothing to do
            }
            else if(c == '?')
            {
                menu();
            }
            else
            {
                printf("unknown command `%c'\n", c);
                menu();
            }
        }
        catch(const Ice::Exception& ex)
        {
            fprintf(stderr, "%s\n", ex.toString().c_str());
        }
    }
    while(c != EOF && c != 'x');

    return EXIT_SUCCESS;
}
Example #17
0
int main(int argc , char* argv[])
{
	const bfs::path binPath(argv[0]);
	const bfs::path& homePath = system_complete(binPath).parent_path().parent_path();
	cout<<homePath.string();
	bpo::options_description desc("msgWait allowed options");
	desc.add_options()
		("help", "help message")
		("log_conf", bpo::value<string>(), "log4cplus configure file")
		("server_id", bpo::value<int>(), "The server id")
		("service_port", bpo::value<short>(), "The endpoint ice service port")
		("domain", bpo::value<string>(), "The server endpoint domain")
		("zk_servers", bpo::value<string>(), "The zookeeper servers list split with ','");

	string logConf;
	string domain;

	bpo::variables_map vm;
	string configFile = homePath.string() + "/conf/msgWait_config.cfg";
	ifstream configIFS(configFile.c_str());
	bpo::store(bpo::parse_config_file(configIFS, desc), vm);
	bpo::notify(vm);

	if(vm.count("help")){
		cout << desc << endl;
		return 0;
	}
	if(vm.count("log_conf")){
		logConf = vm["log_conf"].as<string>();
	} else {
		cout << desc << endl;
		return 0;
	}
	if(vm.count("server_id")){
		serverId = vm["server_id"].as<int>();
	} else {
		cout << desc << endl;
		return 0;
	}
	if(vm.count("service_port")){
		servicePort = vm["service_port"].as<short>();
	} else {
		cout << desc << endl;
		return 0;
	}
	if(vm.count("domain")){
		domain = vm["domain"].as<string>();
	} else {
		cout << desc << endl;
		return 0;
	}
	if(vm.count("zk_servers")){
		zkServers = vm["zk_servers"].as<string>();
	} else {
		cout << desc << endl;
		return 0;
	}

	//configure log4cplus
	ConfigureAndWatchThread configureThread(LOG4CPLUS_TEXT(logConf), 5 * 1000);

	boost::shared_ptr<MessageWaitManager> messageWaitManagerPtr(new MessageWaitManager);
	messageWaitManagerPtr->init(serverId, servicePort, domain, zkServers);
	messageWaitManagerPtr->start();
    
    // init whitelist
    mtalk::utils::wl::InitWhiteList();

	Ice::CommunicatorPtr ic;

	try{
		ic = Ice::initialize();
		ostringstream os;
		os << "default -p " << servicePort;
		Ice::ObjectAdapterPtr adapter = ic->createObjectAdapterWithEndpoints("TalkAdapter", os.str());
		Ice::ObjectPtr object = new msgwait::MessageWaitManagerServiceI( messageWaitManagerPtr );
		adapter->add(object, ic->stringToIdentity("MessageWaitManagerService"));
		adapter->activate();
		LOG_INFO("main => endpoint server started");
		cout << "==== Server Started ====" << endl;
		ic->waitForShutdown();
	} catch (const Ice::Exception& e) {
		cout << e << endl;
	} catch (const char* msg){
		cout << msg << endl;
	}
	messageWaitManagerPtr->stop();
	if(ic){
		ic->destroy();
	}

	return 0;
}
Example #18
0
void
allTests(const Ice::CommunicatorPtr& communicator)
{
    string sref = "timeout:" + getTestEndpoint(communicator, 0);
    Ice::ObjectPrxPtr obj = communicator->stringToProxy(sref);
    test(obj);

    TimeoutPrxPtr timeout = ICE_CHECKED_CAST(TimeoutPrx, obj);
    test(timeout);

    ControllerPrxPtr controller =
        ICE_CHECKED_CAST(ControllerPrx, communicator->stringToProxy("controller:" + getTestEndpoint(communicator, 1)));
    test(controller);

    cout << "testing connect timeout... " << flush;
    {
        //
        // Expect ConnectTimeoutException.
        //
        TimeoutPrxPtr to = ICE_UNCHECKED_CAST(TimeoutPrx, obj->ice_timeout(100));
        controller->holdAdapter(-1);
        try
        {
            to->op();
            test(false);
        }
        catch(const Ice::ConnectTimeoutException&)
        {
            // Expected.
        }
        controller->resumeAdapter();
        timeout->op(); // Ensure adapter is active.
    }
    {
        //
        // Expect success.
        //
        TimeoutPrxPtr to = ICE_UNCHECKED_CAST(TimeoutPrx, obj->ice_timeout(2000));
        controller->holdAdapter(100);
        try
        {
            to->op();
        }
        catch(const Ice::ConnectTimeoutException&)
        {
            test(false);
        }
    }
    cout << "ok" << endl;

    // The sequence needs to be large enough to fill the write/recv buffers
    ByteSeq seq(2000000);

    cout << "testing connection timeout... " << flush;
    {
        //
        // Expect TimeoutException.
        //
        TimeoutPrxPtr to = ICE_UNCHECKED_CAST(TimeoutPrx, obj->ice_timeout(250));
        connect(to);
        controller->holdAdapter(-1);
        try
        {
            to->sendData(seq);
            test(false);
        }
        catch(const Ice::TimeoutException&)
        {
            // Expected.
        }
        controller->resumeAdapter();
        timeout->op(); // Ensure adapter is active.
    }
    {
        //
        // Expect success.
        //
        TimeoutPrxPtr to = ICE_UNCHECKED_CAST(TimeoutPrx, obj->ice_timeout(2000));
        controller->holdAdapter(100);
        try
        {
            ByteSeq seq(1000000);
            to->sendData(seq);
        }
        catch(const Ice::TimeoutException&)
        {
            test(false);
        }
    }
    cout << "ok" << endl;

    cout << "testing invocation timeout... " << flush;
    {
        Ice::ConnectionPtr connection = obj->ice_getConnection();
        TimeoutPrxPtr to = ICE_UNCHECKED_CAST(TimeoutPrx, obj->ice_invocationTimeout(100));
        test(connection == to->ice_getConnection());
        try
        {
            to->sleep(500);
            test(false);
        }
        catch(const Ice::InvocationTimeoutException&)
        {
        }
        obj->ice_ping();
        to = ICE_CHECKED_CAST(TimeoutPrx, obj->ice_invocationTimeout(1000));
        test(connection == to->ice_getConnection());
        try
        {
            to->sleep(100);
        }
        catch(const Ice::InvocationTimeoutException&)
        {
            test(false);
        }
        test(connection == to->ice_getConnection());
    }
    {
        //
        // Expect InvocationTimeoutException.
        //
        TimeoutPrxPtr to = ICE_UNCHECKED_CAST(TimeoutPrx, obj->ice_invocationTimeout(100));

#ifdef ICE_CPP11_MAPPING
        auto f = to->sleepAsync(500);
        try
        {
            f.get();
            test(false);
        }
        catch(const Ice::InvocationTimeoutException&)
        {
        }
        catch(...)
        {
            test(false);
        }
#else
        CallbackPtr cb = new Callback();
        to->begin_sleep(500, newCallback_Timeout_sleep(cb, &Callback::responseEx, &Callback::exceptionEx));
        cb->check();
#endif
        obj->ice_ping();
    }
    {
        //
        // Expect success.
        //
        TimeoutPrxPtr to = ICE_UNCHECKED_CAST(TimeoutPrx, obj->ice_invocationTimeout(1000));
#ifdef ICE_CPP11_MAPPING
        auto f = to->sleepAsync(100);
        try
        {
            f.get();
        }
        catch(...)
        {
            test(false);
        }
#else
        CallbackPtr cb = new Callback();
        to->begin_sleep(100, newCallback_Timeout_sleep(cb, &Callback::response, &Callback::exception));
        cb->check();
#endif
    }
    {
        //
        // Backward compatible connection timeouts
        //
        TimeoutPrxPtr to = ICE_UNCHECKED_CAST(TimeoutPrx, obj->ice_invocationTimeout(-2)->ice_timeout(250));
        Ice::ConnectionPtr con = connect(to);
        try
        {
            to->sleep(750);
            test(false);
        }
        catch(const Ice::TimeoutException&)
        {
            try
            {
                con->getInfo();
                test(false);
            }
            catch(const Ice::TimeoutException&)
            {
                // Connection got closed as well.
            }
        }
        obj->ice_ping();
        try
        {
            con = connect(to);
#ifdef ICE_CPP11_MAPPING
            to->sleepAsync(750).get();
#else
            to->end_sleep(to->begin_sleep(750));
#endif
            test(false);
        }
        catch(const Ice::TimeoutException&)
        {
            try
            {
                con->getInfo();
                test(false);
            }
            catch(const Ice::TimeoutException&)
            {
                // Connection got closed as well.
            }
        }
        obj->ice_ping();
    }
    cout << "ok" << endl;

    cout << "testing close timeout... " << flush;
    {
        TimeoutPrxPtr to = ICE_UNCHECKED_CAST(TimeoutPrx, obj->ice_timeout(250));
        Ice::ConnectionPtr connection = connect(to);
        controller->holdAdapter(-1);
        connection->close(Ice::ICE_SCOPED_ENUM(ConnectionClose, GracefullyWithWait));
        try
        {
            connection->getInfo(); // getInfo() doesn't throw in the closing state.
        }
        catch(const Ice::LocalException&)
        {
            test(false);
        }
        while(true)
        {
            try
            {
                connection->getInfo();
                IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(10));
            }
            catch(const Ice::ConnectionManuallyClosedException& ex)
            {
                // Expected.
                test(ex.graceful);
                break;
            }
        }
        controller->resumeAdapter();
        timeout->op(); // Ensure adapter is active.
    }
    cout << "ok" << endl;

    cout << "testing timeout overrides... " << flush;
    {
        //
        // Test Ice.Override.Timeout. This property overrides all
        // endpoint timeouts.
        //
        Ice::InitializationData initData;
        initData.properties = communicator->getProperties()->clone();
        initData.properties->setProperty("Ice.Override.ConnectTimeout", "250");
        initData.properties->setProperty("Ice.Override.Timeout", "100");
        Ice::CommunicatorHolder ich(initData);
        TimeoutPrxPtr to = ICE_UNCHECKED_CAST(TimeoutPrx, ich->stringToProxy(sref));
        connect(to);
        controller->holdAdapter(-1);
        try
        {
            to->sendData(seq);
            test(false);
        }
        catch(const Ice::TimeoutException&)
        {
            // Expected.
        }
        controller->resumeAdapter();
        timeout->op(); // Ensure adapter is active.

        //
        // Calling ice_timeout() should have no effect.
        //
        to = ICE_UNCHECKED_CAST(TimeoutPrx, to->ice_timeout(1000));
        connect(to);
        controller->holdAdapter(-1);
        try
        {
            to->sendData(seq);
            test(false);
        }
        catch(const Ice::TimeoutException&)
        {
            // Expected.
        }
        controller->resumeAdapter();
        timeout->op(); // Ensure adapter is active.
    }
    {
        //
        // Test Ice.Override.ConnectTimeout.
        //
        Ice::InitializationData initData;
        initData.properties = communicator->getProperties()->clone();
        initData.properties->setProperty("Ice.Override.ConnectTimeout", "250");
        Ice::CommunicatorHolder ich(initData);
        controller->holdAdapter(-1);
        TimeoutPrxPtr to = ICE_UNCHECKED_CAST(TimeoutPrx, ich->stringToProxy(sref));
        try
        {
            to->op();
            test(false);
        }
        catch(const Ice::ConnectTimeoutException&)
        {
            // Expected.
        }
        controller->resumeAdapter();
        timeout->op(); // Ensure adapter is active.

        //
        // Calling ice_timeout() should have no effect on the connect timeout.
        //
        controller->holdAdapter(-1);
        to = ICE_UNCHECKED_CAST(TimeoutPrx, to->ice_timeout(1000));
        try
        {
            to->op();
            test(false);
        }
        catch(const Ice::ConnectTimeoutException&)
        {
            // Expected.
        }
        controller->resumeAdapter();
        timeout->op(); // Ensure adapter is active.

        //
        // Verify that timeout set via ice_timeout() is still used for requests.
        //
        to = ICE_UNCHECKED_CAST(TimeoutPrx, to->ice_timeout(250));
        connect(to);
        controller->holdAdapter(-1);
        try
        {
            to->sendData(seq);
            test(false);
        }
        catch(const Ice::TimeoutException&)
        {
            // Expected.
        }
        controller->resumeAdapter();
        timeout->op(); // Ensure adapter is active.
    }
    {
        //
        // Test Ice.Override.CloseTimeout.
        //
        Ice::InitializationData initData;
        initData.properties = communicator->getProperties()->clone();
        initData.properties->setProperty("Ice.Override.CloseTimeout", "100");
        Ice::CommunicatorHolder ich(initData);
        Ice::ConnectionPtr connection = ich->stringToProxy(sref)->ice_getConnection();
        controller->holdAdapter(-1);
        IceUtil::Time now = IceUtil::Time::now();
        ich.release()->destroy();
        test(IceUtil::Time::now() - now < IceUtil::Time::milliSeconds(700));
        controller->resumeAdapter();
        timeout->op(); // Ensure adapter is active.
    }
    cout << "ok" << endl;

    cout << "testing invocation timeouts with collocated calls... " << flush;
    {
        communicator->getProperties()->setProperty("TimeoutCollocated.AdapterId", "timeoutAdapter");

        Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("TimeoutCollocated");
        adapter->activate();

        TimeoutPrxPtr timeout = ICE_UNCHECKED_CAST(TimeoutPrx, adapter->addWithUUID(ICE_MAKE_SHARED(TimeoutI)));
        timeout = timeout->ice_invocationTimeout(100);
        try
        {
            timeout->sleep(500);
            test(false);
        }
        catch(const Ice::InvocationTimeoutException&)
        {
        }

        try
        {
#ifdef ICE_CPP11_MAPPING
            timeout->sleepAsync(500).get();
#else
            timeout->end_sleep(timeout->begin_sleep(500));
#endif
            test(false);
        }
        catch(const Ice::InvocationTimeoutException&)
        {
        }

        try
        {
            timeout->ice_invocationTimeout(-2)->ice_ping();
            #ifdef ICE_CPP11_MAPPING
            timeout->ice_invocationTimeout(-2)->ice_pingAsync().get();
            #else
            timeout->ice_invocationTimeout(-2)->begin_ice_ping()->waitForCompleted();
            #endif
        }
        catch(const Ice::Exception&)
        {
            test(false);
        }

        TimeoutPrxPtr batchTimeout = timeout->ice_batchOneway();
        batchTimeout->ice_ping();
        batchTimeout->ice_ping();
        batchTimeout->ice_ping();

        // Keep the server thread pool busy.
#ifdef ICE_CPP11_MAPPING
        timeout->ice_invocationTimeout(-1)->sleepAsync(300);
#else
        timeout->ice_invocationTimeout(-1)->begin_sleep(300);
#endif
        try
        {
            batchTimeout->ice_flushBatchRequests();
            test(false);
        }
        catch(const Ice::InvocationTimeoutException&)
        {
        }

        batchTimeout->ice_ping();
        batchTimeout->ice_ping();
        batchTimeout->ice_ping();

        // Keep the server thread pool busy.
#ifdef ICE_CPP11_MAPPING
        timeout->ice_invocationTimeout(-1)->sleepAsync(300);
#else
        timeout->ice_invocationTimeout(-1)->begin_sleep(300);
#endif
        try
        {
#ifdef ICE_CPP11_MAPPING
            batchTimeout->ice_flushBatchRequestsAsync().get();
#else
            batchTimeout->end_ice_flushBatchRequests(batchTimeout->begin_ice_flushBatchRequests());
#endif
            test(false);
        }
        catch(const Ice::InvocationTimeoutException&)
        {
        }

        adapter->destroy();
    }
    cout << "ok" << endl;

    controller->shutdown();
}
Example #19
0
int ::muecasservos::run(int argc, char* argv[])
{
	QCoreApplication a(argc, argv);  // NON-GUI application
	int status=EXIT_SUCCESS;


	string proxy, tmp;
	initialize();



	SpecificWorker *worker = new SpecificWorker(mprx);
	//Monitor thread
	SpecificMonitor *monitor = new SpecificMonitor(worker,communicator());
	QObject::connect(monitor, SIGNAL(kill()), &a, SLOT(quit()));
	QObject::connect(worker, SIGNAL(kill()), &a, SLOT(quit()));
	monitor->start();

	if ( !monitor->isRunning() )
		return status;
	
	while (!monitor->ready)
	{
		usleep(10000);
	}
	
	try
	{
		// Server adapter creation and publication
		if (not GenericMonitor::configGetString(communicator(), prefix, "CommonBehavior.Endpoints", tmp, ""))
		{
			cout << "[" << PROGRAM_NAME << "]: Can't read configuration for proxy CommonBehavior\n";
		}
		Ice::ObjectAdapterPtr adapterCommonBehavior = communicator()->createObjectAdapterWithEndpoints("commonbehavior", tmp);
		CommonBehaviorI *commonbehaviorI = new CommonBehaviorI(monitor );
		adapterCommonBehavior->add(commonbehaviorI, communicator()->stringToIdentity("commonbehavior"));
		adapterCommonBehavior->activate();




		// Server adapter creation and publication
		if (not GenericMonitor::configGetString(communicator(), prefix, "JointMotor.Endpoints", tmp, ""))
		{
			cout << "[" << PROGRAM_NAME << "]: Can't read configuration for proxy JointMotor";
		}
		Ice::ObjectAdapterPtr adapterJointMotor = communicator()->createObjectAdapterWithEndpoints("JointMotor", tmp);
		JointMotorI *jointmotor = new JointMotorI(worker);
		adapterJointMotor->add(jointmotor, communicator()->stringToIdentity("jointmotor"));
		adapterJointMotor->activate();




		// Server adapter creation and publication
		cout << SERVER_FULL_NAME " started" << endl;

		// User defined QtGui elements ( main window, dialogs, etc )

#ifdef USE_QTGUI
		//ignoreInterrupt(); // Uncomment if you want the component to ignore console SIGINT signal (ctrl+c).
		a.setQuitOnLastWindowClosed( true );
#endif
		// Run QT Application Event Loop
		a.exec();
		status = EXIT_SUCCESS;
	}
	catch(const Ice::Exception& ex)
	{
		status = EXIT_FAILURE;

		cout << "[" << PROGRAM_NAME << "]: Exception raised on main thread: " << endl;
		cout << ex;

#ifdef USE_QTGUI
		a.quit();
#endif
		monitor->exit(0);
}

	return status;
}
Example #20
0
BOOL CHelloServerApp::InitInstance()
{
    //
    // InitCommonControls() is required on Windows XP if an application
    // manifest specifies use of ComCtl32.dll version 6 or later to enable
    // visual styles.  Otherwise, any window creation will fail.
    //
    InitCommonControls();

    CWinApp::InitInstance();

    //
    // Create a communicator and object adapter.
    //
    Ice::CommunicatorPtr communicator;
    Ice::ObjectAdapterPtr adapter;
    LogIPtr log;
    try
    {
        int argc = 0;
        Ice::InitializationData initData;
        initData.properties = Ice::createProperties();

        //
        // Set a default value for Hello.Endpoints so that the demo
        // will run without a configuration file.
        //
        initData.properties->setProperty("Hello.Endpoints", "tcp -p 10000");

        //
        // Now, load the configuration file if present. Under WinCE we
        // use "config.txt" since it can be edited with pocket word.
        //
#ifdef _WIN32_WCE
        string config = "config.txt";
#else
        string config = "config";
#endif
        try
        {
            initData.properties->load(config);
        }
        catch(const Ice::FileException&)
        {
        }

        log = new LogI;
        initData.logger = log;

        communicator = Ice::initialize(argc, 0, initData);
        adapter = communicator->createObjectAdapter("Hello");
    }
    catch(const IceUtil::Exception& ex)
    {
        AfxMessageBox(CString(ex.toString().c_str()), MB_OK|MB_ICONEXCLAMATION);
        return FALSE;
    }

    //
    // Create the dialog.
    //
    CHelloServerDlg dlg(communicator, log);

    //
    // Instantiate the servant.
    //
    Ice::ObjectPtr servant = new HelloI(log, &dlg);
    adapter->add(servant, communicator->stringToIdentity("hello"));
    adapter->activate();
    log->message("Ready to receive requests.");

    //
    // Show dialog and wait until it is closed, or until the servant receives
    // a shutdown request.
    //
    m_pMainWnd = &dlg;
    dlg.DoModal();

    //
    // Edit control no longer exists.
    //
    log->setHandle(0);

    //
    // Clean up.
    //
    try
    {
        communicator->destroy();
    }
    catch(const Ice::Exception&)
    {
    }

    // Since the dialog has been closed, return FALSE so that we exit the
    // application, rather than start the application's message pump.
    return FALSE;
}
Example #21
0
int reflexxes::run(int argc, char* argv[])
{
#ifdef USE_QTGUI
	QApplication a(argc, argv);  // GUI application
#else
	QCoreApplication a(argc, argv);  // NON-GUI application
#endif
	int status=EXIT_SUCCESS;

	JointMotorPrx jointmotor_proxy;

	string proxy, tmp;
	initialize();


	try
	{
		if (not GenericMonitor::configGetString(communicator(), prefix, "JointMotorProxy", proxy, ""))
		{
			cout << "[" << PROGRAM_NAME << "]: Can't read configuration for proxy JointMotorProxy\n";
		}
		jointmotor_proxy = JointMotorPrx::uncheckedCast( communicator()->stringToProxy( proxy ) );
	}
	catch(const Ice::Exception& ex)
	{
		cout << "[" << PROGRAM_NAME << "]: Exception: " << ex;
		return EXIT_FAILURE;
	}
	rInfo("JointMotorProxy initialized Ok!");
	mprx["JointMotorProxy"] = (::IceProxy::Ice::Object*)(&jointmotor_proxy);//Remote server proxy creation example



	GenericWorker *worker = new SpecificWorker(mprx);
	//Monitor thread
	GenericMonitor *monitor = new SpecificMonitor(worker,communicator());
	QObject::connect(monitor, SIGNAL(kill()), &a, SLOT(quit()));
	QObject::connect(worker, SIGNAL(kill()), &a, SLOT(quit()));
	monitor->start();

	if ( !monitor->isRunning() )
		return status;
	try
	{
		// Server adapter creation and publication
		if (not GenericMonitor::configGetString(communicator(), prefix, "CommonBehavior.Endpoints", tmp, ""))
		{
			cout << "[" << PROGRAM_NAME << "]: Can't read configuration for proxy CommonBehavior\n";
		}
		Ice::ObjectAdapterPtr adapterCommonBehavior = communicator()->createObjectAdapterWithEndpoints("commonbehavior", tmp);
		CommonBehaviorI *commonbehaviorI = new CommonBehaviorI(monitor );
		adapterCommonBehavior->add(commonbehaviorI, communicator()->stringToIdentity("commonbehavior"));
		adapterCommonBehavior->activate();




		// Server adapter creation and publication
		if (not GenericMonitor::configGetString(communicator(), prefix, "Reflexxes.Endpoints", tmp, ""))
		{
			cout << "[" << PROGRAM_NAME << "]: Can't read configuration for proxy Reflexxes";
		}
		Ice::ObjectAdapterPtr adapterReflexxes = communicator()->createObjectAdapterWithEndpoints("Reflexxes", tmp);
		ReflexxesI *reflexxes = new ReflexxesI(worker);
		adapterReflexxes->add(reflexxes, communicator()->stringToIdentity("reflexxes"));
		adapterReflexxes->activate();




		// Server adapter creation and publication
		cout << SERVER_FULL_NAME " started" << endl;

		// User defined QtGui elements ( main window, dialogs, etc )

#ifdef USE_QTGUI
		//ignoreInterrupt(); // Uncomment if you want the component to ignore console SIGINT signal (ctrl+c).
		a.setQuitOnLastWindowClosed( true );
#endif
		// Run QT Application Event Loop
		a.exec();
		status = EXIT_SUCCESS;
	}
	catch(const Ice::Exception& ex)
	{
		status = EXIT_FAILURE;

		cout << "[" << PROGRAM_NAME << "]: Exception raised on main thread: " << endl;
		cout << ex;

#ifdef USE_QTGUI
		a.quit();
#endif
		monitor->exit(0);
}

	return status;
}
Example #22
0
int main(int argc, char* argv[]){
	const bfs::path binPath(argv[0]);
	const bfs::path& binDir = system_complete(binPath).parent_path();
	const bfs::path& homePath = binDir.parent_path();

	bpo::options_description desc("talk allowed options");
	desc.add_options()
		("help", "help message")
		("log_conf", bpo::value<string>(), "log4cplus configure file")
		("server_id", bpo::value<int>(), "The server id")
		("server_port", bpo::value<short>(), "The server port")
		("domain", bpo::value<string>(), "The server domain")
		("zk_servers", bpo::value<string>(), "The zookeeper server list split with ','")
		("redis_servers", bpo::value<string>(), "The redis server list split with ','");

	string logConf;
	int serverId;
	short serverPort;
	string domain;
	string zkServers;
	string redisServers;

	bpo::variables_map vm;
	string configFile = homePath.string() + "/conf/muc_config.cfg";
	ifstream configIFS(configFile.c_str());
	bpo::store(bpo::parse_config_file(configIFS, desc), vm);
	bpo::notify(vm);


	if(vm.count("help")){
		cout << desc << endl;
		return 0;
	}
	if(vm.count("log_conf")){
		logConf = vm["log_conf"].as<string>();
	} else {
		cout << desc << endl;
		return 0;
	}
	if(vm.count("server_id")){
		serverId = vm["server_id"].as<int>();
	} else {
		cout << desc << endl;
		return 0;
	}
	if(vm.count("server_port")){
		serverPort = vm["server_port"].as<short>();
	} else {
		cout << desc << endl;
		return 0;
	}
	if(vm.count("domain")){
		domain = vm["domain"].as<string>();
	} else {
		cout << desc << endl;
		return 0;
	}
	if(vm.count("zk_servers")){
		zkServers = vm["zk_servers"].as<string>();
		cout << "zkServers = " << zkServers << endl;
		LOG_INFO("main ==> zkServers = " << zkServers);
	} else {
		cout << desc << endl;
		return 0;
	}
	

	ConfigureAndWatchThread configureThread(LOG4CPLUS_TEXT(logConf), 5 * 1000);
	
	MucServer& mucServer = MY_INSTANCE(MucServer);
	mucServer.init(serverId, serverPort, zkServers);

	boost::thread thread(boost::bind(&MucServer::start, &mucServer));

	WapIceChannel iceChannel;
	try{
		iceChannel.init();
		Ice::ObjectAdapterPtr adapter = iceChannel.createObjectAdapterWithEndpoints("MucAdapter", serverPort);

		Ice::ObjectPtr mucService = new MucServiceI();
		adapter->add(mucService, iceChannel.getCommunicator()->stringToIdentity("MucService"));

		adapter->activate();

		LOG_INFO("main => muc server started");
		cout << "=== Server started ===" << endl;
		iceChannel.getCommunicator()->waitForShutdown();
	} catch (const Ice::Exception& e){
		cout << e << endl;
	} catch (const char* msg){
		cout << msg << endl;
	}

	mucServer.stop();
	thread.join();
	iceChannel.destroy();
	return 0;
}
Example #23
0
int WINAPI
WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
    static const TCHAR windowClassName[] = L"Throughput Server";
    WNDCLASS wc;
    
    wc.style                 = CS_HREDRAW|CS_VREDRAW;
    wc.lpfnWndProc         = (WNDPROC)WndProc;
    wc.cbClsExtra         = 0;
    wc.cbWndExtra         = 0;
    wc.hInstance         = hInstance;
    wc.hIcon                 = LoadIcon(NULL, 0);
    wc.hCursor                 = 0;
    wc.hbrBackground         = (HBRUSH) GetStockObject(WHITE_BRUSH);
    wc.lpszMenuName      = NULL;
    wc.lpszClassName     = windowClassName;

    if(!RegisterClass(&wc))
    {
        MessageBox(NULL, L"Window Registration Failed!", L"Error!",
                   MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    RECT rect;
    GetClientRect(GetDesktopWindow(), &rect);
    int width = rect.right - rect.left;
    if(width > 320)
    {
        width = 320;
    }
    int height = rect.bottom - rect.top;
    if(height > 200)
    {
        height = 200;
    }
    HWND mainWnd = CreateWindow(windowClassName, L"Throughput Server", WS_VISIBLE|WS_OVERLAPPED|WS_SYSMENU|WS_SIZEBOX,
                                CW_USEDEFAULT, CW_USEDEFAULT, width, height,
                                NULL, NULL, hInstance, NULL);
    if(mainWnd == NULL)
    {
        MessageBox(NULL, L"Window Creation Failed!", L"Error!", MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    ShowWindow(mainWnd, SW_SHOW);
    UpdateWindow(mainWnd);

    int status = EXIT_SUCCESS;

    extern int    __argc;
    extern char **__argv; 

    Ice::CommunicatorPtr communicator;

    try
    {
        Ice::InitializationData initData;
        initData.properties = Ice::createProperties();

        //
        // Set a default value for Latency.Endpoints so that the demo
        // will run without a configuration file.
        //
        initData.properties->setProperty("Throughput.Endpoints","tcp -p 10000");

        //
        // Now, load the configuration file if present. Under WinCE we
        // use "config.txt" since it can be edited with pocket word.
        //
        try
        {
            initData.properties->load("config.txt");
        }
        catch(const Ice::FileException&)
        {
        }

        communicator = Ice::initialize(__argc, __argv, initData);

        Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("Throughput");
        Demo::ThroughputPtr servant = new ThroughputI(100);
        adapter->add(servant, communicator->stringToIdentity("throughput"));
        adapter->activate();

        //
        // Display a helpful message to the user.
        //
        ::SendMessage(editHwnd, EM_REPLACESEL,
                      (WPARAM)FALSE, (LPARAM)L"Close the window to terminate the server.\r\n");

        //
        // Run the message pump.
        //
        MSG Msg;
        while(GetMessage(&Msg, NULL, 0, 0) > 0)
        {
            TranslateMessage(&Msg);
            DispatchMessage(&Msg);
        }
    }
    catch(const Ice::Exception& ex)
    {
        TCHAR wtext[1024];
        string err = ex.toString();
        mbstowcs(wtext, err.c_str(), err.size());
        MessageBox(mainWnd, wtext, L"Error", MB_ICONEXCLAMATION | MB_OK);

        status = EXIT_FAILURE;
    }

    if(communicator)
    {
        try
        {
            communicator->destroy();
        }
        catch(const Ice::Exception& ex)
        {
            TCHAR wtext[1024];
            string err = ex.toString();
            mbstowcs(wtext, err.c_str(), err.size());
            MessageBox(mainWnd, wtext, L"Error", MB_ICONEXCLAMATION | MB_OK);

            status = EXIT_FAILURE;
        }
    }
    return status;
}
Example #24
0
int ::velodyneDataManager::run(int argc, char* argv[])
{
#ifdef USE_QTGUI
	QApplication a(argc, argv);  // GUI application
#else
	QCoreApplication a(argc, argv);  // NON-GUI application
#endif
	int status=EXIT_SUCCESS;

	VelodyneDataPrx velodynedata_proxy;

	string proxy, tmp;
	initialize();

	IceStorm::TopicManagerPrx topicManager = IceStorm::TopicManagerPrx::checkedCast(communicator()->propertyToProxy("TopicManager.Proxy"));

	IceStorm::TopicPrx velodynedata_topic;
	while (!velodynedata_topic)
	{
		try
		{
			velodynedata_topic = topicManager->retrieve("VelodyneData");
		}
		catch (const IceStorm::NoSuchTopic&)
		{
			try
			{
				velodynedata_topic = topicManager->create("VelodyneData");
			}
			catch (const IceStorm::TopicExists&){
				// Another client created the topic.
			}
		}
	}
	Ice::ObjectPrx velodynedata_pub = velodynedata_topic->getPublisher()->ice_oneway();
	VelodyneDataPrx velodynedata = VelodyneDataPrx::uncheckedCast(velodynedata_pub);
	mprx["VelodyneDataPub"] = (::IceProxy::Ice::Object*)(&velodynedata);



	SpecificWorker *worker = new SpecificWorker(mprx);
	//Monitor thread
	SpecificMonitor *monitor = new SpecificMonitor(worker,communicator());
	QObject::connect(monitor, SIGNAL(kill()), &a, SLOT(quit()));
	QObject::connect(worker, SIGNAL(kill()), &a, SLOT(quit()));
	monitor->start();

	if ( !monitor->isRunning() )
		return status;
	
	while (!monitor->ready)
	{
		usleep(10000);
	}
	
	try
	{
		// Server adapter creation and publication
		if (not GenericMonitor::configGetString(communicator(), prefix, "CommonBehavior.Endpoints", tmp, ""))
		{
			cout << "[" << PROGRAM_NAME << "]: Can't read configuration for proxy CommonBehavior\n";
		}
		Ice::ObjectAdapterPtr adapterCommonBehavior = communicator()->createObjectAdapterWithEndpoints("commonbehavior", tmp);
		CommonBehaviorI *commonbehaviorI = new CommonBehaviorI(monitor );
		adapterCommonBehavior->add(commonbehaviorI, communicator()->stringToIdentity("commonbehavior"));
		adapterCommonBehavior->activate();







		// Server adapter creation and publication
		if (not GenericMonitor::configGetString(communicator(), prefix, "PersonPositionTopic.Endpoints", tmp, ""))
		{
			cout << "[" << PROGRAM_NAME << "]: Can't read configuration for proxy PersonPositionProxy";
		}
		Ice::ObjectAdapterPtr PersonPosition_adapter = communicator()->createObjectAdapterWithEndpoints("personposition", tmp);
		PersonPositionPtr personpositionI_ = new PersonPositionI(worker);
		Ice::ObjectPrx personposition = PersonPosition_adapter->addWithUUID(personpositionI_)->ice_oneway();
		PersonPosition_adapter->add(personpositionI_, communicator()->stringToIdentity("PersonPositionTopic.Endpoints"));
		IceStorm::TopicPrx personposition_topic;
		if(!personposition_topic){
		try {
			personposition_topic = topicManager->create("PersonPosition");
		}
		catch (const IceStorm::TopicExists&) {
		//Another client created the topic
		try{
			personposition_topic = topicManager->retrieve("PersonPosition");
		}
		catch(const IceStorm::NoSuchTopic&)
		{
			//Error. Topic does not exist
			}
		}
		IceStorm::QoS qos;
		personposition_topic->subscribeAndGetPublisher(qos, personposition);
		}
		PersonPosition_adapter->activate();

		// Server adapter creation and publication
		cout << SERVER_FULL_NAME " started" << endl;

		// User defined QtGui elements ( main window, dialogs, etc )

#ifdef USE_QTGUI
		//ignoreInterrupt(); // Uncomment if you want the component to ignore console SIGINT signal (ctrl+c).
		a.setQuitOnLastWindowClosed( true );
#endif
		// Run QT Application Event Loop
		a.exec();
		status = EXIT_SUCCESS;
	}
	catch(const Ice::Exception& ex)
	{
		status = EXIT_FAILURE;

		cout << "[" << PROGRAM_NAME << "]: Exception raised on main thread: " << endl;
		cout << ex;

#ifdef USE_QTGUI
		a.quit();
#endif
		monitor->exit(0);
}

	return status;
}
Example #25
0
int
WarehouseServer::run(int argc, char* argv[])
{
    bool useSimpleEvictor = argc > 1 && string(argv[1]) == "simple";

    if(useSimpleEvictor)
    {
        cout << "Using SimpleEvictor" << endl;
    }
    else
    {
        cout << "Using Evictor implemented with IceUtil::Cache" << endl; 
    }

    Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("Warehouse");

    const string envName = "db";
    const string dbName = "items";

    {
        //
        // Open our database, a Freeze dictionary.
        //
        Freeze::ConnectionPtr connection = Freeze::createConnection(communicator(), envName);
        Database db(connection, dbName);

        if(db.empty())
        {
            cout << "Creating new database..." << flush;

            //
            // Populate database with objectCount entries.
            //
            ItemInfo info;

            connection->beginTransaction();

            for(int i = 0; i < objectCount; ++i)
            {
                ostringstream os;
                os << "P/N " << i;
                string name = os.str();
                info.description = "The description of " + name;
                info.unitPrice = i + 0.95f;
                info.quantityInStock = i;
                info.filler = string(5000, 'x');

                db.put(Database::value_type(name, info));
            }
            connection->currentTransaction()->commit();
            cout << "done" << endl;
        }
    }

    CurrentDatabase currentDb(communicator(), envName, dbName);

    //
    // This servant locator (evictor) will intercept all categories.
    //
    if(useSimpleEvictor)
    {
        adapter->addServantLocator(new SimpleEvictor(currentDb, evictorSize), "");
    }
    else
    {
        adapter->addServantLocator(new Evictor(currentDb, evictorSize), "");
    }

    adapter->activate();
    communicator()->waitForShutdown();
    return EXIT_SUCCESS;
}
Example #26
0
int ::doorbell::run(int argc, char* argv[])
{
#ifdef USE_QTGUI
	QApplication a(argc, argv);  // GUI application
#else
	QCoreApplication a(argc, argv);  // NON-GUI application
#endif
	int status=EXIT_SUCCESS;

	ros::init(argc, argv, "doorbell");

	AGMAgentTopicPrx agmagenttopic_proxy;
	SpeechPrx speech_proxy;
	TrajectoryRobot2DPrx trajectoryrobot2d_proxy;
	WelcomeVisitorPrx welcomevisitor_proxy;

	string proxy, tmp;
	initialize();


	try
	{
		if (not GenericMonitor::configGetString(communicator(), prefix, "SpeechProxy", proxy, ""))
		{
			cout << "[" << PROGRAM_NAME << "]: Can't read configuration for proxy SpeechProxy\n";
		}
		speech_proxy = SpeechPrx::uncheckedCast( communicator()->stringToProxy( proxy ) );
	}
	catch(const Ice::Exception& ex)
	{
		cout << "[" << PROGRAM_NAME << "]: Exception: " << ex;
		return EXIT_FAILURE;
	}
	rInfo("SpeechProxy initialized Ok!");
	mprx["SpeechProxy"] = (::IceProxy::Ice::Object*)(&speech_proxy);//Remote server proxy creation example


	try
	{
		if (not GenericMonitor::configGetString(communicator(), prefix, "TrajectoryRobot2DProxy", proxy, ""))
		{
			cout << "[" << PROGRAM_NAME << "]: Can't read configuration for proxy TrajectoryRobot2DProxy\n";
		}
		trajectoryrobot2d_proxy = TrajectoryRobot2DPrx::uncheckedCast( communicator()->stringToProxy( proxy ) );
	}
	catch(const Ice::Exception& ex)
	{
		cout << "[" << PROGRAM_NAME << "]: Exception: " << ex;
		return EXIT_FAILURE;
	}
	rInfo("TrajectoryRobot2DProxy initialized Ok!");
	mprx["TrajectoryRobot2DProxy"] = (::IceProxy::Ice::Object*)(&trajectoryrobot2d_proxy);//Remote server proxy creation example


	try
	{
		if (not GenericMonitor::configGetString(communicator(), prefix, "WelcomeVisitorProxy", proxy, ""))
		{
			cout << "[" << PROGRAM_NAME << "]: Can't read configuration for proxy WelcomeVisitorProxy\n";
		}
		welcomevisitor_proxy = WelcomeVisitorPrx::uncheckedCast( communicator()->stringToProxy( proxy ) );
	}
	catch(const Ice::Exception& ex)
	{
		cout << "[" << PROGRAM_NAME << "]: Exception: " << ex;
		return EXIT_FAILURE;
	}
	rInfo("WelcomeVisitorProxy initialized Ok!");
	mprx["WelcomeVisitorProxy"] = (::IceProxy::Ice::Object*)(&welcomevisitor_proxy);//Remote server proxy creation example

	IceStorm::TopicManagerPrx topicManager = IceStorm::TopicManagerPrx::checkedCast(communicator()->propertyToProxy("TopicManager.Proxy"));

	IceStorm::TopicPrx agmagenttopic_topic;
	while (!agmagenttopic_topic)
	{
		try
		{
			agmagenttopic_topic = topicManager->retrieve("AGMAgentTopic");
		}
		catch (const IceStorm::NoSuchTopic&)
		{
			try
			{
				agmagenttopic_topic = topicManager->create("AGMAgentTopic");
			}
			catch (const IceStorm::TopicExists&){
				// Another client created the topic.
			}
		}
	}
	Ice::ObjectPrx agmagenttopic_pub = agmagenttopic_topic->getPublisher()->ice_oneway();
	AGMAgentTopicPrx agmagenttopic = AGMAgentTopicPrx::uncheckedCast(agmagenttopic_pub);
	mprx["AGMAgentTopicPub"] = (::IceProxy::Ice::Object*)(&agmagenttopic);



	SpecificWorker *worker = new SpecificWorker(mprx);
	//Monitor thread
	SpecificMonitor *monitor = new SpecificMonitor(worker,communicator());
	QObject::connect(monitor, SIGNAL(kill()), &a, SLOT(quit()));
	QObject::connect(worker, SIGNAL(kill()), &a, SLOT(quit()));
	monitor->start();

	if ( !monitor->isRunning() )
		return status;
	
	while (!monitor->ready)
	{
		usleep(10000);
	}
	
	try
	{
		// Server adapter creation and publication
		if (not GenericMonitor::configGetString(communicator(), prefix, "CommonBehavior.Endpoints", tmp, ""))
		{
			cout << "[" << PROGRAM_NAME << "]: Can't read configuration for proxy CommonBehavior\n";
		}
		Ice::ObjectAdapterPtr adapterCommonBehavior = communicator()->createObjectAdapterWithEndpoints("commonbehavior", tmp);
		CommonBehaviorI *commonbehaviorI = new CommonBehaviorI(monitor );
		adapterCommonBehavior->add(commonbehaviorI, communicator()->stringToIdentity("commonbehavior"));
		adapterCommonBehavior->activate();




		// Server adapter creation and publication
		if (not GenericMonitor::configGetString(communicator(), prefix, "AGMCommonBehavior.Endpoints", tmp, ""))
		{
			cout << "[" << PROGRAM_NAME << "]: Can't read configuration for proxy AGMCommonBehavior";
		}
		Ice::ObjectAdapterPtr adapterAGMCommonBehavior = communicator()->createObjectAdapterWithEndpoints("AGMCommonBehavior", tmp);
		AGMCommonBehaviorI *agmcommonbehavior = new AGMCommonBehaviorI(worker);
		adapterAGMCommonBehavior->add(agmcommonbehavior, communicator()->stringToIdentity("agmcommonbehavior"));
		adapterAGMCommonBehavior->activate();
		cout << "[" << PROGRAM_NAME << "]: AGMCommonBehavior adapter created in port " << tmp << endl;





		// Server adapter creation and publication
		if (not GenericMonitor::configGetString(communicator(), prefix, "AGMExecutiveTopicTopic.Endpoints", tmp, ""))
		{
			cout << "[" << PROGRAM_NAME << "]: Can't read configuration for proxy AGMExecutiveTopicProxy";
		}
		Ice::ObjectAdapterPtr AGMExecutiveTopic_adapter = communicator()->createObjectAdapterWithEndpoints("agmexecutivetopic", tmp);
		AGMExecutiveTopicPtr agmexecutivetopicI_ = new AGMExecutiveTopicI(worker);
		Ice::ObjectPrx agmexecutivetopic = AGMExecutiveTopic_adapter->addWithUUID(agmexecutivetopicI_)->ice_oneway();
		IceStorm::TopicPrx agmexecutivetopic_topic;
		if(!agmexecutivetopic_topic){
		try {
			agmexecutivetopic_topic = topicManager->create("AGMExecutiveTopic");
		}
		catch (const IceStorm::TopicExists&) {
		//Another client created the topic
		try{
			agmexecutivetopic_topic = topicManager->retrieve("AGMExecutiveTopic");
		}
		catch(const IceStorm::NoSuchTopic&)
		{
			//Error. Topic does not exist
			}
		}
		IceStorm::QoS qos;
		agmexecutivetopic_topic->subscribeAndGetPublisher(qos, agmexecutivetopic);
		}
		AGMExecutiveTopic_adapter->activate();

		// Server adapter creation and publication
		cout << SERVER_FULL_NAME " started" << endl;

		// User defined QtGui elements ( main window, dialogs, etc )

#ifdef USE_QTGUI
		//ignoreInterrupt(); // Uncomment if you want the component to ignore console SIGINT signal (ctrl+c).
		a.setQuitOnLastWindowClosed( true );
#endif
		// Run QT Application Event Loop
		a.exec();
		status = EXIT_SUCCESS;
	}
	catch(const Ice::Exception& ex)
	{
		status = EXIT_FAILURE;

		cout << "[" << PROGRAM_NAME << "]: Exception raised on main thread: " << endl;
		cout << ex;

#ifdef USE_QTGUI
		a.quit();
#endif
		monitor->exit(0);
}

	return status;
}
Example #27
0
void
allTests(const Ice::CommunicatorPtr& communicator, const string& ref)
{
    ServerManagerPrx manager = ServerManagerPrx::checkedCast(communicator->stringToProxy(ref));
    TestLocatorPrx locator = TestLocatorPrx::uncheckedCast(communicator->getDefaultLocator());
    test(manager);

    TestLocatorRegistryPrx registry = TestLocatorRegistryPrx::checkedCast(locator->getRegistry());
    test(registry);

    cout << "testing stringToProxy... " << flush;
    Ice::ObjectPrx base = communicator->stringToProxy("test @ TestAdapter");
    Ice::ObjectPrx base2 = communicator->stringToProxy("test @ TestAdapter");
    Ice::ObjectPrx base3 = communicator->stringToProxy("test");
    Ice::ObjectPrx base4 = communicator->stringToProxy("ServerManager"); 
    Ice::ObjectPrx base5 = communicator->stringToProxy("test2");
    Ice::ObjectPrx base6 = communicator->stringToProxy("test @ ReplicatedAdapter");
    cout << "ok" << endl;

    cout << "testing ice_locator and ice_getLocator... " << flush;
    test(Ice::proxyIdentityEqual(base->ice_getLocator(), communicator->getDefaultLocator()));
    Ice::LocatorPrx anotherLocator = Ice::LocatorPrx::uncheckedCast(communicator->stringToProxy("anotherLocator"));
    base = base->ice_locator(anotherLocator);
    test(Ice::proxyIdentityEqual(base->ice_getLocator(), anotherLocator));
    communicator->setDefaultLocator(0);
    base = communicator->stringToProxy("test @ TestAdapter");
    test(!base->ice_getLocator());
    base = base->ice_locator(anotherLocator);
    test(Ice::proxyIdentityEqual(base->ice_getLocator(), anotherLocator));
    communicator->setDefaultLocator(locator);
    base = communicator->stringToProxy("test @ TestAdapter");
    test(Ice::proxyIdentityEqual(base->ice_getLocator(), communicator->getDefaultLocator())); 
    
    //
    // We also test ice_router/ice_getRouter (perhaps we should add a
    // test/Ice/router test?)
    //
    test(!base->ice_getRouter());
    Ice::RouterPrx anotherRouter = Ice::RouterPrx::uncheckedCast(communicator->stringToProxy("anotherRouter"));
    base = base->ice_router(anotherRouter);
    test(Ice::proxyIdentityEqual(base->ice_getRouter(), anotherRouter));
    Ice::RouterPrx router = Ice::RouterPrx::uncheckedCast(communicator->stringToProxy("dummyrouter"));
    communicator->setDefaultRouter(router);
    base = communicator->stringToProxy("test @ TestAdapter");
    test(Ice::proxyIdentityEqual(base->ice_getRouter(), communicator->getDefaultRouter()));
    communicator->setDefaultRouter(0);
    base = communicator->stringToProxy("test @ TestAdapter");
    test(!base->ice_getRouter());
    cout << "ok" << endl;

    cout << "starting server... " << flush;
    manager->startServer();
    cout << "ok" << endl;

    cout << "testing checked cast... " << flush;
    TestIntfPrx obj = TestIntfPrx::checkedCast(base);
    test(obj);
    TestIntfPrx obj2 = TestIntfPrx::checkedCast(base2);
    test(obj2);
    TestIntfPrx obj3 = TestIntfPrx::checkedCast(base3);
    test(obj3);
    ServerManagerPrx obj4 = ServerManagerPrx::checkedCast(base4);
    test(obj4);
    TestIntfPrx obj5 = TestIntfPrx::checkedCast(base5);
    test(obj5);
    TestIntfPrx obj6 = TestIntfPrx::checkedCast(base6);
    test(obj6);
    cout << "ok" << endl;
 
    cout << "testing id@AdapterId indirect proxy... " << flush;
    obj->shutdown();
    manager->startServer();
    try
    {
        obj2->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    cout << "ok" << endl;    
    
    cout << "testing id@ReplicaGroupId indirect proxy... " << flush;
    obj->shutdown();
    manager->startServer();
    try
    {
        obj6->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    cout << "ok" << endl;    

    cout << "testing identity indirect proxy... " << flush;
    obj->shutdown();
    manager->startServer();
    try
    {
        obj3->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    try
    {
        obj2->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    obj->shutdown();
    manager->startServer();
    try
    {
        obj2->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    try
    {
        obj3->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    obj->shutdown();
    manager->startServer();

    try
    {
        obj2->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    obj->shutdown();
    manager->startServer();
    try
    {
        obj3->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    obj->shutdown();
    manager->startServer();
    try
    {
        obj2->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    obj->shutdown();
    manager->startServer();

    try
    {
        obj5->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    cout << "ok" << endl;

    cout << "testing proxy with unknown identity... " << flush;
    try
    {
        base = communicator->stringToProxy("unknown/unknown");
        base->ice_ping();
        test(false);
    }
    catch (const Ice::NotRegisteredException& ex)
    {
        test(ex.kindOfObject == "object");
        test(ex.id == "unknown/unknown");
    }
    cout << "ok" << endl;

    cout << "testing proxy with unknown adapter... " << flush;
    try
    {
        base = communicator->stringToProxy("test @ TestAdapterUnknown");
        base->ice_ping();
        test(false);
    }
    catch (const Ice::NotRegisteredException& ex)
    {
        test(ex.kindOfObject == "object adapter");
        test(ex.id == "TestAdapterUnknown");
    }
    cout << "ok" << endl;

    cout << "testing locator cache timeout... " << flush;

    int count = locator->getRequestCount();
    communicator->stringToProxy("test@TestAdapter")->ice_locatorCacheTimeout(0)->ice_ping(); // No locator cache.
    test(++count == locator->getRequestCount());
    communicator->stringToProxy("test@TestAdapter")->ice_locatorCacheTimeout(0)->ice_ping(); // No locator cache.
    test(++count == locator->getRequestCount());
    communicator->stringToProxy("test@TestAdapter")->ice_locatorCacheTimeout(1)->ice_ping(); // 1s timeout.
    test(count == locator->getRequestCount());
    IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(1300));
    communicator->stringToProxy("test@TestAdapter")->ice_locatorCacheTimeout(1)->ice_ping(); // 1s timeout.
    test(++count == locator->getRequestCount());

    communicator->stringToProxy("test")->ice_locatorCacheTimeout(0)->ice_ping(); // No locator cache.
    count += 2;
    test(count == locator->getRequestCount());
    communicator->stringToProxy("test")->ice_locatorCacheTimeout(1)->ice_ping(); // 1s timeout
    test(count == locator->getRequestCount());
    IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(1300));
    communicator->stringToProxy("test")->ice_locatorCacheTimeout(1)->ice_ping(); // 1s timeout
    count += 2;
    test(count == locator->getRequestCount());

    communicator->stringToProxy("test@TestAdapter")->ice_locatorCacheTimeout(-1)->ice_ping(); 
    test(count == locator->getRequestCount());
    communicator->stringToProxy("test")->ice_locatorCacheTimeout(-1)->ice_ping();
    test(count == locator->getRequestCount());
    communicator->stringToProxy("test@TestAdapter")->ice_ping(); 
    test(count == locator->getRequestCount());
    communicator->stringToProxy("test")->ice_ping();
    test(count == locator->getRequestCount());

    test(communicator->stringToProxy("test")->ice_locatorCacheTimeout(99)->ice_getLocatorCacheTimeout() == 99);

    cout << "ok" << endl;

    cout << "testing proxy from server... " << flush;
    obj = TestIntfPrx::checkedCast(communicator->stringToProxy("test@TestAdapter"));
    HelloPrx hello = obj->getHello();
    test(hello->ice_getAdapterId() == "TestAdapter");
    hello->sayHello();
    hello = obj->getReplicatedHello();
    test(hello->ice_getAdapterId() == "ReplicatedAdapter");
    hello->sayHello();
    cout << "ok" << endl;

    cout << "testing locator request queuing... " << flush;
    hello = obj->getReplicatedHello()->ice_locatorCacheTimeout(0)->ice_connectionCached(false);
    count = locator->getRequestCount();
    hello->ice_ping();
    test(++count == locator->getRequestCount());
    int i;

    list<Ice::AsyncResultPtr>  results;
    AMICallbackPtr cb = new AMICallback;
    for(i = 0; i < 1000; i++)
    {
        Ice::AsyncResultPtr result = hello->begin_sayHello(
            newCallback_Hello_sayHello(cb, &AMICallback::response1, &AMICallback::exception1));
        results.push_back(result);
    }
    while(!results.empty())
    {
        Ice::AsyncResultPtr result = results.front();
        results.pop_front();
        result->waitForCompleted();
    }
    test(locator->getRequestCount() > count && locator->getRequestCount() < count + 999);
    if(locator->getRequestCount() > count + 800)
    {
        cout << "queuing = " << locator->getRequestCount() - count;
    }
    count = locator->getRequestCount();
    hello = hello->ice_adapterId("unknown");
    for(i = 0; i < 1000; i++)
    {
        Ice::AsyncResultPtr result = hello->begin_sayHello(
            newCallback_Hello_sayHello(cb, &AMICallback::response2, &AMICallback::exception2));
        results.push_back(result);
    }
    while(!results.empty())
    {
        Ice::AsyncResultPtr result = results.front();
        results.pop_front();
        result->waitForCompleted();
    }
    // Take into account the retries.
    test(locator->getRequestCount() > count && locator->getRequestCount() < count + 1999);
    if(locator->getRequestCount() > count + 800)
    {
        cout << "queuing = " << locator->getRequestCount() - count;
    }
    cout << "ok" << endl;

    cout << "testing adapter locator cache... " << flush;
    try
    {
        communicator->stringToProxy("test@TestAdapter3")->ice_ping();
        test(false);
    }
    catch(const Ice::NotRegisteredException& ex)
    {
        test(ex.kindOfObject == "object adapter");
        test(ex.id == "TestAdapter3");
    }
    registry->setAdapterDirectProxy("TestAdapter3", locator->findAdapterById("TestAdapter"));
    try
    {
        communicator->stringToProxy("test@TestAdapter3")->ice_ping();
        registry->setAdapterDirectProxy("TestAdapter3", communicator->stringToProxy("dummy:tcp"));
        communicator->stringToProxy("test@TestAdapter3")->ice_ping();
    }
    catch(const Ice::LocalException&)
    {
        test(false);
    }
    
    try
    {
        communicator->stringToProxy("test@TestAdapter3")->ice_locatorCacheTimeout(0)->ice_ping();
        test(false);
    }
    catch(const Ice::LocalException&)
    {
    }
    try
    {
        communicator->stringToProxy("test@TestAdapter3")->ice_ping();
        test(false);
    }
    catch(const Ice::LocalException&)
    {   
    }
    registry->setAdapterDirectProxy("TestAdapter3", locator->findAdapterById("TestAdapter"));
    try
    {
        communicator->stringToProxy("test@TestAdapter3")->ice_ping();
    }
    catch(const Ice::LocalException&)
    {
        test(false);
    }
    cout << "ok" <<endl;

    cout << "testing well-known object locator cache... " << flush;

    registry->addObject(communicator->stringToProxy("test3@TestUnknown"));
    try
    {
        communicator->stringToProxy("test3")->ice_ping();
        test(false);
    }
    catch(const Ice::NotRegisteredException& ex)
    {
        test(ex.kindOfObject == "object adapter");
        test(ex.id == "TestUnknown");
    }
    registry->addObject(communicator->stringToProxy("test3@TestAdapter4")); // Update
    registry->setAdapterDirectProxy("TestAdapter4", communicator->stringToProxy("dummy:tcp"));
    try
    {
        communicator->stringToProxy("test3")->ice_ping();
        test(false);
    }
    catch(const Ice::LocalException&)
    {
    }
    registry->setAdapterDirectProxy("TestAdapter4", locator->findAdapterById("TestAdapter"));
    try
    {
        communicator->stringToProxy("test3")->ice_ping();
    }
    catch(const Ice::LocalException&)
    {
        test(false);
    }

    registry->setAdapterDirectProxy("TestAdapter4", communicator->stringToProxy("dummy:tcp"));
    try
    {
        communicator->stringToProxy("test3")->ice_ping();
    }
    catch(const Ice::LocalException&)
    {
        test(false);
    }

    try
    {
        communicator->stringToProxy("test@TestAdapter4")->ice_locatorCacheTimeout(0)->ice_ping();
        test(false);
    }
    catch(const Ice::LocalException&)
    {
    }
    try
    {
        communicator->stringToProxy("test@TestAdapter4")->ice_ping();
        test(false);
    }
    catch(const Ice::LocalException&)
    {   
    }
    try
    {
        communicator->stringToProxy("test3")->ice_ping();
        test(false);
    }
    catch(const Ice::LocalException&)
    {
    }
    registry->addObject(communicator->stringToProxy("test3@TestAdapter"));
    try
    {
        communicator->stringToProxy("test3")->ice_ping();
    }
    catch(const Ice::LocalException&)
    {
        test(false);
    }
    
    registry->addObject(communicator->stringToProxy("test4"));
    try
    {
        communicator->stringToProxy("test4")->ice_ping();
        test(false);
    }
    catch(const Ice::NoEndpointException&)
    {
    }
    cout << "ok" << endl;

    cout << "testing locator cache background updates... " << flush;
    {
        Ice::InitializationData initData;
        initData.properties = communicator->getProperties()->clone();
        initData.properties->setProperty("Ice.BackgroundLocatorCacheUpdates", "1");
        Ice::CommunicatorPtr ic = Ice::initialize(initData);

        registry->setAdapterDirectProxy("TestAdapter5", locator->findAdapterById("TestAdapter"));
        registry->addObject(communicator->stringToProxy("test3@TestAdapter"));

        int count = locator->getRequestCount();
        ic->stringToProxy("test@TestAdapter5")->ice_locatorCacheTimeout(0)->ice_ping(); // No locator cache.
        ic->stringToProxy("test3")->ice_locatorCacheTimeout(0)->ice_ping(); // No locator cache.
        count += 3;
        test(count == locator->getRequestCount());
        registry->setAdapterDirectProxy("TestAdapter5", 0);
        registry->addObject(communicator->stringToProxy("test3:tcp"));
        ic->stringToProxy("test@TestAdapter5")->ice_locatorCacheTimeout(10)->ice_ping(); // 10s timeout.
        ic->stringToProxy("test3")->ice_locatorCacheTimeout(10)->ice_ping(); // 10s timeout.
        test(count == locator->getRequestCount());
        IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(1200));

        // The following request should trigger the background updates but still use the cached endpoints
        // and therefore succeed.
        ic->stringToProxy("test@TestAdapter5")->ice_locatorCacheTimeout(1)->ice_ping(); // 1s timeout.
        ic->stringToProxy("test3")->ice_locatorCacheTimeout(1)->ice_ping(); // 1s timeout.

        try
        {
            while(true)
            {
                ic->stringToProxy("test@TestAdapter5")->ice_locatorCacheTimeout(1)->ice_ping(); // 1s timeout.
                IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(10));
            }
        }
        catch(const Ice::LocalException&)
        {
            // Expected to fail once they endpoints have been updated in the background.
        }
        try
        {
            while(true)
            {
                ic->stringToProxy("test3")->ice_locatorCacheTimeout(1)->ice_ping(); // 1s timeout.
                IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(10));
            }
        }
        catch(const Ice::LocalException&)
        {
            // Expected to fail once they endpoints have been updated in the background.
        }
        ic->destroy();
    }
    cout << "ok" << endl;

    cout << "testing proxy from server after shutdown... " << flush;
    hello = obj->getReplicatedHello();
    obj->shutdown();
    manager->startServer();
    hello->sayHello();
    cout << "ok" << endl;

    cout << "testing object migration... " << flush;
    hello = HelloPrx::checkedCast(communicator->stringToProxy("hello"));
    obj->migrateHello();
    hello->ice_getConnection()->close(false);
    hello->sayHello();
    obj->migrateHello();
    hello->sayHello();
    obj->migrateHello();
    hello->sayHello();
    cout << "ok" << endl;

    cout << "testing locator encoding resolution... " << flush;

    hello = HelloPrx::checkedCast(communicator->stringToProxy("hello"));
    count = locator->getRequestCount();
    communicator->stringToProxy("test@TestAdapter")->ice_encodingVersion(Ice::Encoding_1_1)->ice_ping();
    test(count == locator->getRequestCount());
    communicator->stringToProxy("test@TestAdapter10")->ice_encodingVersion(Ice::Encoding_1_0)->ice_ping();
    test(++count == locator->getRequestCount());
    communicator->stringToProxy("test -e 1.0@TestAdapter10-2")->ice_ping();
    test(++count == locator->getRequestCount());

    cout << "ok" << endl;

    cout << "shutdown server... " << flush;
    obj->shutdown();
    cout << "ok" << endl;

    cout << "testing whether server is gone... " << flush;
    try
    {
        obj2->ice_ping();
        test(false);
    }
    catch(const Ice::LocalException&)
    {
    }
    try
    {
        obj3->ice_ping();
        test(false);
    }
    catch(const Ice::LocalException&)
    {
    }
    try
    {
        obj5->ice_ping();
        test(false);
    }
    catch(const Ice::LocalException&)
    {
    }
    cout << "ok" << endl;

    string host = communicator->getProperties()->getPropertyAsIntWithDefault("Ice.IPv6", 0) == 0 ? 
            "127.0.0.1" : "\"0:0:0:0:0:0:0:1\"";
    if(communicator->getProperties()->getProperty("Ice.Default.Host") == host)
    {
        cout << "testing indirect proxies to collocated objects... " << flush;
        //
        // Set up test for calling a collocated object through an indirect, adapterless reference.
        //
        Ice::PropertiesPtr properties = communicator->getProperties();
        properties->setProperty("Ice.PrintAdapterReady", "0");
        Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("Hello", "default");
        adapter->setLocator(locator);

        Ice::Identity id;
        id.name = IceUtil::generateUUID();
        registry->addObject(adapter->add(new HelloI, id));
        adapter->activate();
        
        HelloPrx helloPrx = HelloPrx::checkedCast(communicator->stringToProxy(communicator->identityToString(id)));
        test(!helloPrx->ice_getConnection());

        adapter->deactivate();
        cout << "ok" << endl;
    }
    cout << "shutdown server manager... " << flush;
    manager->shutdown();
    cout << "ok" << endl;
}
Example #28
0
void
ServerManagerI::startServer(const Ice::Current&)
{
    for(::std::vector<Ice::CommunicatorPtr>::const_iterator i = _communicators.begin(); i != _communicators.end(); ++i)
    {
        (*i)->waitForShutdown();
        (*i)->destroy();
    }
    _communicators.clear();

    //
    // Simulate a server: create a new communicator and object
    // adapter. The object adapter is started on a system allocated
    // port. The configuration used here contains the Ice.Locator
    // configuration variable. The new object adapter will register
    // its endpoints with the locator and create references containing
    // the adapter id instead of the endpoints.
    //
    Ice::CommunicatorPtr serverCommunicator = Ice::initialize(_initData);
    _communicators.push_back(serverCommunicator);

    //
    // Use fixed port to ensure that OA re-activation doesn't re-use previous port from
    // another OA (e.g.: TestAdapter2 is re-activated using port of TestAdapter).
    //
    int nRetry = 10;
    while(--nRetry > 0)
    {
        Ice::ObjectAdapterPtr adapter;
        Ice::ObjectAdapterPtr adapter2;
        try
        {
            Ice::PropertiesPtr props = _initData.properties;
            serverCommunicator->getProperties()->setProperty("TestAdapter.Endpoints",
                                                             getTestEndpoint(props, _nextPort++));
            serverCommunicator->getProperties()->setProperty("TestAdapter2.Endpoints",
                                                             getTestEndpoint(props, _nextPort++));

            adapter = serverCommunicator->createObjectAdapter("TestAdapter");
            adapter2 = serverCommunicator->createObjectAdapter("TestAdapter2");

            Ice::ObjectPrxPtr locator = serverCommunicator->stringToProxy("locator:" + getTestEndpoint(props, 0));
            adapter->setLocator(ICE_UNCHECKED_CAST(Ice::LocatorPrx, locator));
            adapter2->setLocator(ICE_UNCHECKED_CAST(Ice::LocatorPrx, locator));

            Ice::ObjectPtr object = ICE_MAKE_SHARED(TestI, adapter, adapter2, _registry);
            _registry->addObject(adapter->add(object, Ice::stringToIdentity("test")));
            _registry->addObject(adapter->add(object, Ice::stringToIdentity("test2")));
            adapter->add(object, Ice::stringToIdentity("test3"));

            adapter->activate();
            adapter2->activate();
            break;
        }
        catch(const Ice::SocketException&)
        {
            if(nRetry == 0)
            {
                throw;
            }

            // Retry, if OA creation fails with EADDRINUSE (this can occur when running with JS web
            // browser clients if the driver uses ports in the same range as this test, ICE-8148)
            if(adapter)
            {
                adapter->destroy();
            }
            if(adapter2)
            {
                adapter2->destroy();
            }
        }
    }
}
int objectDetectionComp::run(int argc, char* argv[])
{
#ifdef USE_QTGUI
	QApplication a(argc, argv);  // GUI application
#else
	QCoreApplication a(argc, argv);  // NON-GUI application
#endif
	int status=EXIT_SUCCESS;

	// Remote server proxy access example
	// RemoteComponentPrx remotecomponent_proxy;
	InnerModelManagerPrx innermodelmanager_proxy;
RGBDPrx rgbd_proxy;


	string proxy;

	// User variables


	initialize();

	// Remote server proxy creation example
	// try
	// {
	// 	// Load the remote server proxy
	//	proxy = getProxyString("RemoteProxy");
	//	remotecomponent_proxy = RemotePrx::uncheckedCast( communicator()->stringToProxy( proxy ) );
	//	if( !remotecomponent_proxy )
	//	{
	//		rInfo(QString("Error loading proxy!"));
	//		return EXIT_FAILURE;
	//	}
	//catch(const Ice::Exception& ex)
	//{
	//	cout << "[" << PROGRAM_NAME << "]: Exception: " << ex << endl;
	//	return EXIT_FAILURE;
	//}
	//rInfo("RemoteProxy initialized Ok!");
	// 	// Now you can use remote server proxy (remotecomponent_proxy) as local object
	//Remote server proxy creation example
	try
	{
		innermodelmanager_proxy = InnerModelManagerPrx::uncheckedCast( communicator()->stringToProxy( getProxyString("InnerModelManagerProxy") ) );
	}
	catch(const Ice::Exception& ex)
	{
		cout << "[" << PROGRAM_NAME << "]: Exception: " << ex;
		return EXIT_FAILURE;
	}
	rInfo("InnerModelManagerProxy initialized Ok!");
	mprx["InnerModelManagerProxy"] = (::IceProxy::Ice::Object*)(&innermodelmanager_proxy);//Remote server proxy creation example
	try
	{
		rgbd_proxy = RGBDPrx::uncheckedCast( communicator()->stringToProxy( getProxyString("RGBDProxy") ) );
	}
	catch(const Ice::Exception& ex)
	{
		cout << "[" << PROGRAM_NAME << "]: Exception: " << ex;
		return EXIT_FAILURE;
	}
	rInfo("RGBDProxy initialized Ok!");
	mprx["RGBDProxy"] = (::IceProxy::Ice::Object*)(&rgbd_proxy);
	IceStorm::TopicManagerPrx topicManager = IceStorm::TopicManagerPrx::checkedCast(communicator()->propertyToProxy("TopicManager.Proxy"));
	
	
	GenericWorker *worker = new SpecificWorker(mprx);
	//Monitor thread
	GenericMonitor *monitor = new SpecificMonitor(worker,communicator());
	QObject::connect(monitor,SIGNAL(kill()),&a,SLOT(quit()));
	QObject::connect(worker,SIGNAL(kill()),&a,SLOT(quit()));
	monitor->start();
	
	if ( !monitor->isRunning() )
		return status;
	try
	{
		// Server adapter creation and publication
		Ice::ObjectAdapterPtr adapterCommonBehavior = communicator()->createObjectAdapter("CommonBehavior");
		CommonBehaviorI *commonbehaviorI = new CommonBehaviorI(monitor );
		adapterCommonBehavior->add(commonbehaviorI, communicator()->stringToIdentity("commonbehavior"));
		adapterCommonBehavior->activate();
		// Server adapter creation and publication
    	Ice::ObjectAdapterPtr AprilTags_adapter = communicator()->createObjectAdapter("AprilTagsTopic");
    	AprilTagsPtr apriltagsI_ = new AprilTagsI(worker);
    	Ice::ObjectPrx apriltags_proxy = AprilTags_adapter->addWithUUID(apriltagsI_)->ice_oneway();
    	IceStorm::TopicPrx apriltags_topic;
    	if(!apriltags_topic){
	    	try {
	    		apriltags_topic = topicManager->create("AprilTags");
	    	}
	    	catch (const IceStorm::TopicExists&) {
	    	  	//Another client created the topic
	    	  	try{
	       			apriltags_topic = topicManager->retrieve("AprilTags");
	    	  	}catch(const IceStorm::NoSuchTopic&){
	    	  	  	//Error. Topic does not exist
				}
	    	}
	    	IceStorm::QoS qos;
	      	apriltags_topic->subscribeAndGetPublisher(qos, apriltags_proxy);
    	}
    	AprilTags_adapter->activate();
    	// Server adapter creation and publication
		Ice::ObjectAdapterPtr adapterobjectDetection = communicator()->createObjectAdapter("objectDetectionComp");
		objectDetectionI *objectdetection = new objectDetectionI(worker);
		adapterobjectDetection->add(objectdetection, communicator()->stringToIdentity("objectdetection"));

		adapterobjectDetection->activate();
		cout << SERVER_FULL_NAME " started" << endl;

		// User defined QtGui elements ( main window, dialogs, etc )

#ifdef USE_QTGUI
		//ignoreInterrupt(); // Uncomment if you want the component to ignore console SIGINT signal (ctrl+c).
		a.setQuitOnLastWindowClosed( true );
#endif
		// Run QT Application Event Loop
		a.exec();
		status = EXIT_SUCCESS;
	}
	catch(const Ice::Exception& ex)
	{
		status = EXIT_FAILURE;

		cout << "[" << PROGRAM_NAME << "]: Exception raised on main thread: " << endl;
		cout << ex;

#ifdef USE_QTGUI
		a.quit();
#endif
		monitor->exit(0);
}

	return status;
}
Example #30
0
int
PhoneBookCollocated::run(int argc, char* argv[])
{
    Ice::PropertiesPtr properties = communicator()->getProperties();

    //
    // Create and install a factory for contacts.
    //
    ContactFactoryPtr contactFactory = new ContactFactory();
    communicator()->addValueFactory(contactFactory, Demo::Contact::ice_staticId());

    //
    // Create the name index.
    //
    NameIndexPtr index = new NameIndex("name");
    vector<Freeze::IndexPtr> indices;
    indices.push_back(index);

    //
    // Create an object adapter, use the evictor as servant locator.
    //
    Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("PhoneBook");

    //
    // Create an evictor for contacts.
    //
    // When Freeze.Evictor.db.contacts.PopulateEmptyIndices is not 0
    // and the Name index is empty, Freeze will traverse the database
    // to recreate the index during createXXXEvictor(). Therefore the
    // factories for the objects stored in evictor (contacts here)
    // must be registered before the call to createXXXEvictor().
    //
    Freeze::EvictorPtr evictor = Freeze::createBackgroundSaveEvictor(adapter, _envName, "contacts", 0, indices);
    adapter->addServantLocator(evictor, "contact");

    Ice::Int evictorSize = properties->getPropertyAsInt("EvictorSize");
    if(evictorSize > 0)
    {
        evictor->setSize(evictorSize);
    }

    //
    // Completes the initialization of the contact factory. Note that ContactI/
    // ContactFactoryI uses this evictor only when a Contact is destroyed,
    // which cannot happen during createXXXEvictor().
    //
    contactFactory->setEvictor(evictor);

    //
    // Create the phonebook, and add it to the Object Adapter.
    //
    PhoneBookIPtr phoneBook = new PhoneBookI(evictor, contactFactory, index);
    adapter->add(phoneBook, communicator()->stringToIdentity("phonebook"));

    //
    // Everything ok, let's go.
    //
    int runParser(int, char*[], const Ice::CommunicatorPtr&);
    int status = runParser(argc, argv, communicator());
    adapter->destroy();

    return status;
}